Click here to Skip to main content
13,189,884 members (51,380 online)
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(", ");
         //}
      }
      
 
      System.out.println("");
   }
}
Posted 4 days ago
Updated 4 days ago
Rate this: bad
 
good
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(", ");
         System.out.print(hourlyTemp[i]);
      }
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.
  Permalink  
Comments
Member 13458860 4 days ago
   
@OriginalGriff wont that make a comma come before the numbers even start? like- , 90, 92, 94, 95
OriginalGriff 4 days ago
   
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
 
good
Please Sign up or sign in to vote.

Solution 2

Assuming there is at least 1 item to print, I do this way:
System.out.print(hourlyTemp[0]);
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.
  Permalink  

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 |
Web01 | 2.8.171016.2 | Last Updated 12 Oct 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

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