加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 尝试catch时可以实现无限

发布时间:2020-12-15 04:34:21 所属栏目:Java 来源:网络整理
导读:当我尝试在循环中执行try-catch语句时遇到问题.我要求用户首先输入字母然后输入一个数字,如果他正确输入数字,程序结束.如果他输入字母而不是数字,程序应该说“发生错误请输入数字“并要求用户再次输入数字,但每次输入字母而不是数字时,程序进入无限循环,不允
当我尝试在循环中执行try-catch语句时遇到问题.我要求用户首先输入字母然后输入一个数字,如果他正确输入数字,程序结束.如果他输入字母而不是数字,程序应该说“发生错误请输入数字“并要求用户再次输入数字,但每次输入字母而不是数字时,程序进入无限循环,不允许我输入新值.
然后就去吧
“发生错误,你必须输入数字”
“请输入号码”.

public class OmaBrisem {

    public static void main(String[] args) {
        Scanner tastatura = new Scanner(System.in);
        boolean b = true;
        int a = 0;
        String r = "";
        System.out.println("Please enter a letter");
        r = tastatura.next();
        do {
            try {
                System.out.println("Please enter numerical value");
                a = tastatura.nextInt();
                b = true;
            } catch (Exception e) {
                System.out.println("An error occured you must enter number");
                b = false;
            }
        } while (!b);

    }

}

解决方法

这是你的问题.如果用户在您希望输入数字的位置输入非数字,则您的nextInt()将引发异常,但不会从输入流中删除该字母!

这意味着当你循环返回以再次获得该数字时,该字母仍将存在,而你的nextInt()将再次引发异常.等等,无限制地(或者至少直到宇宙的热量死亡,或者机器最终崩溃,以先到者为准).

解决这个问题的一种方法是在nextInt()失败时实际读取/跳过下一个字符,以便从输入流中删除它.您基本上可以使用Scanner.findInLine(“.”)执行此操作,直到Scanner.hasNextInt()返回true.

以下代码显示了一种方法:

import java.util.Scanner;
public class MyTestProg {
     public static void main(String [] args) {
         Scanner inputScanner = new Scanner(System.in);
         System.out.print("Enter letter,number: ");

         // Get character,handling newlines as needed

         String str = inputScanner.findInLine(".");
         while (str == null) {
             str = inputScanner.nextLine();
             str = inputScanner.findInLine(".");
         }

         // Skip characters (incl. newline) until int available.

         while (! inputScanner.hasNextInt()) {
             String junk = inputScanner.findInLine(".");
             if (junk == null) {
                 junk = inputScanner.nextLine();
             }
             System.out.println("Ignoring '" + junk + "'");
         }

         // Get integer and print both.

         int num = inputScanner.nextInt();
         System.out.println("Got '" + str + "' and " + num);
     }
}

以下成绩单显示了它的实际效果:

Enter letter,number: Abcde42
Ignoring 'b'
Ignoring 'c'
Ignoring 'd'
Ignoring 'e'
Got 'A' and 42

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读