我有一项涉及用户输入的家庭作业。
我想询问用户1-7范围内的三个整数输入并将它们存储在一个数组中。
到目前为止,如果所有输入都超过7并且排除字符串等输入并且仍然允许单个输入超过7,我到目前为止似乎正确验证。
感谢任何帮助。
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
while(!valid)
{
System.out.println("enter three numbers: ");
if(in.hasNextInt())
{
for(int i = 0; i< inputRange.length; i++)
{
inputRange[i] = in.nextInt();
if(inputRange[i] >= 1 && inputRange[i] <= 9){
valid = true;
}
}
}else{
in.next();
}
}
答案 0 :(得分:1)
您的逻辑很好,但每次用户输入新数字时,您需要再次将valid
重新设置为false。
以下是如何使用相同的逻辑将用户输入验证为1-9和do-while
之间的差别。
下次请务必发布有效的MCVE而不仅仅是&#34;摘要&#34; (它应包括main
方法和导入)
import java.util.Scanner;
public class ValidationOfNumbers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid = false;
int[] inputRange = new int[3];
int counter = 0;
int number = 0;
System.out.println("Enter 3 digits between 1-9"); //Ask for digits, numbers can have multiple digits, while digits are numbers from 0-9
for (int i = 0; i < inputRange.length; i++) {
valid = false; //Restart "valid" variable for each new user input
do {
number = in.nextInt();
if (number >= 1 && number <= 9) {
valid = true; //If valid, it will exit do-while
} else {
System.out.println("Enter a valid digit between 1-9");
}
} while (!valid);
inputRange[i] = number; //We know it's valid because it went out of do-while, so we can now store it in the array
}
for (int i = 0; i < inputRange.length; i++) {
System.out.println(inputRange[i]);
}
}
}
答案 1 :(得分:-1)
这是代码
Scanner in = new Scanner(System.in);
int count = 0;
int data[] = new int[3];
while(count < 3) {
if(in.hasNextInt()) {
int val = in.nextInt();
if(val>=1 && val <=7) {
data[count] = val;
count++;
}
}
else {
in.next();
}
}