【问题标题】:How do I fix my output regarding my switch statement?如何修复关于我的 switch 语句的输出?
【发布时间】:2020-06-10 11:10:56
【问题描述】:

我的程序输出有问题。应该发生的是用户将选择他们想要使用的方法。然后程序将根据该选择执行 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;
    }

【问题讨论】:

  • 你要求用户输入“S”或“F”,那你为什么将输入比作“sum”和“fact”呢?
  • 啊,我知道那是我做错了。谢谢你的帮助!
  • 不是你的问题,但Gauss 注意到1n 的数字总和是((n + 1) * n) / 2(在小学)。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    相关资源
    最近更新 更多