You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Scanner输入字符串数组并随机选取,及用Switch实现抽名字?

How to Input a String Array with Scanner & Pick a Random Name (Switch Implementation)

Hey there! Let's tackle your problem step by step—you want to create a name array via user input (either one line or multiple entries) and build a "hat picker" with a switch statement. First, let's fix the quick issues in your existing code, then walk through two common input methods plus the random selection logic.

Quick Fixes for Your Existing Code

  • You can't assign sc.next() directly to a String[]—sc.next() returns a single string, not an array.
  • You're redefining final String[] names inside the case, which will cause a compilation error (duplicate variable). Declare the array outside the switch to keep scope across cases instead.

Method 1: Input Multiple Names in One Line (Space-Separated)

This lets users type all names at once, separated by spaces. We'll read the entire line, split it into parts, and clean up any empty entries from extra spaces.

Switch Case Implementation

import java.util.Arrays;
import java.util.Scanner;

// Declare array outside switch to access across cases
String[] names = new String[0];
Scanner sc = new Scanner(System.in);

switch (yourChoiceVariable) {
    case 'a':
        System.out.println("\nPlease enter the names of the participants (separated by spaces):");
        // Consume leftover newline from menu input (critical to avoid empty reads!)
        sc.nextLine();
        // Read the full input line
        String inputLine = sc.nextLine();
        // Split on any number of whitespace characters (spaces, tabs, etc.)
        names = inputLine.split("\\s+");
        // Filter out empty strings from leading/trailing spaces
        names = Arrays.stream(names).filter(name -> !name.isEmpty()).toArray(String[]::new);
        System.out.println("Added " + names.length + " names successfully!");
        break;
    // Add other cases here...
}

Method 2: Input Names One by One (Enter "done" to Finish)

If you prefer users to enter one name per line, we'll use a List to collect names until they type a stop word (like "done"), then convert the list to an array.

Switch Case Implementation

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

String[] names = new String[0];
Scanner sc = new Scanner(System.in);

switch (yourChoiceVariable) {
    case 'a':
        System.out.println("\nPlease enter the names of the participants (type 'done' when finished):");
        List<String> nameList = new ArrayList<>();
        String input;
        // Loop until user enters "done"
        while (true) {
            input = sc.nextLine();
            if ("done".equalsIgnoreCase(input)) {
                break;
            }
            // Skip empty input lines
            if (!input.isEmpty()) {
                nameList.add(input);
            }
        }
        // Convert list to array
        names = nameList.toArray(new String[0]);
        System.out.println("Added " + names.length + " names successfully!");
        break;
    // Add other cases here...
}

Add Random Name Selection Logic

Once you have the names array, add a case to pick a random name using the Random class. Always check if the array isn't empty first to avoid errors!

case 'b':
    if (names.length == 0) {
        System.out.println("\nNo names have been entered yet!");
        break;
    }
    // Generate a random index within the array's bounds
    Random random = new Random();
    int randomIndex = random.nextInt(names.length);
    System.out.println("\nRandomly selected name: " + names[randomIndex]);
    break;

Full Working Example

Here's a complete program that ties it all together with a menu system:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class HatNamePicker {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] names = new String[0];
        char choice;

        while (true) {
            System.out.println("\n=== Hat Name Picker ===");
            System.out.println("a) Enter participant names");
            System.out.println("b) Pick a random name");
            System.out.println("q) Quit");
            System.out.print("Choose an option: ");
            choice = sc.next().charAt(0);

            switch (choice) {
                case 'a':
                    System.out.println("\nOption 1: Type all names separated by spaces");
                    System.out.println("Option 2: Enter one name per line (type 'done' to finish)");
                    System.out.print("Choose input method (1/2): ");
                    int inputMethod = sc.nextInt();
                    sc.nextLine(); // Consume leftover newline

                    if (inputMethod == 1) {
                        System.out.println("\nEnter names (space-separated):");
                        String inputLine = sc.nextLine();
                        names = inputLine.split("\\s+");
                        names = Arrays.stream(names).filter(n -> !n.isEmpty()).toArray(String[]::new);
                    } else if (inputMethod == 2) {
                        System.out.println("\nEnter names (type 'done' when done):");
                        List<String> nameList = new ArrayList<>();
                        String input;
                        while (true) {
                            input = sc.nextLine();
                            if ("done".equalsIgnoreCase(input)) break;
                            if (!input.isEmpty()) nameList.add(input);
                        }
                        names = nameList.toArray(new String[0]);
                    } else {
                        System.out.println("Invalid input method!");
                        break;
                    }
                    System.out.println("Added " + names.length + " names.");
                    break;

                case 'b':
                    if (names.length == 0) {
                        System.out.println("\nNo names to pick from!");
                        break;
                    }
                    Random random = new Random();
                    System.out.println("\nRandomly selected: " + names[random.nextInt(names.length)]);
                    break;

                case 'q':
                    System.out.println("\nGoodbye!");
                    sc.close();
                    return;

                default:
                    System.out.println("\nInvalid option—please try again.");
            }
        }
    }
}

Key Notes

  • Consume Newlines: After using sc.next() to read menu choices, always call sc.nextLine() to clear the leftover newline character—otherwise, the next sc.nextLine() will read an empty string.
  • Filter Empty Entries: This prevents empty strings from cluttering your array if users accidentally hit extra spaces or enter blank lines.
  • Array Non-Empty Check: Always verify the array has elements before trying to pick a random name to avoid ArrayIndexOutOfBoundsException.

内容的提问来源于stack exchange,提问作者J bl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:49:10