Java 扫描仪对象不返回预期结果
我正在尝试使用Java 扫描仪对象不返回预期结果,java,java.util.scanner,Java,Java.util.scanner,我正在尝试使用扫描仪对象验证一些用户输入。根据我的要求,如果用户输入100>输入100){ sc.next();//放弃 System.out.println(“请输入分数和数字,仅在0-100之间:”); }else if(sc.nextInt()100){ System.out.println(“请输入分数和数字,仅在0-100之间:”); }else if(nextInt100){ System.out.println(“请输入分数和数字,仅在0-100之间:”); }else if(ne
扫描仪
对象验证一些用户输入。根据我的要求,如果用户输入100>输入100){
sc.next();//放弃
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}else if(sc.nextInt()<0){
sc.next();//放弃
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}否则{
分数=sc.nextInt();
打破
}
}
返回分数;
}
您不应多次读取
扫描仪的内容。只需通过nextInt
将数字读入变量并进行检查即可。否则,在每个if
分支上,都会提示您输入新号码
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}
public int validateScore(扫描仪sc){
智力得分=0;
System.out.println(“请输入学生分数”);
对于(;;){
如果(!sc.hasnetint()){
System.out.println(“请输入分数和数字”);
sc.next();//放弃
}否则{
int-nextInt=sc.nextInt();
如果(nextInt>100){
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}else if(nextInt<0){
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}否则{
分数=nextInt;
打破
}
}
}
返回分数;
}
您不应多次读取扫描仪的内容。只需通过nextInt
将数字读入变量并进行检查即可。否则,在每个if
分支上,都会提示您输入新号码
public int validateScore(Scanner sc) {
int score = 0;
System.out.println("Please Enter Student's Score.");
for (;;) {
if (!sc.hasNextInt()) {
System.out.println("Please enter the score and in number");
sc.next(); // discard
} else {
int nextInt = sc.nextInt();
if (nextInt > 100) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else if (nextInt < 0) {
System.out.println("Please enter the score and in number in between 0-100 only: ");
} else {
score = nextInt;
break;
}
}
}
return score;
}
public int validateScore(扫描仪sc){
智力得分=0;
System.out.println(“请输入学生分数”);
对于(;;){
如果(!sc.hasnetint()){
System.out.println(“请输入分数和数字”);
sc.next();//放弃
}否则{
int-nextInt=sc.nextInt();
如果(nextInt>100){
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}else if(nextInt<0){
System.out.println(“请输入分数和数字,仅在0-100之间:”);
}否则{
分数=nextInt;
打破
}
}
}
返回分数;
}
由于在if-else块中使用了nextInt(),导致该错误。在验证值之前,请使用hasNextInt()方法并将值存储在临时变量中 由于在if-else块中使用了nextInt(),导致该错误。在验证值之前,请使用hasNextInt()方法并将值存储在临时变量中 您将读取输入两次,一次是在验证时,另一次是在返回值赋值时。首先将其读入变量,然后进行验证并返回。您将在验证时读取输入两次,然后在返回值赋值时再次读取输入。首先将它读入一个变量,然后验证并返回.ya是一个小错误。谢谢你的回复。这是个小错误。谢谢你的回复