验证负面输入

时间:2016-02-28 03:00:01

标签: java

我正在尝试验证用户输入。我不希望用户输入负数,字符串和双精度数。我只需要int。我只能验证字符串和双精度。我们将不胜感激。

do {

    System.out.println("How many cappuccino drinks were sold today?");
    if(input.hasNextInt()) {

        cappuccinoDrink = input.nextInt();


            capexpenses = cappuccinoDrink * 1.56;
            capRevenue = cappuccinoDrink * 3.50;
            capProfit = capRevenue - capexpenses;
            isNumber = true;

    }else {
        System.out.println("You didn't didn't enter the require imput");
        isNumber = false;
        input.next();
    }
} while(!isNumber);

2 个答案:

答案 0 :(得分:1)

if(input.hasNextInt()) {更改为以下内容:

if(input.hasNextInt() && (cappuccinoDrink = input.nextInt()) >= 0) {
            //removed assignment as it is handled in if statement
            capRevenue = cappuccinoDrink * 3.50;
            capProfit = capRevenue - capexpenses;
            isNumber = true;
}

答案 1 :(得分:0)

int cappuccinoDrink;
boolean invalidinput = true;
System.out.println("Please enter a positive integer : ");
while(invalidInput){
   try{
     cappuccinoDrink = input.nextInt();
     if( cappuccinoDrink<= 0) {  
            System.out.println("Please enter a positive integer value: ");
     }
     else{invalidInput=false;}
   }
   catch(InputMismatchException e){
        System.out.println("Please enter a positive integer value: ");
   }
}
        capexpenses = cappuccinoDrink * 1.56;
        capRevenue = cappuccinoDrink * 3.50;
        capProfit = capRevenue - capexpenses;