切换机箱不适用于我的while循环?

时间:2018-04-08 20:37:21

标签: java switch-statement java.util.scanner

嘿,我是一个非常新手的编码员,我正在尝试创建一个平均的计算器程序。但是,一旦我使用此代码,它会跳过我的开关案例并立即转到我的默认情况。我该如何解决这个问题?

import java.util.*;

class AverageCalculator {
    public static void main(String[] args) {
        Scanner ramim = new Scanner(System.in);
        int totalToAverage;
        int counter = 1;
        int ans;
        String ans2;
        int tally = 0;

        System.out.print("How many different inputs do you want to put in?: ");
        totalToAverage = ramim.nextInt();
        System.out.println("Your input # is " + totalToAverage + ".");

        while (counter <= totalToAverage) {
            System.out.print("Enter number " + counter + ":");
            counter++;
            ans = ramim.nextInt();
            tally = ans + tally;
        }

        System.out.println("You have entered " + --counter + " numbers." + "Your total is " + tally + ".");

        System.out.println("Would you like to find your average?");
        ans2 = ramim.nextLine();

        switch (ans2) {
        case "yes":
            System.out.println("note: dont worry about this part yet");
            break;

        case "no":
            System.out.println("Alright.");
            break;

        default:
            System.out.println("Please enter yes or no only. :)");
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在获得int输入后,您需要使用ramim.nextLine();两次来获取String输入。这是因为ramim.nextInt();无法读取您输入的最后一个ENTER字符。所以做一些像:

System.out.println("Would you like to find your average?");
ramim.nextLine();
ans2 = ramim.nextLine();