我一直在努力处理这个循环分配。我可以使程序按预期工作,但是,如果用户未输入值,则代价是在末尾有额外的文本。如果我编写代码以使未输入值的用户没有此额外文本(即最大数字为 0 并且最大数字的计数为 0),则循环不起作用。我的代码包含在下面。这是怎么回事?
//Name:
//Date:
//File:
//Description: Program that allows the user to enter numbers and determine the maximum value as well as count how many times that maximum value is entered.
import java.util.Scanner;
public class lab4b_hmcka
{
public static void main (String [] args)
{
//variables
int num1, num2, max1 = 0, max2 = 0, count = 0, maxCount = 0;
System.out.println(" Find the maximum number");
System.out.println();
System.out.print("Enter an integer <0 ends the input>: ");
Scanner input = new Scanner(System.in);
num1 = input.nextInt();
if (num1 ==0)
{
System.out.println("No numbers are entered except 0");
}
while (num1 != 0)
{
if (maxCount == 0)
{
System.out.print("Enter an integer <0 ends the input>: ");
num2 = input.nextInt();
max1 = Math.max(num1, num2);
maxCount = maxCount + 1;
count = count + 1;
System.out.print("Enter an integer <0 ends the input>: ");
num1 = input.nextInt();
continue;
}
else
{
max2 = Math.max(num1, max1);
if (num1 == max1)
{
maxCount = maxCount + 1;
count = count + 1;
}
else
{
count = count + 1;
}
System.out.print("Enter an integer <0 ends the input>: ");
num1 = input.nextInt();
}
}
if (count == 1)
{
System.out.println("The maximum number is " + max1);
}
else
{
System.out.println("The maximum numberis " + max2);
}
System.out.println("The count for the max number is " + maxCount);
}
}
最佳答案
我不完全确定您想要实现什么以及您试图实现什么(无论是什么),但我假设您只是想在用户想要立即退出时终止程序(= 首先输入 0)。因此只需添加一个返回即可:
if (num1 == 0) {
System.out.println("No numbers are entered except 0");
return; // Terminate now.
}
关于java - 循环错误 - 修复循环意味着破坏其他东西,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869124/