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

前端 未结 3 1628

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

3条回答
  •  梦谈多话
    2021-01-03 16:00

    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:

    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
    }
    

提交回复
热议问题