I want to run a block of code which repeats until user wants to exit themself. So I put it into a for loop where it’ll keep iterating until user enters 0 as a choice. It works fine in the first iteration but as soon as it goes for the second iteration, it stops asking for values from user, and just proceeds with null
. Here’s the main()
‘s code. I’ve only included the relevant code lines.
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String text;
for(int isRunning= 1; isRunning != 0;){
System.out.println("Enter a string value");
text = sc.nextLine();
System.out.println(text);
System.out.println("Enter 0 if you want to exit, or enter any other number if you want to proceed again");
isRunning= sc.nextInt();
}
}
I was expecting an output like:
Enter a string value
Hello World
Hello World
Enter 0 if you want to exit, or enter any other number if you want to proceed again
3
Enter a string value
Hello World
Hello World
Enter 0 if you want to exit, or enter any other number if you want to proceed again
0
But the expected output was:
Enter a string value
Hello World
Hello World
Enter 0 if you want to exit, or enter any other number if you want to proceed again
3
Enter a string value
Enter 0 if you want to exit, or enter any other number if you want to proceed again
3
Enter a string value
Enter 0 if you want to exit, or enter any other number if you want to proceed again
UGHHH
Please guide me through this. Why does the scanner class stops taking output after the first iteration?
Thanks in advance!