Answer the question
In order to leave comments, you need to log in
The for loop with console input is executed twice, no debugging?
I use NetBeans, implement this loop, if you enter a value other than S, then the console displays
Pass #0
Pass #1
That is, the loop runs twice, I did not understand the program execution sequence, why it runs twice
I tried to use the NetBeans debugger to trace the execution of actions, the debugger just takes a long time to load, apparently, when input is made through the console, the debugger will not work or you need to use some other approach.
public class JavaApplication51 {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
throws java.io.IOException {
int i;
System.out.println("Press the S key to stop");
for(i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
Answer the question
In order to leave comments, you need to log in
Good afternoon!
I recommend using Intellij IDEA Community Edition or Eclipse, although this is irrelevant to the problem.
Regarding your question, the 'Enter' character is also a character. From here and 2 passes
Try:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
char symbol = scanner.next().charAt(0);
if (symbol == 'S') {
System.exit(-1);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question