The "==" used for numerical values cannot be used for character string comparison. For character strings, use "** equals **".
The way of writing is a little different from when "=="
Variable a.equals(Variable b)
It seems to write. When you want to compare variables s1 and s2 with if, use it like this ↓
String s1 = "tomato", s2 = "tomato";
if (s1.equals(s2)){
System.out.println("match");
}
This ↑ is executed in if when s1 and s2 match If you want to "when the strings do not match" Enclose the conditional expression in front of and behind it with "()" and add "!" In front of it.
!(Variable a.equals(Variable b))
When the variables s1 and s2 are different, it is ↓ to execute in if
String s1 = "tomato", s2 = "potato";
if (!(s1.equals(s2))){
System.out.println("Mismatch");
}
Feeling accustomed to using "!" For denial.
The first time to put a value in a variable is in if, An error occurred when trying to use the value of that variable in subsequent processing.
You may not know what you mean Is the person who writes "Hmm?" I don't want you to worry about it.
The error occurred when ↓
Yomogi.java
public class Yomogi{
public static void main(String[] args){
int a, b;
a = 1;
if (a == 1){
b = 1; //With this
}
System.out.println("b = " + b); //This relationship is useless
}
}
Since the variable a contains 1, if becomes 100% true This is fine because the internal processing of if is executed. I thought, but it didn't work.
It seems that the problem was that the value was entered for the first time in the if. Therefore, enter an appropriate value in the variable b in advance.
Yomogi.java
public class Yomogi{
public static void main(String[] args){
int a, b;
a = 1;
b = 0; //Initialized with 0 in advance
if (a == 1){
b = 1;
}
System.out.println("b = " + b);
}
}
It worked well in this way. I see, java has that kind of specification.
I understood.
Even if the first assignment to a variable is in an if It was OK to use that variable only in if, so I decided to remember it.
Yomogi.java
public class Yomogi{
public static void main(String[] args){
int a, b;
a = 1;
if (a == 1){
b = 1;
System.out.println("b = " + b); //It's OK to use it only in if
}
}
}
When using if, you have to be careful when assigning to variables. It was an encounter with an error that I thought.
Recommended Posts