Reputation: 98
I've been wondering about what is wrong with my code
String s = JOptionPane.showInputDialog(null,"Enter discount type");
if(s == "PWD"){
dis = 0.25;
}
else{
dis = 0;
JOptionPane.showMessageDialog(null, s);
}
when I run my program, it performs the code in the 'else' block instead of doing what is in the 'if' block. Thanks!
Upvotes: 1
Views: 1166
Reputation: 59
==
calling a reference similarity
and .equals()
check the value similarity so its better to use a (s.equals("PWD"))
Upvotes: 0
Reputation: 777
==
tests for reference equality (whether they are the same object).
.equals()
tests for value equality (whether they are logically "equal").
Objects.equals()
checks for nulls before calling .equals() so you don't have to (available as of JDK7, also available in Guava).
try like this
if(s.equals("PWD"))
Upvotes: 2
Reputation: 43
import javax.swing.JOptionPane;
public class Testing {
public static void main(String[] args) {
double dis = 0;
// TODO Auto-generated method stub
String s = JOptionPane.showInputDialog(null,"Enter discount type");
if(s.equalsIgnoreCase("PWD")){
dis = 0.25;
}
else{
dis = 0;
JOptionPane.showMessageDialog(null, s);
}
System.out.println(dis);
}
}
Try this I used .equalsIgnoreCase instead of ==
Upvotes: 1
Reputation: 1776
if you use:
s == "PWD"
java defines another String by "PWD" value and compare the references of s and the new var you have to use:
s.equals("PWD")
Upvotes: 2
Reputation: 8247
You should be using equals method of string.
`s.equals("PWD")` instead of `s == "PWD"` or `equalsIgnoreCase(...)` for case insensitive comparison.
Upvotes: 1