初学者试图编写一个简单的计算器 [英] Beginner trying to program a simple calculator

查看:92
本文介绍了初学者试图编写一个简单的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用Java,并尝试编写一个简单的计算器:

I just started Java and was trying to program a simple calculator:

我尝试了以下内容:

    double x, y; //inputs
    Scanner sc = new Scanner(System.in);
    System.out.println("x?");
    x = sc.nextDouble();
    System.out.println("y?");
    y = sc.nextDouble();

    double answer = 0;

    System.out.println("Operation type: (+,-,*,/)");


    String opStr= sc.nextLine();
    char op = opStr.charAt(0);


    switch(op)
    {
        case '+':
            answer=x+y;
            break;

        case '-':
            answer=x-y;
            break;

        case '*':
            answer=x*y;
            break;

        case '/':

            if (y==0)
            {
                System.out.println("Error, can't divide by zero");
            }
            else
            {
                answer=x/y;
            }

            break;
        default: System.out.println("Unkown operation");
    }  // switch end

    System.out.println("answer = " +x+op+y+"=" + answer);

当我尝试运行它时,我得到以下内容:(我可以输入x和y,但之后我收到错误信息。

When I try to run it I get the following: (I can input x and y, but afterwards I get the error message.

Operation type: (+,-,*,/)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:686)
    at edf_1.EDF_1.main(EDF_1.java:170)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)



Would be really grateful if anyone can help me find the mistake or issue!

谢谢

NaC


NaC

推荐答案

nextDouble() 所以当你打电话 nextLine()输入( \\\
)。所以它正在跳过实际的输入,并从以前的输入中删除 nextLine()错过的 \\\
。您应该在真正的 nextLine()之前调用另一个 nextLine()(所以它会吞下 \\\
)。

nextDouble() doesn't handle the end of the line. So when you call nextLine() again, it'll take as input the enter (\n) you entered before. So it's skipping the actual input and swallows the \n from the previous input that was missed by nextLine(). You should call another nextLine() before the real nextLine() (So it will swallow the \n).

如果您不想这样做,您应该构建另一个 Scanner 而不是使用相同的对象。

If you don't want to do that, you should construct another Scanner rather than using the same object.

这是你的 StringIndexOutOfBoundsException opStr 目前只有一个 \\\

That's the reason of your StringIndexOutOfBoundsException, opStr is only a \n at this point.

这篇关于初学者试图编写一个简单的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆