I was caught in the skill check problem "character string comparison" (* problem of code disclosure OK) published in Paiza, so I summarized it.
The content of the problem is "Compare the two entered strings"
I knew that there was a string comparison function, but the video I referred to didn't show how to do it, so I had a preconceived notion that I wouldn't use it.
Incorrect code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line1 = sc.nextLine();
String line2 = sc.nextLine();
if( line1 == line2 ){
System.out.println("OK");
}
else{
System.out.println("NG");
}
}
}
Even if the output result is the same character string, "NG"
Enter the code below to confirm
Try debugging
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line1 = sc.nextLine();
String line2 = sc.nextLine();
//Check if statement
String line1 = "moji";
String line2 = "moji";
//Confirmation of input
System.out.println(line1);
System.out.println(line2);
if( line1 == line2 ){
System.out.println("OK");
}
else{
System.out.println("NG");
}
}
}
Output result;
moji
moji
ok
There is no problem with getting the if statement and character input. After all, I think that the character string comparison is bad (condition of if statement) and confirm it, and arrive at the following site. [Introduction to Java] How to compare strings (String) ("==" and "equals") Regarding the equality comparison of String type in Java
Correct code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line1 = sc.nextLine();
String line2 = sc.nextLine();
if( line1.equals(line2)){
System.out.println("OK");
}
else{
System.out.println("NG");
}
}
}
Recommended Posts