62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Test test = new Test();
int fri = test.isOKInput("第一次输入1~9的数字:", 1, 9);
int sec = test.isOKInput("第二次输入1~9的数字:", 1, 9);
System.out.println("第一次:" + fri);
System.out.println("第二次:" + sec);
}
// 检测非法输入
public int isOKInput(String str, int fri, int last) {
// 创建文本扫描器
Scanner input = new Scanner(System.in);
// 循环结束符
boolean flag = false;
int index = 0;
do {
System.out.print(str);
if (!(input.hasNextInt() && (index=input.nextInt()) >= fri && index <= last)) {
input.nextLine();
System.out.println("输入错误,请重新输入!");
continue;
}
flag = true;
} while (!flag);
input.close();
return index;
}
}