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

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, and java.util.Scanner because these aren't part of Java's core java.lang package—forgetting these will cause compilation errors.
  • List Initialization: We use ArrayList<>() because List is 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 with input = scanner.nextLine() to avoid redundant code.
  • Input Handling: Using scanner.nextLine() instead of nextInt() or next() ensures we capture full lines of input (including spaces). If you used nextInt(), the program would break if the user enters text instead of numbers.
  • Resource Cleanup: Closing the Scanner with scanner.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 use equals() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:09:50