Reputation: 101
Newbie question, but I have this code:
import java.util.*;
import java.io.*;
public class Welcome1
{
// main method begins execution of Java application
public static void main( String[] args )
{
String confirm = "y";
while(confirm=="y")
{
System.out.println( "Welcome to Java Programming!" );
System.out.println( "Print Again? (y/n)" );
Scanner input = new Scanner(System.in);
confirm = input.nextLine();
}
}
}
I just need to simply print the welcome message again when user input "y" when asked. But it's not working. Any ideas?
Upvotes: 3
Views: 6096
Reputation: 3489
Rewrite your code as follows (just an example):
import java.util.*;
import java.io.*;
public class Welcome1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String confirm = "y";
do {
System.out.println("Welcome to Java Programming!");
System.out.println("Print Again? (y/n)");
confirm = input.nextLine();
}
while (confirm.equalsIgnoreCase("y"));
}
}
Upvotes: 1
Reputation: 236004
In Java, the primitive types (int, long, boolean, etc.) are compared for equality using ==
, whereas the Object types (String, etc.) are compared for equality using the equals()
method. If you compare two Objects types using ==
, you're checking for identity, not equality - that is, you'd be verifying if the two objects share exactly the same reference in memory (and hence are the same object); and in general, what you need is just verifying if their values are the same, and for that you use equals()
.
As a good programming practice, it's better to compare Strings like this, flipping the order of the strings:
while ("y".equals(confirm)) {
In this way, you can be sure that the comparison will work, even if confirm
was null, avoiding a potential NullPointerException
.
Upvotes: 11
Reputation: 178451
you should use equals() instead of operator==.
the operator== checks if the two object are actually the same objects, while you want to check if they are equal.
code snap:
while(confirm.equals("y")) {
Upvotes: 5
Reputation: 5375
For string comparison, use .equals().
while(confirm.equals("y")){
Upvotes: 6