【问题标题】:Loop when incorrect input is given?输入错误时循环?
【发布时间】:2021-12-20 08:51:15
【问题描述】:
所以基本上我一直试图让这个简单的小代码工作,但我遇到了制作循环的问题。我想要发生的基本上是这样的:用户输入一个整数,如果它不是一个整数,它将显示一个错误并要求一个整数,直到给出整数。我很难设置循环,因为我不太知道该怎么做。我很新而且很笨,所以这可能真的很容易,但我有点白痴,对此很烂,但我正在学习。
这就是我所拥有的。
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
【问题讨论】:
标签:
java
loops
conditional-statements
【解决方案1】:
您可以为此使用while 循环。
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
【解决方案2】:
您需要在代码中使用循环(for 或 while)。你可以这样做。
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}