How to go to a new line only after the last qualifying number has been printed (java)

My input is 5 50 60 140 200 75 100

So my current output is:
50,60,75,

But I need my output to go to a new line after 75, is printed, and it isn’t. I am not sure where I am messing up, so if anyone could help I would appreciate it!

    import java.util.Scanner; 

    public class LabProgram {
    public static void main(String[] args) {
        
          Scanner scnr = new Scanner(System.in);
          
          int userInputs = scnr.nextInt();
          
          int[] userValues = new int[userInputs];   // List of integers from input

          for (int i = 0; i < userInputs; i++) {
              userValues[i] = scnr.nextInt();
          }
          
          /* Type your code here. */
      int stopping = scnr.nextInt();
      
    
      for (int i = 0; i < stopping; ++i) {
          if (userValues[i] <= stopping) {
              System.out.print(userValues[i] + ",");
             
              
          }
        
      
       
    }
      System.out.println("");
}
}

I have tried adding ln to the print statement, but that made it print after each individual value, which I don’t want. Same result happended with \n. My latest attempt has been moving a separate SOPln statement outside of the for loop, but that didn’t work.

for (int i = 0; i < userInputs; i++) {
    System.out.print(userValues[i] + ",");

    if (userValues[i] == stopping) {
        System.out.println(); // Start a new line when the stopping value is encountered
        break; // Exit the loop when the stopping value is encountered
    }
}

Leave a Comment