I have tried making a simple random calculator and its not working?
I have tried making this calculator to get used to working with classes, methods, return statements, etc..., but the method that should return my result won't return anything. I have tried using the debug mode in Eclipse but that didn't help me either.
Main method:
Code :
public class CalculatorMain { //class CalculatorMain
public static void main(String[] args) { //main method
Calculator1 a = new Calculator1(); //new class a
JOptionPane.showMessageDialog(null, "This is a primitive Calculator"); //startup message
a.input(); //input method
double y = a.input(); //create y which equals the return value of input method
JOptionPane.showMessageDialog(null, y); //shows result
}
}
Calculator method:
Code :
package calculator;
import javax.swing.JOptionPane;
public class Calculator1 {
double b;
double a;
double input()
{
a = Double.parseDouble(JOptionPane.showInputDialog("Enter your first number: ")); //shows input and sets a
b = Double.parseDouble(JOptionPane.showInputDialog("Enter your first number: ")); //shows input and sets b
String c = JOptionPane.showInputDialog("Type a(dd), s(ubtract), m(ultiply), d(evide)"); //asks for a, b, c or d
if (c == "a"){
return a + b;
}
else if (c == "s"){
return a - b;
}
else if (c == "m"){
return a * b;
}
else if (c == "d"){
return a / b;
}
return 0;
}
}
Thanks for any help, I am new to coding and teaching java to myself, so the only place I can go for help is the internet.
-StackOfCookies
Re: I have tried making a simple random calculator and its not working?
Re: I have tried making a simple random calculator and its not working?
From the Java String class descriptions of the 'equals()' method at Java String Class:
Quote:
equals
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Bottom line: Don't use something like (c =="a") to compare one String to another. Use c.equals("a")
Cheers!
Z