Skip to content
Advertisement

Java print() not printing until println() NetBeans

I just installed NetBeans 12.6 today, and I’m having an issue with System.out.print() in the code I pasted below. For some reason, the print() in removeValue doesn’t print until the println() in the for loop in main. When I ran this code in BlueJ, everything worked fine. Is something wrong with my NetBeans or ??

Desired output would look something like:

Enter index: 2
1
3

Instead, it looks like:

2
Enter index: 1
3

package e.mavenproject1;
import java.util.Scanner;

public class NewClass {
    static Scanner input = new Scanner(System.in);
    
    public static void main(String[]args) {
        int[] array = {1, 2, 3};
  
        array = removeValue(array);
    
        for (int i = 0; i < array.length; i++) {
           System.out.println(array[i]);
        }
    }

    public static int[] removeValue(int[] array) {
         System.out.print("Enter index: ");
         int index = input.nextInt() - 1;

         int[] copy = new int[array.length - 1];

         for (int i = 0, j = 0; i < array.length; i++) {
             if (i != index) {
                 copy[j++] = array[i];
             }
         }
         return copy;
     }
}

Advertisement

Answer

print() adds a string to the PrintStream without flushing it. If you want it flushed you need to add the flush() command after it. The println() automatically flushes it so this will also work. Also, to be clear, this is not a bug.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement