我试图添加一个尝试捕获,告诉用户他们不能插入负数
我能够添加一个尝试捕获,告诉用户他们不能使用字母。但是由于某种原因添加一个尝试捕获负数量dosent似乎工作。我知道try块是在哪里,如果somthing可能会出错像进入一个负数,catch可以打印出错误信息。 我认为这就是我的问题所在。 与try catch相关的另一个问题是我使用输入-1的用户输入用户输入的内容,所以我认为它会导致逻辑问题。
tl; dr添加try catch或其他catch以防止用户添加负数
这不是整个程序,但它的作用是过滤掉用户输入的整数并分离平均值和赔率。
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(); } }
从扫描仪获取input
变量后,可以检查input
变量
if (input < 0) { System.out.println("Only Positive Numbers & no Letters Please!"); }
从扫描仪读取数字时,您的代码不会抛出任何exception。 因此,当您输入负数时,您不能指望执行会跳转到catch块。
但是,当input
为负时,您也可以抛出exception。 这将使线程直接跳转到catch块。 在catch-block中,您可以打印传递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()); }
捕获Exception
( java.lang.Exception
)通常是不好的做法。 这是所有已检查exception的“根”,只要抛出任何Exception
子类,catch块就会被跳转。
抓住你期待的具体例外。 (在这种情况下为IllegalArgumentException
。)
此外,您不应该使用exception来控制程序的执行流程。
我会建议这样的事情:
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 }
这将接受正整数并将提示输入,直到用户输入正数,0(零)或-1(应显示结果)
你可以这样做:
if (input < 0) { throw new IllegalArgumentException(); }
现在,如果数字是负数,它将抛出exception
并且可以执行catch
代码。 因为你捕获了Exception
所以所有exception都将在这里捕获。
注意:在catch
块中你不需要添加stdin.next();
因为程序将从while
循环的第一行继续。
为了使catch块捕获exception,需要从代码中抛出exception。 在负数的情况下,行input= stdin.nextInt();
不会抛出exception,因为整数是负数是完全合法的。 您将需要添加if条件,如下所示:
input = stdin.nextInt(); if ( input < 0 ) { throw new Exception("Negative number entered"); }
但有些人认为这是不好的做法,因为你使用exception来控制程序的流程。 所以我再举一个例子说明如何在不抛出exception的情况下做到这一点:
input = stdin.nextInt(); if ( input < 0 ) { System.out.println("Only Positive Numbers Please"); continue; // will continue from the beginning of a loop }