首页 > 解决方案 > 我很难让我的循环工作

问题描述

我很难让循环工作。如果用户在开始时键入“退出”或“退出”,则循环应该有一个输出,但如果没有输入退出,则继续处理。

但是,我尝试了一个 do 循环,因为一旦它不适用于给定的参数,它将运行循环。我也根本无法使用 if/else 语句。我正在使用 Eclipse 按照教授的指示进行编码/编译。

这是我目前的片段:

public static void main(String[] args) {
    Scanner scan= new Scanner (System.in);
    String fullName;
    int total= 0;
        System.out.print("Please enter your full name: ");
        fullName= scan.nextLine(); //Scans user input for name
        int count= fullName.length()-1;//Evaluates the length of the user's name
        while (fullName.equalsIgnoreCase("Quit || quit")) 
        {   
        System.out.println("Thank you for using the system. Come back soon.");
        }
        {   
            System.out.println("Please enter "+count+" numbers and the total will be calculated\n");
                    for (int i=0; i<count; i++) {
                    int userEnteredNum= scan.nextInt();
                    total += userEnteredNum;
                }
            System.out.println("Good day, "+ fullName+ "! You have entered "+
            count+ " numbers.\nThe total of all the numbers is "+ total);
        }
        while (fullName.equalsIgnoreCase("Quit || quit")); 
}

}

如果用户键入退出,它应该显示一条感谢消息而不是继续。如果用户没有键入quit,程序应该继续并要求用户根据姓名的字符长度输入数字,并将它们相加,然后重复直到用户键入quit。

使用我拥有的当前版本,会发生以下情况:

“请输入您的全名:退出请输入3个数字,然后计算总数”

或“请输入您的全名:Jane Lane 请输入8个数字,将计算总数

1 2 3 4 5 6 7 8 美好的一天,简·莱恩!您输入了 8 个数字。所有数字的总和是 36"

标签: javaloops

解决方案


    public static void main(String[] args) {
        while (true) {
            Scanner scan = new Scanner(System.in);
            String fullName;
            int total = 0;
            System.out.print("Please enter your full name: ");
            fullName = scan.nextLine(); //Scans user input for name
            int count = fullName.length() - 1;//Evaluates the length of the user's name
            if (fullName.equalsIgnoreCase("Quit")) {
                System.out.println("Thank you for using the system. Come back soon.");
                return;
            }
            System.out.println("Please enter " + count + " numbers and the total will be calculated\n");
            for (int i = 0; i < count; i++) {
                int userEnteredNum = scan.nextInt();
                total += userEnteredNum;
            }
            System.out.println("Good day, " + fullName + "! You have entered " +
                    count + " numbers.\nThe total of all the numbers is " + total);
        }
    }

推荐阅读