Java 我试图添加一个 try catch 告诉用户他们不能插入负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35604342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:51:43  来源:igfitidea点击:

Im trying to add a try catch that tells the user they cant plug in negative numbers

javatry-catchnegative-number

提问by Ronaldo

I was able to add a try catch that tells the user that they cant use letters.However for some reason adding a try catch for negative numbers dosent seem to work.I know that the try block is where if somthing can go wrong like entering in a negative number the catch can print out the error message. I think thats where my problem lies. Another problem that is associated with the try catch is that I'm use to the user entering in -1 to enter the contents that the user inputs so I'm thinking its gonna cause a logical problem.

我能够添加一个 try catch 告诉用户他们不能使用字母。但是由于某种原因,为负数添加一个 try catch 似乎没有用。 catch 可以打印出错误消息的负数。我想这就是我的问题所在。与 try catch 相关的另一个问题是,我习惯于用户输入 -1 来输入用户输入的内容,因此我认为它会导致逻辑问题。

tl;dr Adding a try catch or another catch to prevent user from adding negative numbers

tl;dr 添加 try catch 或其他 catch 以防止用户添加负数

this is not the the whole program but what it does is that it filters out the integers that the user inputs and separates the evens and odds.

这不是整个程序,但它的作用是过滤掉用户输入的整数并分离偶数和几率。

 public static void main(String [] args)
    {
        Scanner stdin = new Scanner(System.in);//for user input
        int[] evenNum = new int [100];//Even Array up too 100
        int[] oddNum = new int[100];//Odd Array up too 100
        int evenIndex=0;//even numbers
        int input=0;//user input
        int i=0;//incrementer for arrays
        int k=0; 
        int j=0;
        String name;

        System.out.println("Type In Your Name");//Type in name 
            name = stdin.nextLine();


while ((i < oddNum.length && i < evenNum.length) && input !=-1)//100 numbers only
        {
    try{//this is what we want anything else the catch will block it and display a message


                System.out.println(name+" Enter a positive number, Enter -1 For results");
                input= stdin.nextInt();

                oddNum[i]=input;//holds input
                i++;//Increments array
            }  

                catch(Exception d){
                    System.out.println("Only Positive Numbers & no Letters Please!");
                    stdin.next();

                     }


                }

回答by Bahramdun Adil

You can do it like this:

你可以这样做:

if (input < 0) {
    throw new IllegalArgumentException();
}

Now if the number is negative, it will throw exceptionand the catchcode can be executed. Because you catch Exceptionso all of the exception will be catches here.

现在如果数字是负数,它将抛出exception并且catch代码可以被执行。因为你捕获Exception所以所有的异常都会在这里捕获。

Note:In catchblock you no need to add stdin.next();because the program will continue from the first line of whileloop.

注意:catch块中您不需要添加,stdin.next();因为程序将从while循环的第一行继续。

回答by stjepano

In order for your catch block to catch exception, the Exception needs to be thrown from the code. In case of negative numbers the line input= stdin.nextInt();will not throw exception as it is perfectly legal for integer to be negative. You will need to add if condition like this:

为了让 catch 块捕获异常,需要从代码中抛出异常。在负数的情况下,该行input= stdin.nextInt();不会抛出异常,因为整数为负是完全合法的。您将需要添加 if 条件如下:

input = stdin.nextInt();
if ( input < 0 ) {
  throw new Exception("Negative number entered");
}

But some consider this to be bad practice because you are using exceptions to control the flow of a program. So I give you another example how you can do this without throwing an exception:

但有些人认为这是不好的做法,因为您正在使用异常来控制程序的流程。所以我给你另一个例子,你如何在不抛出异常的情况下做到这一点:

input = stdin.nextInt();
if ( input < 0 ) {
  System.out.println("Only Positive Numbers Please");
  continue;  // will continue from the beginning of a loop
}

回答by deepthought-64

You can check the inputvariable after you get it from the scanner

input从扫描仪获取变量后,您可以检查该变量

if (input < 0) {
     System.out.println("Only Positive Numbers & no Letters Please!");
}

Your code does not throw any Exception when the number is read from the scanner. So you cannot expect that the execution jumps into the catch-block when you enter a negative number.

从扫描仪读取数字时,您的代码不会抛出任何异常。因此,当您输入负数时,您不能期望执行会跳转到 catch 块。

But you can alternatively throw an exception when the inputis negative. This will make the thread to jump directly into the catch-block. In the catch-block you can then print the message you passed the IllegalArgumentException

但是您也可以在input为负数时抛出异常。这将使线程直接跳转到 catch 块。在 catch 块中,您可以打印您通过的消息IllegalArgumentException

if (input < 0) {
     // this gets caught in the catch block
     throw new IllegalArgumentException("Only Positive Numbers & no Letters Please!"); 
}      
...
} catch (IllegarArgumentException e) {
    System.out.println(e.getMessage());
}

It is generally bad practice to catch Exception(java.lang.Exception). This is the "root" of all checked exceptions and the catch-block will be jumped into whenever any subclass of Exceptionis thrown.
Just catch the concrete exception that you are expecting. (In this case IllegalArgumentException.)

捕获Exception( java.lang.Exception)通常是不好的做法。这是所有已检查异常的“根”,只要Exception抛出 的任何子类,就会跳转到捕获块。
只需捕获您期望的具体异常即可。(在这种情况下IllegalArgumentException。)

Also you should not use exceptions to control the execution flow of your program.

此外,您不应使用异常来控制程序的执行流程。

I would suggest something like this:

我会建议这样的事情:

do {
    System.out.println(name+" Enter a positive number, Enter -1 For results");
    try {
        input = stdin.nextInt();
    } catch (java.util.InputMismatchException e) { // if the user enters something that is not an integer
        System.out.println("Please only enter integers");
        input = Integer.MIN_VALUE; 
        stdin.next(); // consume the non-int so we don't get caught in an endless loop
    }
} while (input < -1);  // loop as long as the input is less than -1

if (input == -1) {
    // show the results here
}

This will accept positive integers and will prompt for an input until the user enters a positive number, 0 (zero) or -1 (which should show the results)

这将接受正整数并提示输入,直到用户输入正数 0(零)或 -1(应显示结果)