How should i do to make gender = "F" even if it is in if statement. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!

25th Oct 2017, 4:15 PM
YuHai
YuHai - avatar
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
25th Oct 2017, 4:21 PM
Chrizzhigh
Chrizzhigh - avatar
+ 4
Try it like this (as @Chrizzhigh explained): if(gender.equals("F")) { //your code here... } Hth, cmiiw
25th Oct 2017, 6:47 PM
Ipang
+ 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.
26th Oct 2017, 5:44 AM
Ipang
+ 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
26th Oct 2017, 3:22 AM
Chrizzhigh
Chrizzhigh - avatar
+ 1
@Ipang , thank you so much.
26th Oct 2017, 1:21 AM
YuHai
YuHai - avatar
0
so....how should i correct my code. i just have no idea.thanks.
25th Oct 2017, 5:20 PM
YuHai
YuHai - avatar
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.
26th Oct 2017, 9:16 AM
YuHai
YuHai - avatar