-1

我最近创建的计算器出现了一些问题。
我不太清楚哪里出了问题,我必须做什么,所以我希望能得到一些帮助。

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);
    }
}
}
4

2 回答 2

4

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

为什么?Answer是一个int,不是一个char

if永远不会满意,因为当您这样做时,if(Answer == '1')您实际上是在与字符Answer十进制值'1'进行比较。

建议

  1. 遵循Java 命名约定- 以小写开头的变量命名。
  2. if((Answer == 1))可以写if(Answer == 1)
  3. 在这些情况下使用switch-case而不是。if
  4. 命名sum其他东西,因为它并不总是“求和”操作。可能的名称:result.
于 2013-11-14T09:04:13.927 回答
1

您正在将 Answer 与字符值 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);
    }
于 2013-11-14T09:05:37.667 回答