[英]How can I check that the next input is an integer while checking if it's > and < at the same time in Java?
There's two things I'm needing help with.有两件事我需要帮助。 Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string.循环问题 1) 我必须在循环外初始化这个变量,如果用户输入字符串,这会使循环失败。 Is there a way around that?有办法解决吗? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the基本上,如果我将 N 设置为任何值,那么 do-while 循环会在退出后立即读取它
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this?如果没有,那么问题就变成了,我该如何解决呢? I thing that I need to be able to say我想说的是
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the???我放什么??? to make this work?使这项工作? I think I just don't know enough syntax.我想我只是不懂足够的语法。
Thank you!谢谢!
Why don't you try this?你为什么不试试这个?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break
is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail. break
用于在用户输入无效字符(else 子句的条件)时立即结束循环,因此循环不会失败。
Looking at your edited question, continue
is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.查看您编辑的问题,如果您可能希望允许用户在输入无效值后输入另一个值,那么continue
就是您要查找的内容。
Use break
or continue
based on requirement.根据需要使用break
或continue
。 More on breaks and continue.更多关于休息和继续。 Your second approach can be solved as follows:您的第二种方法可以按如下方式解决:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.