Java验证输入
在Java中是否可以检查某个输入是否在某个范围和整数之间? 我编写了以下代码:Java验证输入,java,loops,validation,while-loop,java.util.scanner,Java,Loops,Validation,While Loop,Java.util.scanner,在Java中是否可以检查某个输入是否在某个范围和整数之间? 我编写了以下代码: public void getBetAmountFromUser() { //Get Amount of Bet int x = 0; System.out.println("Your current pot is: " + potAmount); System.out.println("Enter your bet amount: "); x = input.nextInt
public void getBetAmountFromUser() {
//Get Amount of Bet
int x = 0;
System.out.println("Your current pot is: " + potAmount);
System.out.println("Enter your bet amount: ");
x = input.nextInt();
//Error message if bet is larger than pot and less than 0
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
//Bet should be less than or equal to pot if 0 user quit
if (x > 0 && x <= potAmount) {
betAmount = x;
potAmount = potAmount - betAmount;
} else if (x == 0) {
System.out.println("You end the game with pot " + potAmount);
System.exit(0);
}
}
public void getBetAmountFromUser(){
//下注
int x=0;
System.out.println(“您当前的pot是:“+potAmount”);
System.out.println(“输入您的下注金额:”);
x=input.nextInt();
//如果赌注大于pot且小于0,则显示错误消息
虽然(x>potAmount | | | x 0&&x potAmount | | | x您可以尝试使用String
代替int
。然后,您可以使用Integer.parseInt(x)
再次执行int
,因为在执行while
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\
字符串x;
String regex=“[0-9]+”;//检查字符串是否仅由数字组成
int potAmount=10;
扫描仪输入=新扫描仪(System.in);
做{
System.out.println(“请输入一个整数”);
x=输入。下一步();
}而(!x.matches(regex)| | Integer.parseInt(x)>potmount | | Integer.parseInt(x)<0);
int validBet=Integer.parseInt(x);
/* .
.
. *\
仔细检查代码,看看有什么问题
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\