I'm trying to keep up with you youngsters, so I'm taking a beginning Java course. As part of a homework assignment, we were to prompt the user for a number between 1 & 3. We also used while loops in the chapter, so I decided to put the prompt in a while loop to force the user to enter 1, 2 or 3. I was very surprised when it did not work, so I have written a 5-liner to show you the problem: -
import javax.swing.JOptionPane;
-
public class Weird {
-
public static void main(String[] args)
-
{
-
String s = "";
-
while (s != "1" && s!= "2" && s!= "3")
-
{
-
s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");
-
if (s == null) break;
-
}
-
if (s!= null) JOptionPane.showMessageDialog(null, s);
-
}
-
}
-
I fixed the problem by parsing the string and testing for integers 1, 2, or 3, but the above code should work! The same code in VB works great: -
Sub NotWeird()
-
Dim s As String
-
Do While (s <> "1" And s <> "2" And s <> "3")
-
s = InputBox("Enter 1, 2 or 3")
-
Loop
-
MsgBox s
-
End Sub
-
Looking at the Java code in the debugger, after the user enters 1, the debugger says s = "1" So far, great, but if I inspect s != "1", it says "s != "1"" = true
What is this crazyness?!?
12 1960
Here's a secret:
When you say
myStr isn't actually a String. Java tries to trick you into thinking it is (and trust me, that is good for a beginner!), but it's not. myStr is secretly a pointer. Basically, myStr holds an address somewhere in memory. That address is where your actual String is. So when you try and compare myStr to something else with == or !=, you're trying to compare the memory address with a String. So "1" != "1", because the String you use as the left hand side is in a different memory location than the "1" on the right side.
The people at Sun realized this, so they gave you a friendly little method in String called .equals(). So replace
with
That's insane! But, very vital to know. It's interesting that -
String s = "1";
-
if (s == "1")
-
MessageBox.Show("C# is not weird!");
-
else
-
MessageBox.Show("C# is as weird as Java!");
-
string comparisons work in C# but not in Java. Thanks for your help, now I'll have to rewrite my homework like I wanted to in the first place!
That's insane! But, very vital to know. It's interesting that -
String s = "1";
-
if (s == "1")
-
MessageBox.Show("C# is not weird!");
-
else
-
MessageBox.Show("C# is as weird as Java!");
-
string comparisons work in C# but not in Java. Thanks for your help, now I'll have to rewrite my homework like I wanted to in the first place!
As a matter of fact the above might work. Literal Strings are stored in an 'intern'
pool and both "1" strings are stored only once in that pool; that makes your if-
clause succeed while you actually did it all wrong ;-)
kind regards,
Jos
ps. it's not 'insane'; it just doesn't work your prejudiced mind thought it should work.
... it's not 'insane'; it just doesn't work your prejudiced mind thought it should work.
not prejudiced :D I just expect the compiler to say :You don't want to do this, Sam!" At a minimum, it could have said "Illegal Indirection, like C++. ROFL --Sam
not prejudiced :D I just expect the compiler to say :You don't want to do this, Sam!" At a minimum, it could have said "Illegal Indirection, like C++. ROFL --Sam
The compiler can't say that because it's perfectly legal to compare two pointers,
or 'references' as Java calls them; it two pointers compare equal both pointers
point to the same object.
For strings you don't want to compare pointers, you want to compare the *value*
of two (or one?) String object and the String class implements an 'equals' method
for that: -
String s1= new String("foo");
-
String s2= new String("foo");
-
if (s1 == s2)
-
System.out.println("s1 and s2 point to same object");
-
else if (s1.equals(s2))
-
System.out.println("s1 and s2 have equal value");
-
else
-
System.out.println("s1 and s2 are different");
-
In C++ the overloaded '==' operator in the string class takes care of the 'equals'
functionality. Java doesn't have user defined overloaded operators.
kind regards,
Jos
I'm trying to keep up with you youngsters, so I'm taking a beginning Java course. As part of a homework assignment, we were to prompt the user for a number between 1 & 3. We also used while loops in the chapter, so I decided to put the prompt in a while loop to force the user to enter 1, 2 or 3. I was very surprised when it did not work, so I have written a 5-liner to show you the problem: -
import javax.swing.JOptionPane;
-
public class Weird {
-
public static void main(String[] args)
-
{
-
String s = "";
-
while (s != "1" && s!= "2" && s!= "3")
-
{
-
s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");
-
if (s == null) break;
-
}
-
if (s!= null) JOptionPane.showMessageDialog(null, s);
-
}
-
}
-
I fixed the problem by parsing the string and testing for integers 1, 2, or 3, but the above code should work! The same code in VB works great: -
Sub NotWeird()
-
Dim s As String
-
Do While (s <> "1" And s <> "2" And s <> "3")
-
s = InputBox("Enter 1, 2 or 3")
-
Loop
-
MsgBox s
-
End Sub
-
Looking at the Java code in the debugger, after the user enters 1, the debugger says s = "1" So far, great, but if I inspect s != "1", it says "s != "1"" = true
What is this crazyness?!?
Oh! It's crazy alright! Its' quite the headache...
I also find Java sometimes gives you an error on a line, highlights the line, as result of modifications to completely different lines in the code. And of course the moment I put things back where they belong, Java's happy again...
Oh! It's crazy alright! Its' quite the headache...
I also find Java sometimes gives you an error on a line, highlights the line, as result of modifications to completely different lines in the code. And of course the moment I put things back where they belong, Java's happy again...
Read my reply #6 for an explanation of this 'crazyness'.
About those errors on 'unrelated' lines: your modifications have ruined the structure
of your program then and the compiler can only detect it when the rest of the
structure of your program can't make sense anymore which may be (many) lines
from where you made your mistake.
kind regards,
Jos
The compiler can't say that because it's perfectly legal to compare two pointers,
or 'references' as Java calls them; it two pointers compare equal both pointers
point to the same object.
For strings you don't want to compare pointers, you want to compare the *value*
of two (or one?) String object and the String class implements an 'equals' method
for that: -
String s1= new String("foo");
-
String s2= new String("foo");
-
if (s1 == s2)
-
System.out.println("s1 and s2 point to same object");
-
else if (s1.equals(s2))
-
System.out.println("s1 and s2 have equal value");
-
else
-
System.out.println("s1 and s2 are different");
-
In C++ the overloaded '==' operator in the string class takes care of the 'equals'
functionality. Java doesn't have user defined overloaded operators.
kind regards,
Jos
Good heavens JosAH!
Java IS like JavaScript a lot of repect then. I cannot recall how I wrote this but in a previous reply specific to Sammy's scenario, I wondered whether: -
-
Var s1 ="Something"
-
Var s2 ="Something"
-
-
If (s1 == s2) Then
-
This is good stuff
-
Else
-
MsgBox ("Blaze blaze")
-
End If
-
...
-
-
Mind you, I am missing brackets there, but does above signify the similarities in both languages, and if this is a fact, can I look to JavaScrip to get a better understanding of Java, of course to some degree?
Good heavens JosAH!
Java IS like JavaScript a lot of repect then. I cannot recall how I wrote this but in a previous reply specific to Sammy's scenario, I wondered whether: -
-
Var s1 ="Something"
-
Var s2 ="Something"
-
-
If (s1 == s2) Then
-
This is good stuff
-
Else
-
MsgBox ("Blaze blaze")
-
End If
-
...
-
-
Mind you, I am missing brackets there, but does above signify the similarities in both languages, and if this is a fact, can I look to JavaScrip to get a better understanding of Java, of course to some degree?
But, as Jos pointed out above, this will print good stuff in Java also because s1 and s2 are both pointing to the same string.
Run the following and see if it helps! -
import javax.swing.JOptionPane;
-
public class Weird
-
{
-
public static void main(String[] args)
-
{
-
String s1 ="Something";
-
String s2 ="Something";
-
if (s1 == s2)
-
JOptionPane.showMessageDialog(null, "You just think this is good stuff");
-
else
-
JOptionPane.showMessageDialog(null, "Blaze blaze");
-
s2 ="Something else";
-
s2 = s2.substring(0, 9);
-
if (s1 == s2)
-
JOptionPane.showMessageDialog(null, "This is not expected");
-
else
-
JOptionPane.showMessageDialog(null, "Blaze blaze");
-
if (s1.equals(s2))
-
JOptionPane.showMessageDialog(null, "Jos is always right!");
-
else
-
JOptionPane.showMessageDialog(null, "Why bother with this message!");
-
-
}
-
}
-
But, as Jos pointed out above, this will print good stuff in Java also because s1 and s2 are both pointing to the same string.
Run the following and see if it helps! -
import javax.swing.JOptionPane;
-
public class Weird
-
{
-
public static void main(String[] args)
-
{
-
String s1 ="Something";
-
String s2 ="Something";
-
if (s1 == s2)
-
JOptionPane.showMessageDialog(null, "You just think this is good stuff");
-
else
-
JOptionPane.showMessageDialog(null, "Blaze blaze");
-
s2 ="Something else";
-
s2 = s2.substring(0, 9);
-
if (s1 == s2)
-
JOptionPane.showMessageDialog(null, "This is not expected");
-
else
-
JOptionPane.showMessageDialog(null, "Blaze blaze");
-
if (s1.equals(s2))
-
JOptionPane.showMessageDialog(null, "Jos is always right!");
-
else
-
JOptionPane.showMessageDialog(null, "Why bother with this message!");
-
-
}
-
}
-
I must have missed a step or two but I was stuck in what seemed to be an endless loop, should I get pop ups to enter stuff, should I have pressed ok for in pop up with "{ }" in the box?
I must have missed a step or two but I was stuck in what seemed to be an endless loop, should I get pop ups to enter stuff, should I have pressed ok for in pop up with "{ }" in the box?
Copy and paste into Weird.java & run it. You get three popups:
You just think this is good stuff
Blaze blaze
Jos is always right!
Hey you can write the code using the String Methods.
Here is the code which i modified.
while (!s.equalsIgnoreCase("1") && !s.equalsIgnoreCase("2") && !s.equalsIgnoreCase("3"))
{
s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");
if (s == null) break;
}
Sign in to post your reply or Sign up for a free account.
Similar topics
by: steve |
last post by:
I am quite frustrated with php’s include, as I have spent a ton of
time on it already... anyone can tell me why it was designed like this
(or something I don’t get)?
The path in include is...
|
by: David Furey |
last post by:
Hi
I have an XML documnet and a XSLT document as shown below
THe XSLT document brings back a filtered docmument that has the VendorName
that starts with a particular sub-string
This works as...
|
by: Eric Osman |
last post by:
Hi,
I'm looking for a javascript function that will convert input such as this:
<CLUB Code="
into this:
<CLUB Code="
|
by: NecroJoe |
last post by:
I am using PHP to generate a little javascript for one of my pages. In
short it allows a user to select a value from a list and pop it into a form
field on a seperate page. This works well unless...
|
by: Mateusz Loskot |
last post by:
Hi,
I'd like to ask how XML parsers should handle attributes which consists
of " entity as value. I know XML allows to use both: single and
double quotes as attribute value terminator. That's...
|
by: Arpi Jakab |
last post by:
I have a main project that depends on projects A and B. The main project's
additional include directories list is:
...\ProjectA\Dist\Include
...\ProjectB\Dist\Include
Each of the include...
|
by: martin |
last post by:
Hi,
I would be extremly grateful for some help on producing an xml fragemt.
The fragment that I wish to produce should look like this
<Addresses>
<Address>&qout;Somebody's Name"...
|
by: Ulysse |
last post by:
Hello,
I need to clean the string like this :
string =
"""
bonne mentalité mec!:) \n <br>bon pour
info moi je suis un serial posteur arceleur dictateur ^^*
\n ...
|
by: manchin2 |
last post by:
Hi,
Can anybody please provide the information about """ and its use, if possible please provide an example.
...
|
by: fran7 |
last post by:
Hi, from help in the javascript forum I found the error in some code but need help. This bit of code works perfectly, trouble is I am writing it to a javascript function so the height needs to be in...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |