Java while循环结合用户输入问题求助:实现输入存储与终止逻辑
Java Program: Collect User Input with List & While Loop
Hey there! I totally get the struggle of self-teaching Java—let's break down how to build this program correctly, and I'll highlight common mistakes you might run into along the way.
Step-by-Step Explanation & Working Code
First, here's a complete, working version of the program you're trying to build:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class UserInputCollector { public static void main(String[] args) { // Initialize a List to store user input (ArrayList is a common implementation of List) List<String> userInputs = new ArrayList<>(); // Create a Scanner object to read input from the console Scanner scanner = new Scanner(System.in); String input; System.out.println("Enter content to add to the list (type '0' to stop):"); // While loop runs as long as the input is NOT "0" while (!(input = scanner.nextLine()).equals("0")) { // Add the input to the list only if it's not empty (optional, but avoids blank entries) if (!input.trim().isEmpty()) { userInputs.add(input); } else { System.out.println("Blank input won't be added. Please enter something or type '0' to stop."); } } // Close the scanner to free up resources scanner.close(); // Print all contents of the list System.out.println("\nHere's all the content you entered:"); if (userInputs.isEmpty()) { System.out.println("The list is empty."); } else { for (String content : userInputs) { System.out.println("- " + content); } } } }
Key Details to Note (For Self-Learners)
- Import Statements: We need
java.util.ArrayList,java.util.List, andjava.util.Scannerbecause these aren't part of Java's corejava.langpackage—forgetting these will cause compilation errors. - List Initialization: We use
ArrayList<>()becauseListis just an interface (a blueprint), and we need a concrete implementation to store data. - Loop Condition: The loop checks if the input is not equal to "0" using
!input.equals("0"). We read the input directly in the loop condition withinput = scanner.nextLine()to avoid redundant code. - Input Handling: Using
scanner.nextLine()instead ofnextInt()ornext()ensures we capture full lines of input (including spaces). If you usednextInt(), the program would break if the user enters text instead of numbers. - Resource Cleanup: Closing the
Scannerwithscanner.close()is a good practice to release system resources. - Edge Cases: The code checks for blank input and handles empty lists, which makes the program more robust.
Common Mistakes to Avoid
- Dead Loops: If you forget to update the input variable inside the loop, it will run forever. Always make sure your loop condition depends on a value that changes each iteration.
- String Comparison: Never use
==to compare strings in Java—this checks if two objects are the same in memory, not if their content matches. Always useequals()for string content comparison. - Unclosed Scanner: While not a critical error, leaving scanners open can lead to resource leaks, so it's good to get into the habit of closing them.
内容的提问来源于stack exchange,提问作者J. Adam
相关产品推荐
相关产品推荐

