Java 当程序需要整数时,当用户输入字符串时,如何防止程序终止?
我正在尝试设置一个do-while循环,该循环将重新提示用户输入,直到他们输入一个大于零的整数。我不能用try-catch来做这个;这是不允许的。以下是我得到的:Java 当程序需要整数时,当用户输入字符串时,如何防止程序终止?,java,exception,exception-handling,java.util.scanner,do-while,Java,Exception,Exception Handling,Java.util.scanner,Do While,我正在尝试设置一个do-while循环,该循环将重新提示用户输入,直到他们输入一个大于零的整数。我不能用try-catch来做这个;这是不允许的。以下是我得到的: Scanner scnr = new Scanner(System.in); int num; do{ System.out.println("Enter a number (int): "); num = scnr.nextInt(); } while(num<0 || !scnr.hasNextLine()); Scann
Scanner scnr = new Scanner(System.in);
int num;
do{
System.out.println("Enter a number (int): ");
num = scnr.nextInt();
} while(num<0 || !scnr.hasNextLine());
Scanner scnr=新扫描仪(System.in);
int-num;
做{
System.out.println(“输入一个数字(int):”;
num=scnr.nextInt();
}虽然(numAs不允许使用try-catch,但请调用nextLine()
。
使用nextInt()
,然后测试自己是否得到字符串
back是否为整数
import java.util.Scanner;
public class Test038 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num = -1;
do {
System.out.println("Enter a number (int): ");
String str = scnr.nextLine().trim();
if (str.matches("\\d+")) {
num = Integer.parseInt(str);
break;
}
} while (num < 0 || !scnr.hasNextLine());
System.out.println("You entered: " + num);
}
}
import java.util.Scanner;
公共类Test038{
公共静态void main(字符串[]args){
扫描仪scnr=新扫描仪(System.in);
int num=-1;
做{
System.out.println(“输入一个数字(int):”;
字符串str=scnr.nextLine().trim();
如果(str.matches(\\d+)){
num=Integer.parseInt(str);
打破
}
}而(num<0 | |!scnr.hasNextLine());
System.out.println(“您输入:“+num”);
}
}
您可以将其作为字符串,然后使用正则表达式测试该字符串是否只包含数字。因此,如果字符串实际上是整数,则只分配字符串的整数值num
。这意味着您需要将num
初始化为-1
,这样,如果它不是整数,while条件将为true,并且我们将重新开始
Scanner scnr = new Scanner(System.in);
int num = -1;
String s;
do {
System.out.println("Enter a number (int): ");
s = scnr.next().trim(); // trim so that numbers with whitespace are valid
if (s.matches("\\d+")) { // if the string contains only numbers 0-9
num = Integer.parseInt(s);
}
} while(num < 0 || !scnr.hasNextLine());
我们的答案对您有帮助吗?这是一个入门类项目(因此我不能使用try-catch,因为我们还没有学会),我不知道是否允许使用parseInt().这对我来说很有意义,我现在要尝试实现它。谢谢,伙计们。如果你不能使用try-catch,也不能使用字符串regex/parseInt,那么你在做一个荒谬的项目。