Java (I hate strings)

asyork

2[H]4U
Joined
Jan 3, 2002
Messages
2,059
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;
}
}
 
*mumbles something about how much he hates programming*

After days of broken code I manage to figure this out minutes after I post it... I was looking at my history and realized that one of the other things I had tried, compareTo, that hadn't worked only didn't work because I had some minor typos. I called the wrong string into my method... Oh well, works now.
 
if (str1.equals(str2))...

also, you may want to use single chars instead of strings, you can directly compare chars with == or use a switch (nudge..)
 
Back
Top