有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Switch case不适用于我的while循环?

嘿,我是一个非常新手的程序员,我正在尝试创建一个普通的计算器程序。然而,一旦我使用了这段代码,它就会跳过我的开关状态,并立即转到默认状态。我该怎么解决这个问题

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) 个答案

  1. # 1 楼答案

    在获取int输入后,需要使用ramim.nextLine();两次来获取字符串输入。这是因为ramim.nextInt();不会读取您键入的最后一个ENTER字符。所以你可以这样做:

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