P
P
PosikGG2021-08-08 23:10:33
Java
PosikGG, 2021-08-08 23:10:33

Why does a Java program not work properly?

When you enter a letter instead of a number, the loop starts to spin everything.

import java.util.Scanner;

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

int a=0;

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

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

Boolean g=true;

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

  else {
    System.out.println("Некорректно введено число!");
    System.out.println();
  }	
}

}
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Developer, 2021-08-08
@PosikGG

If it is a letter, then from the very beginning the condition does not work and g remains true, which is why the loop spins endlessly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question