[英]Java - Converting String from Scanner to int and vice versa
我正在尝试从 Java 扫描仪获取字符串输入,并将其用于一些不同的功能。 首先,我希望它能够将输入作为文本(不仅仅是数字)用于稍后在程序中的不成文方法。 其次,我想将其转换为 int 值(如果用户使用具有 int 形式参数的不同方法(hasDupes)。
我目前正在这样做:
public static boolean hasDupes(int num){
boolean[] digs = new boolean[10];
while (num > 0){
if (digs[num % 10])
return true;
digs[num % 10] = true;
num /= 10;
}
return false;
}
public static String getGuess() {
boolean validGuess = false;
String userGuess = "";
Scanner sc = new Scanner(System.in);
userGuess = sc.next();
if (!(hasDupes(Integer.parseInt(userGuess))) || (Integer.parseInt(userGuess) < 1000))
validGuess = true;
return userGuess;
}
但是,当我输入一个不是 int 类型的值时,它给了我错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "nonIntText"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Main.getGuess(Main.java:164)
我究竟做错了什么?
当您尝试通过 Integer.parseInt 或任何东西将字符串转换为数字时,如果它不是有效数字,它可能会抛出 NumberFormatException。
public static String getGuess() {
Scanner scanner = new Scanner(System.in);
String text = scanner.next();
boolean isValid = false;
try {
// try to parse it to a number
double number = Double.parseDouble(text);
// now do something with number, call hasDupes()
isValid = true;
} catch (NumberFormatException ignored) {
// it is not a number
}
System.out.println("Is Valid '" + isValid + "'");
return text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.