1

I need to print this array without having he last array item print with a comma. I have tried setting i to be less than 3 but it will not work. :/ I cannot get this last array entry to print all by itself. This is homework so please do not feel the need to give me the answer just a nudge in the right direction would help!

    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 = 0;

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

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

      System.out.println("");

      return;
   }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Eternal Vapor
  • 71
  • 3
  • 7
  • 15
  • what output are you expecting ? – apgp88 Mar 22 '15 at 01:28
  • I don't see where you print the coma. Your if clause inside for has no effect (you have ; just after the closing bracket ), so system.out.print is always called. – Zielu Mar 22 '15 at 01:30

1 Answers1

1

Since you just want a nudge in the correct direction,

if(hourlyTemp[i] < NUM_VALS);

Remove the semicolon at the end of that if (it terminates the if body). Also, I suggest you always use braces

if(hourlyTemp[i] < NUM_VALS) {
    // ...
}

I also think you wanted i + 1 < NUM_VALS and System.out.print(", "); Of course, you might also use

System.out.println(Arrays.toString(hourlyTemp));

Edit Based on your comment below you seem to want something like

for (i = 0; i < NUM_VALS; i++) {
    if (i != 0) {
        System.out.print(", ");
    }
    System.out.print(hourlyTemp[i]);
}
System.out.println("");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Yes that code turned out to be messed up. That was not my original code I must have accidentally messed it up. I edited my code with those tips and I seem to be getting the code to - for(i = 0; i + 1 < NUM_VALS; i++){ if(i < NUM_VALS) System.out.print(hourlyTemp[i] + ", "); } I am expecting to see {90, 92, 94, 95} but i get {90, 92, 94,}. Im now more lost lol – Eternal Vapor Mar 22 '15 at 02:00
  • That worked exactly as expected. Would the if statement keep it from getting a comma on element 0? Iv been staring at code all day maybe im just starting to lose the ability to think logically hah. – Eternal Vapor Mar 22 '15 at 02:15
  • Yes, the first element (0). – Elliott Frisch Mar 22 '15 at 02:49