Use the string comparison in Java again
Novice problem, 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 print the welcome message again when the user enters "Y" But it doesn't work Any ideas?
Solution
In Java, use = = to compare the equality of basic types (int, long, Boolean, etc.), and use the equals () method to compare the equality of object types (string, etc.) If you use = = to compare two object types, you need to check the identity, not equality - that is, you will verify that the two objects share exactly the same reference (and therefore the same object) in memory; In general, all you need is to verify that their values are the same. For this purpose, you use equals()
As a good programming practice, it is better to compare such strings and flip the order of strings:
while ("y".equals(confirm)) {
In this way, you can ensure that the comparison will work and avoid the potential NullPointerException even if it is confirmed to be null