如何将 try 和 catch 合并到此数组列表中?

当我输入正整数以外的任何用户输入时,它会崩溃。我尝试在 Scanner 之前加入 try 和 catch,但是 for 循环的 max_players 和输入有一个红色下划线。


import java.util.*;


public class NameInput {


public static void main(String [] args) {




    ArrayList<String> players = new ArrayList<String>();


    System.out.println("How many players are going to play the game?");

    Scanner input = new Scanner(System.in);

    int max_players = input.nextInt();



    for(int i = 1; i <= max_players; i++) {

        System.out.println("\nPlayer " + i + ", please state your name: ");

        String name =input.next();

        players.add(name);

    }



    System.out.println(players.size());

    System.out.println(players);

  }


}

更新:为什么在我给用户命名后问题会重新出现?


import java.util.*;


public class NameInput {


public static void main(String [] args) {


ArrayList<String> players = new ArrayList<String>();

int max_players = 0;

Scanner input = new Scanner(System.in);

while (true) {

    System.out.println("How many players are going to play the game?");

    try {

        max_players = input.nextInt();

    } catch (InputMismatchException ee) {

        System.out.println("try again");

        input.nextLine ();

    }


    for(int i = 1; i <= max_players; i++) {

        System.out.println("\nPlayer " + i + ", please state your name: ");

        String name =input.next();

        players.add(name);

    }

 }

 }

 }


紫衣仙女
浏览 273回答 2
2回答

跃然一笑

这可以使用循环并捕获异常来完成int max_players = 0;Scanner input = new Scanner(System.in);while (true) {&nbsp; &nbsp; System.out.println("How many players are going to play the game?");&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; max_players = input.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; } catch (InputMismatchException ee) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("try again");&nbsp; &nbsp; &nbsp; &nbsp; input.nextLine ();&nbsp; &nbsp; }}

肥皂起泡泡

我尝试在 Scanner 之前加入 try 和 catch,但是 for 循环的 max_players 和输入有一个红色下划线。要解决此问题,您需要在 try-catch 块之外声明 max_players,并为其初始化默认值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java