N
N
nedevochka2022-03-21 13:19:46
Java
nedevochka, 2022-03-21 13:19:46

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

1 answer(s)
O
Orkhan, 2022-03-21
@nedevochka

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 question

Ask a Question

731 491 924 answers to any question