Click here to Skip to main content
13,665,166 members
Rate this:
Please Sign up or sign in to vote.
See more:
My codes output should end with the last element, without a comma or space at the end. I'm having trouble figuring out how to stop it from happening.

What I have tried:

import java.util.Scanner;

public class PrintWithComma {
   public static void main (String [] args) {
      final int NUM_VALS = 4;
      int[] hourlyTemp = new int[NUM_VALS];
      int i;

      hourlyTemp[0] = 90;
      hourlyTemp[1] = 92;
      hourlyTemp[2] = 94;
      hourlyTemp[3] = 95;

      for(i = 0; i < NUM_VALS; i++)
         System.out.print(hourlyTemp[i] + ", ");
        // if (i <= NUM_VALS)
        // {
          //  System.out.print(", ");

Posted 12-Oct-17 5:07am
Updated 12-Oct-17 10:14am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Two ways:
The first is to manually put the separator in front of the second and subsequant items:
for(i = 0; i < NUM_VALS; i++)
         if (i > 0)
             System.out.Print(", ");
There are many other ways to do that code, but that's the clearest.
The other is to use a Join function: What's the best way to build a string of delimited items in Java? - Stack Overflow[^] And then print that.
12-Oct-17 11:24am
@OriginalGriff wont that make a comma come before the numbers even start? like- , 90, 92, 94, 95
OriginalGriff 12-Oct-17 11:34am
No: try it.
Because the loop starts with zero and that is specifically excluded for the comma, you get
90, 92, 93, ... 98, 99
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Assuming there is at least 1 item to print, I do this way:
for(i = 1; i < NUM_VALS; i++)
  System.out.print(", " + hourlyTemp[i]);

By doing this way, it remove the need to have a test inside the loop.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web01-2016 | 2.8.180810.1 | Last Updated 12 Oct 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100