Rendy
Rendy

Reputation: 101

String comparison in java, again

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

Answers (4)

Nico
Nico

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

Óscar López
Óscar López

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

amit
amit

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

Christian Neverdal
Christian Neverdal

Reputation: 5375

For string comparison, use .equals().

while(confirm.equals("y")){

Upvotes: 6

Related Questions