【问题标题】:what's wrong with this very simple code [duplicate]这个非常简单的代码有什么问题[重复]
【发布时间】:2015-09-30 23:04:54
【问题描述】:

当我运行我的代码时,它会一直运行,直到它询问“您想从(sum、subst、multi、div)中使用哪个操作”这个问题。无论用户选择什么,我的程序都没有响应!

为什么会这样?

import java.util.Scanner;
import java.io.*;

public class three3 {
    public static void main (String[] args) {
        int x;
        int y;
        int opera;
        String oper;

        Scanner in = new Scanner (System.in);
        System.out.println(" write the first number ");
        x = in.nextInt();

        System.out.println(" write the second number ");
        y = in.nextInt();

        System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
        oper = in.nextLine();

        if (oper == "sum") {
            opera=x+y;
            System.out.println(" the sum of two numbers is " + opera );
        }

        if (oper == "subst") {
            opera = x - y;
            System.out.println(" the subtraction of two numbers is " + opera );
        }

        if (oper == "multi") {
            opera = x * y;
            System.out.println(" the multi of two numbers is " + opera );
        }

        if (oper == "div") {
            opera = x / y;
            System.out.println(" the division of two numbers is " + opera );
        }
    }
}

【问题讨论】:

    标签: java if-statement calculator iostream


    【解决方案1】:

    因为没有执行这些 if 子句。 您将Strings== 进行比较,这是错误的。请改用oper.equals("sum")。请参阅this question 以供参考。您的结论是始终将equals 用于Strings

    【讨论】:

    • 这不是正确的答案
    • @gurghet 我错过了胡安回答中的错误,但我要解决的问题仍然是意外行为的原因。
    • 没有错误响应。没有没有响应
    • 谁对回复说了什么?
    【解决方案2】:

    您需要在最后一次调用 in.nextInt() 之后立即调用 in.nextLine() 原因是只要求下一个整数不会消耗输入中的整行,因此您需要跳到下一个新的- 通过调用in.nextLine()在输入中的行字符。

    int y = in.nextInt();
    in.nextLine();
    

    每次在调用不消耗整行的方法后需要获取新行时,这几乎都必须完成,例如当您调用nextBoolean() 等时。

    此外,您无需使用== 运算符检查字符串是否相等,而是使用.equals() 字符串方法。

    【讨论】:

    • 这是正确答案
    【解决方案3】:

    问题是in.nextLine() 在输入 int 后单击 enter 时会使用隐式插入的 \n。这意味着程序不期望用户提供任何其他输入。要解决此问题,您可以使用 in.nextLine() 的新行,然后将其放入您的实际变量中,如下所示:

    System.out.println(" write the second number ");
    y=in.nextInt();
    
    System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
    
    in.nextLine(); //New line consuming the \n
    
    oper=in.nextLine();
    
    if(oper.equals("sum")){//replace == by .equals
       opera=x+y;
    }
    

    除此之外,正如 runDOSrun 所说,您应该将字符串的比较从 a==b 替换为 a.equals(b)

    【讨论】:

      【解决方案4】:

      根据其他人的观点,您还应该考虑使用else if{}else{} 语句,以便捕获无效输入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-16
        相关资源
        最近更新 更多