-3

Need help understanding how to make this function properly. It will only run as "New" not "Void()" and when I get to the Scan.line it crashes. I also have to learn how to plot linear functions such as y = mx + b and such. This is my first time doing a project so big and I am yearning to really develop my analytic thinking skills in order to progress as a programmer. Please some help would much be appreciated.

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);
   }
}
}
Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683

1 Answers1

0

All of the commentaries we made have something relevant to add to your code.

What do you think will happen with this?

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

You havent set the value of Number2 so it should give you a NullPointerException.

Later do not compare strings with "==" when they look at objects they compare references, not values, the compare values only for primitive types.

if ( Operation == "*" )

should be

if ( Operation.equals("*")

And last but not least, the common java convention is to put the braces after the block in every if-else, loop, method, class etc. Not in the next line:

public static class Calculator
{ 

should be

public static class Calculator {

but this is just a matter of conventions for java.

Ringo
  • 853
  • 8
  • 23
  • I am blown away by the amount of self acquired knowledge that can be achieved here. Thank you very much for the tips. The error I was getting was "Non-static variable Number1 cannot be referenced from a static context". – Gregory Scott Nov 26 '14 at 23:07
  • A static variable is a CLASS variable not an INSTANCE variable, you dont need to create an object of a class to access its static members or methods. So a static method like main cant access a variables that needs an instance to exist. Read further on the static word. – Ringo Nov 26 '14 at 23:09