gpt4 book ai didi

java - 负输入的验证

转载 作者:行者123 更新时间:2023-12-01 10:19:43 27 4
gpt4 key购买 nike

我正在尝试验证用户输入。我不希望用户输入负数、字符串和 double 。我只需要 int。我只能验证字符串和 double 。我们将不胜感激您的帮助。

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);

最佳答案

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;
}

关于java - 负输入的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35678182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com