+ 3

Why don't work this simple command with Scanner? return no output

import java.util.Scanner; class coseDaFare { public static void main(String[ ] args) { Scanner myVar = new Scanner(System.in); String[] lunedi = { "film", "pattini", "musica"}; String[] martedi = { "scuola", "merenda","gelato"}; if (myVar.nextLine() == "lunedi"){ System.out.println(lunedi[1]); } } }

12th Feb 2017, 1:17 PM
Alessio Farroni
Alessio Farroni - avatar
7 Answers
+ 9
Dan, dan, dan...!! Hatsy Rei debugs a Java code! So the problem here is that, strings in Java cannot be compared using ==. Consider the following fix: import java.util.Scanner; class coseDaFare { public static void main(String[ ] args) { Scanner myVar = new Scanner(System.in); String[] lunedi = { "film", "pattini", "musica"}; String[] martedi = { "scuola", "merenda","gelato"}; String x = myVar.nextLine(); if (x.equals("lunedi")) { System.out.println(lunedi[1]); } } } You need to use .equals() to compare the strings. Also, as Nelson pointed out, you need to store your input into a variable first before comparing the strings. =^=
12th Feb 2017, 1:32 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Check the if statement first... What are you trying to do there? I'm not sure that you can compare the user input with a whole string array just like that. So, the output statement will never run.
12th Feb 2017, 1:28 PM
Nelson Urbina
Nelson Urbina - avatar
+ 3
thank's Hatsy, now i have understand the problem , thank's Nelson. Hasty have response
12th Feb 2017, 1:43 PM
Alessio Farroni
Alessio Farroni - avatar
+ 1
Please...:(
12th Feb 2017, 1:13 PM
Alessio Farroni
Alessio Farroni - avatar
+ 1
thank's Hatsy, now i have understand the problem , thank's Nelson. Hasty have response
12th Feb 2017, 1:42 PM
Alessio Farroni
Alessio Farroni - avatar
+ 1
thank's Ace for altenative path
12th Feb 2017, 5:54 PM
Alessio Farroni
Alessio Farroni - avatar