【问题标题】:Why is this java calculator giving me this answer?为什么这个 java 计算器会给我这个答案?
【发布时间】:2014-07-12 09:43:25
【问题描述】:

我给自己做了一个计算器:

import java.io.*;

public class Jcal_00_b2 {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 */


public static void main(String[] args) throws IOException {
    int a;
    a = 0;
    int b;
    b = 0;
    int res = 0;
    String c;
    String men;
    BufferedReader ra = new BufferedReader(new InputStreamReader (System.in));
    BufferedReader rb = new BufferedReader(new InputStreamReader (System.in));
    BufferedReader rc = new BufferedReader(new InputStreamReader (System.in));
    BufferedReader rmen = new BufferedReader(new InputStreamReader (System.in));
    System.out.println("Jcal 0.0 b2.....type start to add type help for help and credits.");
    men= rmen.readLine();
    if(men.equals("")){
        System.out.println("Give input please");
        men= rmen.readLine();
    }else if(men.equals("start")){
    System.out.println("Type first number");
    a=(int) ra.read();
     System.out.println("Type Second number");
     b=(int) rb.read();
      System.out.println("Type operation (*,/,+,-)");
      c=rc.readLine();
      if(c.equals("+")){
          res=a+b;
      }else if(c.equals("-")){
        res=a-b;  
      }else if(c.equals("*")){
          res=a*b;
      }else if(c.equals("-")){
        res=a/b;   
      } 
      System.out.println("result:" +res);
      System.out.println("You gave input: \n 1st no.="+a+"\n 2nd no.="+b );

}else if(men.equals("help")){
    System.out.print("first type start to start the calc.\n then input first number, input second number then input the operator. \n the operator symbols are as follows:\n + for addition \n - for subtraction \n * for multiplication \n / for division  ");

}


}



}

当我运行它时,它会显示以下输出:

Jcal,一个计算器.....键入开始添加类型帮助以获得帮助和学分。

开始

输入第一个数字

1

输入第二个数字

1

类型操作(*,/,+,-)

*

结果:2401

您提供了意见:

第 1 号=49

第 2 号=49

我做错了什么?

【问题讨论】:

    标签: java calculator


    【解决方案1】:

    您的问题是BufferedReader 的read 方法从BufferedReader 返回单个字符的ASCII 值。单个数字'1'的ASCII值是49。

    您可能要考虑使用Scanner 而不是BufferedReader,并使用nextInt() 方法。那你就不会有这个问题了。

    此外,您只需要一个 Scanner 对象,而不是您希望读取的每个值一个。

    还有一点需要注意 - 您可以在 Scanner 对象上调用 nextLine(),但如果您刚刚调用了 nextInt(),则可能在带有运营商。您可能需要拨打nextLine() 两次。也就是说,Scanner 可能包含类似"1 newline 1 newline * newline" 的内容——在这种情况下,您需要调用nextInt()(获取第一个1)、nextInt()(获取第二个1)、@987654338 @(获取第二个换行符)然后 nextLine() 再次获取 * 字符。

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2021-04-06
      • 1970-01-01
      • 2021-11-18
      相关资源
      最近更新 更多