Java loop issue

What is the error in the following code?

 while ((char t==(char) System.in.read())!='0')
+3
source share
4 answers

You cannot declare a new variable in a loop while.

    while (boolean always = true) {
    } // DOES NOT COMPILE!!!

You need to declare a variable before and outside the loop, so something like this is possible:

    boolean always = true;
    while (always) {
        break;
    } // compiles fine!

    // always is still in scope after the loop!
    always = !always;

In this sense, the loop foris unique: you can declare a new local variable whose scope is limited to this loop:

    for (boolean always = true; always; ) {
        break;
    } // compiles fine!

    // always is no longer declared after the loop!
    always = !always; // DOES NOT COMPILE!

However, looking at what you are doing, you can look java.util.Scanner. I suspect that it will serve your needs much better.


Example

Scanner , 0. . , hasNextInt() Integer.parseInt/NumberFormatException.

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter numbers (0 to end):");
    int sum = 0;
    int number;
    do {
        while (!sc.hasNextInt()) {
            System.out.println("I'm sorry, that not a number! Try again!");
            sc.next();
        }
        number = sc.nextInt();
        sum += number;
    } while (number != 0);
    System.out.println("The sum of those numbers is " + sum);

:

Enter numbers (0 to end):
1
3
-1
five
I'm sorry, that not a number! Try again!
2
0
The sum of those numbers is 5

+8

, , , .

char t;
while ((t = (char) System.in.read()) != '0') {
    //...
}
+7
 while ((char t==(char) System.in.read())!='0')
 //            ^^  should be 'char t = ...'

,

 while (true) {
    char t = (char) System.in.read();
    if (t == '0')
      break;
    ...
+6

char t - , , ; ==. , , , , ++ .

The easiest way to limit the scope of a variable in a loop is to use it forinstead, which specifically allows you to declare variables.

for (char t; ( t = (char) System.in.read() ) != '0'; )
   // loop body involving t

However, some company guidelines do not allow mutation of operators in boolean expressions, such as reading and assignment, and would prefer that you split them into several lines. Personally, I believe that limiting the scope is more important.

+3
source

Source: https://habr.com/ru/post/1750067/


All Articles