0

I have been working with Java for a very short time, so please be patient with me. I'm working on a program for an INTRODUCTION to java class and I have to create a simple calculator (no GUI) without using exceptions, but that still captures input errors. I was able to do the exception handler with no problem, but this one is driving me bonkers!! I need an alternative to the statement "if (a==char || b==char)" Here's what I have so far:

import java.util.*;

public class calculator_No_Event {

public static void main(String[] args) 
{
    // TODO Auto-generated method stub
    int a,b,c;
    char d;
    boolean e;
    Scanner input=new Scanner(System.in);

    try
    {   
        System.out.print(" Enter the first number: ");
        a=input.nextInt();
        System.out.print("Enter the second number: ");
        b=input.nextInt();
        System.out.print("Enter + or - :");
        String f=input.next();
        d=f.charAt(0);


        if (a==char || b==char)
        {
            System.out.println("Error");
        }   
        else
        {
            switch(d)
            {
                case '+':
                    c =a+b;
                    System.out.print(a + "+" + b + "=" + c);
                    break;
                case '-':
                    c =a-b;
                    System.out.print(a + "-" + b + "=" + c);
                    break;
            }
        }
}
    finally
    {
        System.out.println("Thank you.");
    }
}

}

4

2 回答 2

2

你应该在打电话Scanner.hasNextInt()之前打电话Scanner.nextInt()。与Scanner.hasNext()和 也是如此Scanner.next()

于 2014-11-10T17:52:18.763 回答
0

你对这一行有很多误解

if (a = char || b = char)
  1. 我假设您的意思是使用equal to运算符,而不是assignment运算符== instead of =

  2. ab(c) 是ints,如 中所声明的main。所以我们知道它们永远不会是chars,除非您将它们转换为字符 - 但它们将永远是字符。int并且char是不同的类型,并且1角色可以是任何一种类型 - 所以尝试按照你的方式去做是行不通的。

  3. 谷歌搜索检查字符串是否为数字返回确定字符串是否是 Java 中的整数,但是,在这种情况下,@ElliottFrisch 的答案是您可能想要使用的方法。每当您使用新的 Java 类(Scanner )时,学习查看文档非常有价值,并且可以更好地理解和了解您正在使用的类。

于 2014-11-10T18:21:35.957 回答