Java选择是添加还是减去

时间:2013-10-20 20:02:42

标签: java add subtraction

我的问题很简单,为什么ddoesnt添加,如果我选择+ m并减去,如果我选择 -

这里有所有帮助。在此先感谢,我在这里做错了,我知道我在正确的轨道上

public static void main(String[] args) throws Exception {

    int tal1, tal2;
    char operator;

    Scanner input1 = new Scanner(System.in);
    Scanner input2 = new Scanner(System.in);
    Scanner input3 = new Scanner(System.in);

    System.out.println("Write in a 1st integer");
    tal1 = input1.nextInt();

    System.out.println("Write in 2nd intger");
    tal2 = input2.nextInt();

    System.out.println("Do you want to add or subtract please choose + or -");
    operator = (char) input3.nextInt();

    if (operator == '-') {
        System.out.println("Tal1 - Tal2 = " + (tal1 - tal2));
    } else if (operator == '+') {
        System.out.println("Tal1 + Tal2 = " + (tal1 + tal2));
    }

    System.out.println("Wrong thing to do buddy");

}

2 个答案:

答案 0 :(得分:0)

使用next()而不是nextInt()并使用String而不是char并将字符串与str_1.equals("+")进行比较如果字符串匹配则返回true

答案 1 :(得分:0)

Okey Friend:

你有两个错误:

1-你没有在public static void main之前开始上课。

2-您在此行中有错误。

operator = (char)input3.nextInt();

'+'ans' - '不是int。所以你不能为他们得到一个int。

而是使用我为您编写的以下代码:

class Test2
{
public static void main(String[] args) 
{


int tal1, tal2;
char operator;

Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner (System.in);
Scanner input3 = new Scanner (System.in);

    System.out.println("Write in a 1st integer");
    tal1=input1.nextInt();

    System.out.println("Write in 2nd intger");
    tal2=input2.nextInt();




    System.out.println("Do you want to add or subtract please choose + or -");
    operator = input3.nextLine().charAt(0);




    if (operator == '-')
    {
        System.out.println("Tal1 - Tal2 = "+(tal1-tal2)); 
    }

    else if (operator == '+')
    {

            System.out.println("Tal1 + Tal2 = "+(tal1+tal2)); 
    }

        System.out.println("Wrong thing to do buddy");
}


}