I want to check for both negative number and non-number

戏子无情 提交于 2019-12-11 10:54:25

问题


I have code to check for non numbers but also wish to include a check for negative numbers. If the number is negative or not a number, they have to re-enter info. I tried putting an if(depValue < 0).... after try{ and before catch but that didn't work. It doesn't make sense to me if I were to put the if statement after the while loop.

String depIn = "";
BufferedReader depositInput = new BufferedReader(new InputStreamReader(System.in));
while(true){
     System.out.print("Amount to deposit: ");                   
     depIn = depositInput.readLine();
     double depValue = 0.00;
     try{
          depValue = Double.parseDouble(depIn);
          break;
     }
     catch(NumberFormatException ne){
          System.out.println("You did not enter a number!");
     }
}

回答1:


You can break out of the loop when you have the number you need.

double depValue;
while(true){
     System.out.print("Amount to deposit: ");                   
     depIn = depositInput.readLine();
     try {
          if ((depValue = Double.parseDouble(depIn)) > 0)
              break;
          System.out.println("The number needs to be positive!");
     } catch(NumberFormatException ne) {
          System.out.println("You did not enter a number!");
     }
}



回答2:


Put it in the same try catch block, and just display the error message from the caught NumberFormatException

 try{
      depValue = Double.parseDouble(depIn);
      if (depValue < 0) throw new NumberFormatException("Negative value not acceptable!");
      break;
 }
 catch(NumberFormatException ne){
      ne.printStackTrace();
 }


来源:https://stackoverflow.com/questions/32233093/i-want-to-check-for-both-negative-number-and-non-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!