I tried making a very basic calculator, but if I try to output the calculated result I get the error that my variable "result" has not been initialised, even though I did initialise it inside the if-statement at the bottom. When I put the "System.out" line in my if-statement it works, so I have been wondering how can initialise a variable in my statement and keep the value.
Sorry if this was asked before, but all I found were threads that talked about using "return" to give out a value, but not a variable.
import javax.swing.JOptionPane;
class Calculator{
public static void main(String[] args)
{
double z1, z2, result;
String input, s;
input = JOptionPane.showInputDialog("Input a number:");
//check whether or not the input is a number
if(isNumber(input) == false)
{
JOptionPane.showMessageDialog(null, "Input a real Number", "Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
z1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Input a second number:");
//check whether or not the input is a number
if(isNumber(input) == false)
{
JOptionPane.showMessageDialog(null, "Input a real number", "Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
z2 = Double.parseDouble(input);
s = JOptionPane.showInputDialog("Input an operation(+,-,*,/):");
if(s.equals("+"))
{ result = z1 + z2; }
if(s.equals("-"))
{ result = z1 - z2; }
if(s.equals("*"))
{ result = z1 * z2; }
if(s.equals("/"))
{ result = z1 / z2; }
System.out.println(result);
Aucun commentaire:
Enregistrer un commentaire