循环错误 - 修复循环意味着破坏其他东西,反之亦然

时间:2015-09-30 14:46:42

标签: java loops

我一直在努力解决这个循环任务。我可以使程序按预期工作,但是,如果用户没有输入任何值,则以最后的额外文本为代价。如果我创建代码使得没有输入值的用户没有这个额外的文本(即最大数字是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);
    }

}

2 个答案:

答案 0 :(得分:0)

我不完全确定你想要实现什么以及你想要实现的目标(无论它是什么),但我认为如果用户想立即退出,我只想终止程序(=进入0第一)。所以只需添加一个回报:

if (num1 == 0) {
    System.out.println("No numbers are entered except 0");
    return; // Terminate now.
}

答案 1 :(得分:0)

在程序结尾的if / else语句中,你只是检查count的值是否等于1.在这种情况下,用户最初输入零的情况永远不会为真,因为我们没有输入while循环其中count是第一次递增。如果不改变代码太多,您可以简单地执行以下操作:

if(count == 1)
{
    int maxVal = Math.max(max1, max2);
    System.out.println("The max number is " + maxVal
    System.out.println("The count for the max number is " + maxCount
}

之后你可以简单地删除else,它应该为你提供你想要的输出。

此外,还有许多其他优化可以用较少的代码实现相同的结果,但我会将其留给个人学习体验。祝你好运!