Loop problem in Java
•
Java
What is the error in the following code?
while ((char t==(char) system.in.read())!='0')
Solution
You cannot declare a new variable in a while loop
while (boolean always = true) {
} // DOES NOT COMPILE!!!
You must declare variables before and outside the loop, so it may be like this:
boolean always = true;
while (always) {
break;
} // compiles fine!
// always is still in scope after the loop!
always = !always;
In this sense, the for loop is unique: in fact, you can declare a new local variable whose scope is limited to the loop:
for (boolean always = true; always; ) {
break;
} // compiles fine!
// always is no longer declared after the loop!
always = !always; // DOES NOT COMPILE!
That is, to see what you're doing, you might want to see Java util. Scanner. I doubt it will better meet your needs
example
The following is an example of using scanner to read numbers from standard input, ending at 0 Then print the sum of these numbers It uses hasnextint () instead of integer ParseInt / numberformatexception normally handles invalid input
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's 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);
This is a sample session:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
