gpt4 book ai didi

java - 致力于循环迭代。有没有办法调用这些方法而不会有几个 "do"声明

转载 作者:行者123 更新时间:2023-11-30 07:53:14 27 4
gpt4 key购买 nike

        //Setting my variables.

Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;

//Loop iterations to resolve error, and determine value for each input.

do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();

if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);

do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();

if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}

所以,这是我的代码。我正在尝试循环和 if-else 类型语句。我觉得,我的方法太复杂了,可以很容易地总结或修改。有谁知道如何处理,只声明一个 do 语句?这段代码正处于我的实验的开始阶段,还有很多工作要做。但在我继续之前,我希望能有另一双眼睛!

最佳答案

在有效输入上使用带有 break 的无限循环。增强了处理不良输入的能力。

Scanner keyboard = new Scanner(System.in);

int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");

double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");

关于java - 致力于循环迭代。有没有办法调用这些方法而不会有几个 "do"声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33047665/

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