Java 如果没有那么多相同的else语句,如何有效地验证小于零的输入?
我正试图用计算机模拟21点游戏中的金钱损失。然而,我遇到了一个错误,如果我在其中一个提示中输入了一个小于零的值,那么程序必须在警告小于零的值之前通过所有其他提示 有没有一种方法可以立即警告小于零的值,而不必反复为每个if输入相同的else语句Java 如果没有那么多相同的else语句,如何有效地验证小于零的输入?,java,Java,我正试图用计算机模拟21点游戏中的金钱损失。然而,我遇到了一个错误,如果我在其中一个提示中输入了一个小于零的值,那么程序必须在警告小于零的值之前通过所有其他提示 有没有一种方法可以立即警告小于零的值,而不必反复为每个if输入相同的else语句 private void menu() { boolean NonNumeric=false; //This is so a different exception is thrown for the minimum stakes sinc
private void menu()
{
boolean NonNumeric=false;
//This is so a different exception is thrown for the minimum stakes since it's a float.
boolean isDecimal=false;
while(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0 )
{
try
{
Scanner input = new Scanner(System.in);
if(getRounds()<=0)
{
System.out.println("Enter number of rounds.");
setRounds(input.nextInt());
}
if(getPlayers()<=0)
{
System.out.println("Enter number of players.");
setPlayers(input.nextInt());
}
if(getStakes()<=0)
{
System.out.println("Enter minimum stakes.(Note: All players bet minimum only)");
isDecimal=true;
setStakes(input.nextFloat());
}
}
catch (InputMismatchException e ) //In case some idiot enters a letter or symbol.
{
//This if statement is so that a different message comes if the invalid entry is a float.
if(isDecimal==true)
{
System.out.println("Entry must be a number. Not a letter or symbol. Try Again.\n");
}
else
{
System.out.println("Entry must be a whole number. Not a letter, decimal, or symbol. Try Again.\n");
}
/*This boolean is so that the below if statement does not run if the user enters a letter
since the integer defaults back to a 0 on exception.*/
NonNumeric = true;
}
if(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0)
{
System.out.println("Number must be greater than 0.\n");
}
}
}
private void菜单()
{
布尔非数值=假;
//这是一个不同的例外,因为它是一个浮动的最低赌注抛出。
布尔值isDecimal=false;
while(getRounds()如果您不想对用户友好:
do{
System.out.println("Enter number of rounds. Rounds must greater than zero.");
setRounds(input.nextInt());
}while( getRounds()<=0);
do{
System.out.println(“输入轮数。轮数必须大于零”);
setRounds(input.nextInt());
}while(getRounds()模块化。创建一个方法(甚至一个类),该方法接受输入并仅在满足条件时才接受它。例如
private int myIntGetter(String caption, boolean forcePositive) {
System.out.println(caption);
Scanner input = new Scanner(System.in);
int intValue = input.nextInt();
while ((forcePositive) && (intValue <=0)) {
System.out.println("Number must be greater than \0");
System.out.println(caption);
intValue = input.nextInt();
}
// here intValue is valid
return intValue;
}
private int myIntGetter(字符串标题,布尔值forcePositive){
System.out.println(标题);
扫描仪输入=新扫描仪(System.in);
int intValue=input.nextInt();
而(正),(intValue你所说的格式是什么意思?它是正确缩进的。就我个人而言,我会停止在一个巨大的循环中检查所有格式的有效性,并单独要求每个格式。我现在觉得很愚蠢。为什么我没有想到这一点。@DrinkJavaCodeJava:除了一行代码之外,所有代码都有16个缩进空格。我不会称之为“正确缩进”人生教训:不要老是说自己愚蠢;这很愚蠢。更进一步,创建可以在任何地方重用的验证例程。