基本计算器

时间:2014-11-26 22:46:50

标签: java calculator

需要帮助了解如何正确使用此功能。它只会以" New"不是" Void()"当我到达Scan.line时它会崩溃。 我还必须学习如何绘制线性函数,例如y = mx + b等。这是我第一次做一个如此大的项目,我渴望真正发展我的分析思维技能,以便成为一名程序员。请一些帮助将不胜感激。

import java.util.Scanner;
public static class Calculator
{ 
int Number1;
int Number2;
String Operation;
int Final;

  public static void main(String[] args)
  {
      Scanner scan = new Scanner(System.in);

   System.out.println ("Enter your first number: ");
   Number1 = scan.nextInt();
   System.out.println ("Number 1: " + Number1 + " Number 2: " + Number2);
   System.out.println ("Ener your second number: ");
   Number2 = scan.nextInt();
   System.out.println ("Number1: " + Number1 + " Number 2: " + Number2);
   System.out.println ("Enter numericle operation you wish to preform: ");
   Operation = scan.nextLine();

   if ( Operation == "+" )
   {
    Final = (Number1 + Number2);
    System.out.print("Ans: " + Final);
   }
   if ( Operation == "-" )
   {
    Final = (Number1 - Number2);
    System.out.print("Ans: " + Final);
   }
   if ( Operation == "*" )
   {
    Final = (Number1 * Number2);
    System.out.print("Ans: " + Final);
   }
   if ( Operation == "/" )
   {
    Final = (Number1 / Number2);
    System.out.print("Ans: " + Final);
   }
}
}

1 个答案:

答案 0 :(得分:0)

我们制作的所有评论都与您的代码相关。

你认为这会发生什么?

   Number1 = scan.nextInt();
   System.out.println ("Number 1: " + Number1 + " Number 2: " + Number2);

你没有设置Number2的值,所以它应该给你一个NullPointerException.

稍后不要将字符串与“==”进行比较,因为它们会查看它们比较引用的对象,而不是值,只有原始类型的比较值。

if ( Operation == "*" )

应该是

if ( Operation.equals("*")

最后但并非最不重要的是,常见的java约定是在每个if-else,循环,方法,类等的块之后放置大括号。不在下一行:

public static class Calculator
{ 

应该是

public static class Calculator {

但这只是java的惯例问题。