P
P
PosikGG2021-09-04 11:42:49
Java
PosikGG, 2021-09-04 11:42:49

Why is 0 not equal to 0?

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
    
Scanner sc = new Scanner(System.in);

String a = "";

System.out.println("Какие будут игроки?");
System.out.println();

System.out.println("1 - Добавить игрока");
System.out.println("0 - Закончить добавлять игроков");
System.out.println();

Boolean g=true;

while (g){
  a = sc.nextLine();
  if (a == "0"){
    System.out.println("Конец");
    g = false;
  }
  
  else if (a == "1"){
    System.out.println("Продолжаем");
    g = false;
  }
    
  else {
    System.out.println("Некорректно введено число!");	
  } 
}

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
oleg_ods, 2021-09-04
@PosikGG

Strings created at compile time end up in the StringPool, so they can be compared using '==' since they are essentially the same object. Strings created at Runtime do not get into the StringPool, so a new object is always created, therefore, as mentioned above, to get the correct result, you need to use Equals.

B
BorLaze, 2021-09-04
@BorLaze

Why, why... because someone missed the lecture on object comparison.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question