java - Java 3.6 检查输入
问题描述
要求用户“输入数字:” 4 次。如果输入不是数字,请再次询问。输出“成功”。在他们输入了 4 个数字后。请使用 while、if、if else 和 do 语句为我回答此代码。
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
这是非常基本的东西,但我很挣扎。
解决方案
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner
推荐阅读
- uml - UML - 如何将类图与子类垂直对齐
- json - 使用 jq 创建带有字符串变量作为参数的 json
- xml - 如何获得两个xpath节点集的交集
- c# - 将嵌套对象转换为数组
- mysql - MySQL 8.0.22 指定为定义者('root'@'%')的用户不存在
- javascript - 在 Javascript 中评估表达式树
- reactjs - 如何使材料 ui 自动完成组件可点击链接的选项?
- .net-core - “HubCallerContext”不包含“请求”singnalr .netcore 的定义
- elasticsearch - 来自多个索引的 Elasticsearch 查询,每个索引都有痛苦
- ios - XCode 11.3.1,测试运行器在 CI 上执行测试之前失败