计算器程序问题

时间:2013-11-14 09:00:25

标签: java

我最近创建的计算器遇到了一些问题 我不知道出了什么问题,我必须做什么,所以我希望得到一些帮助。

public class calcclass {

public static void main(String []args){

    Scanner input = new Scanner(System.in);
    int numberone;
    System.out.print("Type in a number : ");
    numberone = input.nextInt();
    System.out.println("");
    System.out.print("Type in another number : ");
    int numbertwo = input.nextInt();
    System.out.println("");
    System.out.print("Do you wish to 1(+), 2(-), 3(*), 4(/) : ");
    int Answer = input.nextInt();
    System.out.println("");
    int Sum;
    if (( Answer == '1'))
    {
        System.out.println("PLUS");
        Sum = numberone + numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if (( Answer == '2'))
    {
        System.out.println("MINUS");
        Sum = numberone - numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if (( Answer == '3'))
    {
        System.out.println("GONGE");
        Sum = numberone * numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if (( Answer == '4' ))
    {
        System.out.println("DELE");
        Sum = numberone / numbertwo;
        System.out.println("The answer is : " + Sum);
    }
}
}

2 个答案:

答案 0 :(得分:4)

if (( Answer == '1'))应为if (( Answer == 1))

为什么呢? Answerint,而不是char

您的if永远不会满意,因为当您执行if(Answer == '1')时,您实际上是在将Answer与角色'1'的{​​{3}}进行比较。

<强>推荐

  1. 关注decimal value - 在开头使用小写命名变量。
  2. if((Answer == 1))可以写成if(Answer == 1)
  3. 在这些情况下,请使用Java Naming Convention代替if
  4. sum命名为其他内容,因为它并不总是“sum”操作。可能的名称:result

答案 1 :(得分:1)

您正在将答案与字符值1,2,3,4进行比较。例如:

System.out.println((int) '1');

会打印49;

使用此代码,不带数字引号:

if ((Answer == 1)) {
        System.out.println("PLUS");
        Sum = numberone + numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if ((Answer == 2)) {
        System.out.println("MINUS");
        Sum = numberone - numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if ((Answer == 3)) {
        System.out.println("GONGE");
        Sum = numberone * numbertwo;
        System.out.println("The answer is : " + Sum);
    }
    if ((Answer == 4)) {
        System.out.println("DELE");
        Sum = numberone / numbertwo;
        System.out.println("The answer is : " + Sum);
    }