I don't understand why this simple program will not print. Help please!!!
This program runs with no errors, it just doesn't print anything. Anyone have a clue as to why it doesn't print anything?
Here is my code:
import javax.swing.JOptionPane;
public class Converter {
public static void main(String[] args) {
int a,b,c;
int inputNum=Integer.parseInt(JOptionPane.showInputDialog(null," Enter a length in yards: "));
String measurement = JOptionPane.showInputDialog(null,"Enter the unit of conversion (inches, feet, or centiyards): ");
if (measurement == "inches"){
a = inputNum*36;
System.out.println(a + "inches");
}
else if (measurement == "feet"){
b = inputNum*3;
System.out.println(b + "feet");
}
else if (measurement == "centiyards"){
c = inputNum*100;
System.out.println(c + "centiyards");
}
}
}
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // true
For more information, check out [url=http://access1.sun.com/FAQSets/newtojavatechfaq.html#9]the Java FAQ[/url]
~
BTW, one of the few legitimate uses for String(String) is the following:
String longString = getALongStringFromSomewhere();
String shortString = longString.substring(lo, hi);
hold.ontoIt = new String(shortString);
Method substring returns a String object that shares its underlying char[] with
this string. This may result in not GCing a large char[] just because you want
to remember a short sequence of its characters. Does that make sense?