Java 如何检查列特的字符串(numberformatexception)

Java 如何检查列特的字符串(numberformatexception),java,Java,我有我的代码,它可以自己检查字母,但是当我把它们放在同一个字符串中时,它就崩溃了 我尝试了.matches方法,我也尝试了.contains方法,我认为它最适合,但我不确定什么方法最适合使用 String regex = "^[a-zA-Z]+$"; System.out.println("How many dice to you want to roll?"); String DiceChoice = scan.nextLine(); while (DiceCh

我有我的代码,它可以自己检查字母,但是当我把它们放在同一个字符串中时,它就崩溃了

我尝试了.matches方法,我也尝试了.contains方法,我认为它最适合,但我不确定什么方法最适合使用

   String regex = "^[a-zA-Z]+$";

   System.out.println("How many dice to you want to roll?");
   String DiceChoice = scan.nextLine();



   while (DiceChoice.indexOf(".")!=-1 || DiceChoice.matches(regex)) {
       System.out.println("Please enter a number without a decimal or 
       letter");
       DiceChoice = s.nextLine();
   }
   int DiceChoiceInt = Integer.parseInt(DiceChoice);
当我加上“a”就好了,或者“a”就好了,但当我加上“4a”就得到了例外


我希望它能在字符串中的某个地方找到字母,然后进入while循环,但它只是出现了一个数字格式的异常,我在想也许我可以尝试捕捉一下?感谢您的帮助

纯数字字符串的正则表达式模式是
\d+
,因此,为什么不直接检查该正匹配:

String diceChoice;

do {
    diceChoice = scan.nextLine();
    if (diceChoice.matches("\\d+")) break;
    System.out.println("Please enter a number-only choice");
} while (true);

int diceChoiceInt = Integer.parseInt(diceChoice);

这种方法将无限期地循环,直到出现纯数字输入。

纯数字字符串的正则表达式模式是
\d+
,因此为什么不直接检查正匹配:

String diceChoice;

do {
    diceChoice = scan.nextLine();
    if (diceChoice.matches("\\d+")) break;
    System.out.println("Please enter a number-only choice");
} while (true);

int diceChoiceInt = Integer.parseInt(diceChoice);

这种方法将无限循环,直到出现纯数字输入。

正则表达式只在只有字母的情况下匹配。正则表达式只在只有字母的情况下匹配。我掷骰子,没有掷骰子。我对这个结果也很满意。我掷骰子,没有拉屎。我也对这个结果感到高兴。