我如何修正关于switch语句的输出?

问题描述 投票:0回答:1

我的程序输出出现问题。假定发生的事情是用户要选择要使用的方法。然后,程序将根据该选择来执行switch语句,并为用户输入的任何方法和值输出相应的总和或乘积。

但是,程序显示菜单选择,但仅输出错误消息。我已经有一段时间了这个错误,但老实说我不知道​​我在做什么错。我请你原谅我的无知,因为我已经很长时间没有编程了。

import java.util.Scanner;
public class Sum {
    public static void main(String[] args)
    {
        String sum = "S";
        String factorial = "F";

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter " + sum + " to use the sum method or " + factorial + " to use the factorial method.");
        String userSelection = scan.next();

        switch (userSelection.toLowerCase()) {
            case "sum":
                System.out.println("Enter the number you want to use: ");
                int userValue = scan.nextInt();
                int userSum = sum(userValue);
                System.out.println("The resulting value for the sum method is: " + userSum);
                break;

            case "fact":
                System.out.println("Enter the number you want to use: ");
                int userFact = scan.nextInt();
                int userFactorial = fact(userFact);
                System.out.println("The resulting value for the factorial method is: " + userFactorial);
                break;
            default:
                System.out.println("ERROR: Invalid choice.");
            }
            scan.close();
    }
    public static int sum(int num) {
        int sum = 0;
        for (int i = 1; i <= num; i++) {
            sum = i + sum;
        }
        return sum;
    }
    public static int fact(int num) {
        int fact = 1;
        for (int i = 1; i <= num; i++) {
            fact = i * fact;
        }
        return fact;
    }
java input switch-statement output java.util.scanner
1个回答
0
投票

您正在将用户输入与错误的字符串进行比较。您要求他键入“ S”或“ F”,然后将此输入与“ sum”和“ fact”进行比较。

© www.soinside.com 2019 - 2024. All rights reserved.