+ 2
How should i do to make gender = "F" even if it is in if statement.
import java.util.Scanner; public class Test{ public static void main(String[ ] args) { Scanner info = new Scanner(System.in); String gender = "O"; gender = info.nextLine(); if (gender == "F"){ System.out.println(gender); }else{ System.out.println("absjhfJFIGF"); } } } originally , when i input F to change the value of gender , I suppose the if statement is true,but im wrong . is there any limit of if statement or it is just my misunderstanding of something? thanks!
7 Answers
+ 5
in java the comparison for objects is done by the function equals...
"F".equals(gender)
the == comparison only checks references and not the value
+ 4
Try it like this (as @Chrizzhigh explained):
if(gender.equals("F"))
{
//your code here...
}
Hth, cmiiw
+ 4
@Chrizzhigh, right, but then again, we should all practice to "never trust the user", by first checking on all user's input prior to processing them.
(Edit)
In your opinion, in Code Playground input dialog, what will happen if the user submit a blank input, or they submit partial entries for multiple input. Do we get null, empty string, or zero for the blanks?.there's no restriction on how user type the input, they can enter string where number expected, and vice versa.
+ 2
@Ipang you should do it like "F".equala(gender) because this way gender can be Null , if you do it like gender.equals(...) and gender is Null java throws an exception
+ 1
@Ipang , thank you so much.
0
so....how should i correct my code.
i just have no idea.thanks.
0
@Ipang you're right. what you say is so important that it became our homework. In fact, I had stuck there for several days.At that time ,I was almost crazy and want to smash my computer.