简体   繁体   English

Java,使用 Scanner 尝试捕获

[英]Java, try-catch with Scanner

I am creating a small algorithm and this is a part of it.我正在创建一个小算法,这是其中的一部分。

If the user enters non integer values, I want to output a message and let the user enter a number again:如果用户输入非整数值,我想输出一条消息,让用户再次输入一个数字:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

I am getting a never ending loop and I can't figure out why.我得到了一个永无止境的循环,我不知道为什么。

How can I identify if the user enters some non integer number?如何识别用户是否输入了一些非整数?
If the user enters a non integer number, how can I ask the user to enter again?如果用户输入了一个非整数,如何让用户重新输入?

Update更新
When I am printing the exception I get 'InputMismatchException', what should I do?当我打印异常时,我得到“InputMismatchException”,我该怎么办?

The Scanner does not advance until the item is being read.在读取项目之前, Scanner不会前进。 This is mentioned in Scanner JavaDoc .这在Scanner JavaDoc中提到。 Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.因此,您可以使用.next()方法读取值,或者在读取int值之前检查是否有hasInt()

boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);

do {
    try {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class
    } catch (InputMismatchException e) {
        sc.next();
        wenttocatch = true;
        System.out.println("xx");
    }
} while (wenttocatch == true);

You dont have to do a try catch.你不必尝试捕捉。 This code will do the trick for you :此代码将为您解决问题:

public static void main(String[] args) {
    boolean wenttocatch = false;
    Scanner scan = new Scanner(System.in);
    int number_of_rigons = 0;
    do{
        System.out.print("Enter a number : ");
        if(scan.hasNextInt()){
            number_of_rigons = scan.nextInt();
            wenttocatch = true;
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(!wenttocatch);
}

Anytime you get an exception, wenttocatch is set to true and the program will be stuck in an infinite loop.任何时候遇到异常, wenttocatch都会设置为true ,程序就会陷入无限循环。 As long as you don't get the exception you'll not get an infinite loop.只要你没有得到异常,你就不会得到无限循环。

The logic if sc.nextInt() causing the error is this如果 sc.nextInt() 导致错误的逻辑是这样的

1) wenttocatch is set to false 1) gotocatch 设置为 false

2) sc.nextInt() throws error 2) sc.nextInt() 抛出错误

3) wenttocatch is set to true 3) gotocatch 设置为 true

4) repeat[because wenttocatch is true] 4) 重复[因为 gotocatch 是真的]

To solve this set wentocatch=false in catch statement在 catch 语句中解决这个 set goocatch=false

catch (Exception e) {
               wenttocatch=false;
               System.out.println("xx");
            }

if you are doing more than you show here, use a counter[if your counting or a boolean if you are not], but unless you are doing more, do the first thing above如果您做的比这里显示的多,请使用计数器[如果您的计数或布尔值,如果您不是],但除非您做的更多,否则请执行上面的第一件事

boolean wenttocatch;
int count = 0;

            do{


             try {
                 wenttocatch=false;
                number_of_rigons=sc.nextInt(); // sc is an object of scanner class 
            } catch (Exception e) {
               count++;
               wenttocatch=true;
               System.out.println("xx");

            }

            }while(wenttocatch==true && count < 1);

Answer Comment:回复评论:

I think you want to get ints until a user doesn't enter anymore.我认为您想获得整数,直到用户不再输入。 Depending on your input one way of doing that is this根据您的输入,一种方法是这样

int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
    //do something
}

you simply can use the hasNext();您只需使用 hasNext(); method in java, instead of try and catch. java中的方法,而不是try and catch。 The hasNext() is a method of Java Scanner class that returns true if this scanner has another token in its input. hasNext() 是 Java Scanner 类的一个方法,如果此扫描器的输入中有另一个标记,则返回 true。

 String[] stringArray = new String[lines];
   int i = 0;
   try (Scanner sc = new Scanner(file)) {
       while (sc.hasNextLine()) {
           String data=sc.nextLine();
           stringArray[i] = data;

           i++;
       }
   } catch (FileNotFoundException fileNotFoundException) {
       System.err.println("Error opening file.");
       throw new FileNotFoundException();
   } catch (NoSuchElementException e) {
       System.err.println("Error in file record structure");
       throw new NoSuchElementException();
   } catch (Exception e) {
       e.printStackTrace();
   }
  

/*added the scanner declaration inside try im new on programming its worked for me but I don't know if its good practice */ : /*在里面添加了扫描仪声明尝试我新的编程它对我有用,但我不知道它是否是好的做法*/:

    boolean wenttocatch;
    do 
    {
        try 
        {
           
        Scanner sc=new Scanner(System.in);
         wenttocoatch = false;
        number_of_rigons = sc.nextInt(); 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);
....
try {
  ....
} catch (Exception e) {
  sc.next();
  wenttocatch=true;
  System.out.println("xx");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM