• Post Reply Bookmark Topic Watch Topic
  • New Topic

Compare a String Variable to a String Array element  RSS feed

 
Jose Hatster
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! I'm kinda new to Java, and I have to make a game where words shuffle and the player needs to write it in the correct order. The problem is when I try to compare the answer introduced by the user to the element in the array, it always says it's incorrect... Is there any way to make it work??

System.out.println("COMENZAMOS");

Arrays.sort(jugar);
Arrays.sort(arregloj);

ArrayList<Integer> palabras = new ArrayList<Integer>();
for (int a=0; a<25; a++){

palabras.add(a);
Collections.shuffle(palabras);
}


for (int x=0; x<25; x++){

nump = palabras.get(x);

System.out.println(jugar[nump]);
respuesta = Lectura.readString();




if (respuesta == arregloj[nump])
{System.out.println("Correcto");}

else {System.out.println("Incorrecto");
System.out.println(arregloj[nump]);}

}
 
Vijitha Kumara
Bartender
Posts: 4002
42
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch
Jose Hatster wrote:

Assuming "respuesta" & "arregloj" are both type String, they (i.e: Strings) should be compared using the "equals()" method if you need to perform a comparison based on the content of them. If you use "==" instead it will try to compare the references whether they refer to the same object which are not. And please use code tags when posting code here next time.

 
Jose Hatster
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!! Wow, you saved my life! Yes, next time I post I'll be sure to use the code label.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!