我现在正在为我的5年薪资比较计划尝试各种类型的Java循环。到目前为止,我似乎在尝试do-while循环时遇到问题。我使用NetBeans构建程序,并且在其中编写do-while循环时,会产生一些我不知道如何解决的错误。也许我的措词听起来不正确,但让我们在下面检查一下是否需要重写:
do {
System.out.println("Enter the salary individual 1 got in year 1: ");
firstIndividualSalary[0] = scan.nextInt();
System.out.println("Enter the salary individual 2 got in year 1: ");
secondIndividualSalary[0] = scan.nextInt();
if (firstIndividualSalary[0] == secondIndividualSalary[0]) {
System.out.println("Error. Try again.");
areAllDifferent = false;
input.next();
}
else {
areAllDifferent = true;
}
while (!(areAllDifferent));
如果在用户输入正确之前,do-while循环不是让用户重新输入答案的正确选择,那么请让我知道while循环或for循环在构建完全无错误的代码中是否更有意义程序。我个人觉得完全不像do-while循环。我只需要弄清楚如何使用户重新输入几个答案,这样他们就不会最终相互匹配。我需要找出相同的问题来计算2个人的5年工资总额。如果您对此有所了解并提出一些修订建议,我将不胜感激。谢谢。
最佳答案
如果do-while
循环在使用户输入正确之前不是让用户重新输入答案的正确选择,那么请让我知道while循环或for循环在构建完全无错的方法中是否更有意义程序。do-while
完全适合此目的。实际上,do-while
循环可确保do-while
块中的代码至少执行一次,这在这种情况下是理想的。
您的代码结构如下所示:
do {
areAllDifferent = true;
System.out.println("Enter the salary individual 1 got in year 1: ");
firstIndividualSalary[0] = Integer.parseInt(scan.nextLine());
System.out.println("Enter the salary individual 2 got in year 1: ");
secondIndividualSalary[0] = Integer.parseInt(scan.nextLine());
if (firstIndividualSalary[0] == secondIndividualSalary[0]) {
System.out.println("Error. Try again.");
areAllDifferent = false;
}
} while (!areAllDifferent);
请注意,我已经使用
Integer.parseInt(scan.nextLine())
而不是scan.nextInt()
来避免next()
,nextInt()
等问题,如here所述。
关于java - 这些循环听起来是否正确,还是应该切换为for或while循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61687928/