need help, this is my code!

import javax.swing.JOptionPane;

public class Lab2_1 {
	public static void main(String[] args) {
		int value1=0 ,value2=0 ,operator=0;
		String temp4="1";
		while(temp4 != "0" ){
			String temp1 = JOptionPane.showInputDialog(null,"Please enter first value.");
			value1=Integer.parseInt(temp1);
			
			String temp2 = JOptionPane.showInputDialog(null,"Please enter operator.(+,-,*,/)");
			
			String temp3 = JOptionPane.showInputDialog(null,"Please enter second value.");
			value2=Integer.parseInt(temp3);
			
			if (temp2 == "+") {
				int total=value1+value2;
				JOptionPane.showMessageDialog(null,value1+" + "+value2+" = "+total);}
				
			else if (temp2 == "-") {
				int total=value1-value2;
				JOptionPane.showMessageDialog(null,value1+" - "+value2+" = "+total);}
				
			else if (temp2 == "*") {
				int total=value1*value2;
				JOptionPane.showMessageDialog(null,value1+" * "+value2+" = "+total);}
				
			else if (temp2 == "/") {
				int total=value1/value2;
				JOptionPane.showMessageDialog(null,value1+" / "+value2+" = "+total);}
				
			else
				JOptionPane.showMessageDialog(null,temp2+" is not a valid operator.");
			
			temp4 = JOptionPane.showInputDialog(null,"Do you still want to continue? Enter 0 to stop.");	
			
}
}
}

why i always get invalid operator only?
+ - * / is not string?

Recommended Answers

All 9 Replies

Use the equals method to compare Strings:

temp2.equals("/")

you check symbols by comparing its ASCII value...

Thanks for this valuable information about java calculator

thanks alot =) how if i wanna compare not equals to? ( != )

thanks alot =) how if i wanna compare not equals to? ( != )

equals is a boolean expression:

if (![B]s1.equals(s2)[/B]) {

}

thanks alot. just started java not long ago. helped me alot =)

i don't understand cues the input method & the so many method u use i need a code by switch and also sacrifice the continuity

i don't understand cues the input method & the so many method u use i need a code by switch and also sacrifice the continuity

You cannot String with switch so these if-else are necessary. All the methods are self explanatory. If you don't understand them, search the API or the internet in general.

And for other questions start a new thread

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.