r/javahelp • u/Wetnoodels • Mar 12 '20
While loop keeps looping even when condition is met
This is the code:
package FirstPackage;
import java.util.Scanner;
public class TheLastHero {
public static void main(String[] args) {
System.out.println("Welcome you are the last Hero please save the land from the monsters that are plaguing it by killing the boss in the dungeon Type \\"Start\\" to Begin");
Scanner Inp = new Scanner([System.in](https://System.in));
String Val = (Inp.nextLine()).toUpperCase();
while (Val != "START"){
System.out.println("Please enter \\"Start\\" to begin");
Val=(Inp.nextLine()).toUpperCase();
System.out.println(Val);
}}
}
And this is the result:
Welcome you are the last Hero please save the land from the monsters that are plaguing it by killing the boss in the dungeon Type "Start" to Begin
dsd
Please enter "Start" to begin
Start
START
Please enter "Start" to begin
As you can see even when the condition is met it keeps looping
Edit : Sorry apparently it s a stupid question i just needed to use !.equals instead of !=
2
u/Sergi2204 Mar 12 '20
The AutoModerator just gave you the solution!! Comparing objects (like Strings) with == or != doesn't work, you need to use .equals() method.
1
u/Wetnoodels Mar 12 '20
Yes if you saw the edit i put i did say that it was a stupid mistake of mine but ty
-1
u/Wolfhammer69 Nooblet Brewer Mar 12 '20
I'm in a good mood today but as /u/Sergi2204 said, the moderator pretty much said it all. You are not comparing Strings properly and your logic is incorrect for what you want to do.
Try this:-
6
u/AutoModerator Mar 12 '20
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals(). For case insensitive comparison, use.equalsIgnoreCase().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take. Still, it would be nice courtesy, even though our rules state to not delete posts, to delete your post if my assumption was correct.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.