如何在不询问数组大小的情况下,使用Scanner类向ArrayList动态输入值?
Great question! Since ArrayList is inherently dynamic—it grows automatically as you add elements—it’s perfect for this use case. Here’s how to implement it step by step, plus alternative approaches you can try:
Using Scanner + ArrayList (Core Solution)
The core idea is to read each line of input the user provides, split it by commas, convert each segment to your desired data type (integers in your example), and add them directly to the ArrayList. You can keep accepting input until the user chooses to stop (like entering "quit").
Here’s a complete Java example:
import java.util.ArrayList; import java.util.Scanner; public class DynamicArrayListInput { public static void main(String[] args) { ArrayList<Integer> numbersList = new ArrayList<>(); Scanner scanner = new Scanner(System.in); System.out.println("Enter comma-separated numbers (type 'quit' to stop):"); while (true) { String inputLine = scanner.nextLine().trim(); // Exit condition to stop input if (inputLine.equalsIgnoreCase("quit")) { break; } // Split input by commas (handles spaces after commas, e.g., "4, 5, 6") String[] numberStrings = inputLine.split(",\\s*"); try { for (String numStr : numberStrings) { int number = Integer.parseInt(numStr); numbersList.add(number); System.out.println("Added " + number + " to the list"); } } catch (NumberFormatException e) { System.out.println("Invalid input! Please enter only numbers separated by commas."); } } scanner.close(); System.out.println("\nFinal list contents: " + numbersList); } }
Key Details:
split(",\\s*")ensures inputs with or without spaces after commas work seamlessly.- The
try-catchblock prevents crashes if the user enters non-numeric values. - The loop runs indefinitely until the user types "quit"—you can adjust this exit condition to fit your needs.
Alternative Implementation Methods
1. Using StringTokenizer
If you want more control over tokenization, StringTokenizer (a classic Java utility) is a solid alternative to split():
import java.util.StringTokenizer; // Inside the loop, replace the split block with this: StringTokenizer tokenizer = new StringTokenizer(inputLine, ", "); while (tokenizer.hasMoreTokens()) { try { int number = Integer.parseInt(tokenizer.nextToken()); numbersList.add(number); } catch (NumberFormatException e) { System.out.println("Invalid number found, skipping this entry..."); } }
2. Using Java 8+ Streams
For a more concise approach, streams can simplify the conversion and addition process:
import java.util.stream.Stream; // Inside the loop: try { Stream.of(inputLine.split(",\\s*")) .map(Integer::parseInt) .forEach(numbersList::add); } catch (NumberFormatException e) { System.out.println("Invalid input! Please check your entry."); }
3. Using BufferedReader for Large Inputs
If you expect very large volumes of input, BufferedReader is more efficient than Scanner. Here’s a quick snippet:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // Replace Scanner with BufferedReader: BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inputLine; while ((inputLine = reader.readLine()) != null) { inputLine = inputLine.trim(); if (inputLine.equalsIgnoreCase("quit")) break; // Use the same parsing logic as before... } reader.close();
内容的提问来源于stack exchange,提问作者antara bhattacharya

