gpt4 book ai didi

java - 如果用户输入 String 而不是 Int,可能会出现异常

转载 作者:行者123 更新时间:2023-12-02 01:19:00 29 4
gpt4 key购买 nike

我只是在玩 Java。我试图强制我的程序只接受 3 位数字。我相信我已经使用 while 循环成功完成了此操作(如果我错了,请纠正我)。但是,如果用户输入字符串,我该如何打印错误语句。例如:“abc”。

我的代码:

    import java.util.Scanner;
public class DigitSum {

public static void main(String[] args) {

Scanner newScan = new Scanner(System.in);

System.out.println("Enter a 3 digit number: ");
int digit = newScan.nextInt();

while(digit > 1000 || digit < 100)
{
System.out.println("Error! Please enter a 3 digit number: ");
digit = newScan.nextInt();
}

System.out.println(digit);
}
}

最佳答案

这个怎么样?

public class Sample {
public static void main (String[] args) {
Scanner newScan = new Scanner (System.in);

System.out.println ("Enter a 3 digit number: ");
String line = newScan.nextLine ();
int digit;
while (true) {
if (line.length () == 3) {
try {
digit = Integer.parseInt (line);
break;
}
catch (NumberFormatException e) {
// do nothing.
}
}

System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
line = newScan.nextLine ();
}

System.out.println (digit);
}
}

正则表达式版本:

public class Sample {
public static void main (String[] args) {
Scanner newScan = new Scanner (System.in);

System.out.println ("Enter a 3 digit number: ");
String line = newScan.nextLine ();
int digit;

while (true) {
if (Pattern.matches ("\\d{3}+", line)) {
digit = Integer.parseInt (line);
break;
}

System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
line = newScan.nextLine ();
}

System.out.println (digit);
}
}

关于java - 如果用户输入 String 而不是 Int,可能会出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12838346/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com