如何以及在何处为此程序添加循环,以便程序继续执行,然后在用户输入介于100和999之间的有效数字后结束?
import java.util.*;
public class numLoop{
public static void main(String[] arg){
Scanner sc = new Scanner(System.in);
int number = 0;
try{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number between 100 and 999: ");
number = reader.nextInt();
if(number > 999 || number < 100)
System.out.println("\nYour number was invalid.");
else
System.out.println("\nThe number " + number + " was vaild.");
}
catch(InputMismatchException ime){
System.out.println("You didn't enter a number.");
}
}
}
答案 0 :(得分:1)
将整个try / catch放在while
循环中:
while (number < 100 || number > 999)
{
// ...
}
或者使用while (true) { }
或for (;;) { }
将其置于无限循环中,然后在输入有效数字时添加条件break
:
if (number < 100 || number > 999)
{
// handle invalid entry
}
else
{
// handle valid entry
break; // exit loop
}
答案 1 :(得分:1)
使用while
循环可以实现以下逻辑
(伪代码)
Input a number
while (number is not valid)
Tell them something went wrong
Input another number
Valid number was entered, do something about it
while循环本身看起来像
while (condition) {
// code to run while condition is true
}
答案 2 :(得分:0)
import java.util.*;
public class numLoop{
public static void main(String[] arg){
Scanner sc = new Scanner(System.in);
int number = 0;
try{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number between 100 and 999: ");
number = reader.nextInt();
while(number > 999 || number < 100){
System.out.println("\nYour number was invalid.");
number = reader.nextInt();
}
System.out.println("\nThe number " + number + " was vaild.");
}catch(InputMismatchException ime){
System.out.println("You didn't enter a number.");
}
}
}
答案 3 :(得分:0)
你也可以像这样使用while(true)break循环:
import java.util.*;
public class numLoop{
public static void main(String[] arg){
Scanner sc = new Scanner(System.in);
int number = 0;
while(true){
try{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number between 100 and 999: ");
number = reader.nextInt();
if(number > 999 || number < 100)
System.out.println("\nYour number was invalid.");
else
System.out.println("\nThe number " + number + " was vaild.");
break;
}
catch(InputMismatchException ime){
System.out.println("You didn't enter a number.");
}
}
}
}
不是每个人都警告这是良好的代码练习。
答案 4 :(得分:0)
在您现有的try
添加
while(true) // you could (and should) add braces (for the look of it).
// could also have used for(;;)
在这里
else
System.out.println("\nThe number " + number + " was vaild.");
然后你需要一个
else {
System.out.println("\nThe number " + number + " was vaild.");
break; // End the infinite loop.
}