Ok, I think this should be ok to post since I have tried for a while on my own, if not then I apologize.
I have to make a very basic calculator for my Java class. I can get all the user inputs stored correctly, but I am having trouble running strings through my if statements. I have tried a number of ways, but each had its own problems. I think it would work if I could cast my string into a char, but that seems to be impossible. Here is what I have so far.
import java.awt.Container;
import javax.swing.*;
public class Calc extends JApplet {
public void init() {
String s1 = JOptionPane.showInputDialog("First number.");
String s2 = JOptionPane.showInputDialog("Operation.");
String s3 = JOptionPane.showInputDialog("Second number.");
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(s3);
double ans = answer(n1, s2, n2);
JTextArea outputArea = new JTextArea();
outputArea.setText(n1 + " " + s2 + " " + n2 + " = " + ans);
Container container = getContentPane();
container.add(outputArea);
}
public double answer(double x, String o, double y) {
if (o == "+")
return (x + y);
if (o == "-")
return (x - y);
if (o == "*")
return (x * y);
if (o == "/")
return (x / y);
return 0.0;
}
}
I have to make a very basic calculator for my Java class. I can get all the user inputs stored correctly, but I am having trouble running strings through my if statements. I have tried a number of ways, but each had its own problems. I think it would work if I could cast my string into a char, but that seems to be impossible. Here is what I have so far.
import java.awt.Container;
import javax.swing.*;
public class Calc extends JApplet {
public void init() {
String s1 = JOptionPane.showInputDialog("First number.");
String s2 = JOptionPane.showInputDialog("Operation.");
String s3 = JOptionPane.showInputDialog("Second number.");
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(s3);
double ans = answer(n1, s2, n2);
JTextArea outputArea = new JTextArea();
outputArea.setText(n1 + " " + s2 + " " + n2 + " = " + ans);
Container container = getContentPane();
container.add(outputArea);
}
public double answer(double x, String o, double y) {
if (o == "+")
return (x + y);
if (o == "-")
return (x - y);
if (o == "*")
return (x * y);
if (o == "/")
return (x / y);
return 0.0;
}
}