代码运行正常但ArrayList显示异常,是否遗漏空白字符?
问题分析与修复方案
核心问题:列表作用域错误
你把ArrayList<String> fruits = new ArrayList<>();声明在do-while循环内部,每次循环都会新建一个空列表,之前添加的水果根本没被保存下来,所以调用displayFruit时列表是空的,自然显示不出内容——这和你怀疑的空白字符没关系。
次要问题:nextInt后的换行残留
scan.nextInt()只会读取输入的数字,不会处理数字后面的换行符,导致第一次调用addFruit时,scan.nextLine()会直接读取到这个空换行,看起来像是跳过了输入步骤。
修复后的完整代码
import java.util.ArrayList; import java.util.Scanner; public class FruitManager { private static Scanner scan = new Scanner(System.in); public static void main(String[] args) { int choice = 0; String input = ""; // 将列表声明移到循环外,确保全程使用同一个列表 ArrayList<String> fruits = new ArrayList<>(); do { System.out.println("Choose an option: "); System.out.println("1. Add a fruit\n2. Delete a fruit"); System.out.println("3. Display fruits\n4. Exit"); choice = scan.nextInt(); // 吃掉nextInt留下的换行符,避免影响后续的nextLine scan.nextLine(); if (choice == 1) { input = addFruit(); fruits.add(input); } else if (choice == 2) { input = deleteFruit(); if (fruits.remove(input)) { System.out.println(input + " deleted from the list"); } else { System.out.println(input + " not found in the list"); } } else if (choice == 3) { displayFruit(fruits); } } while (choice != 4); System.out.println("Exiting the program. Goodbye!"); } public static void displayFruit(ArrayList<String> f) { if (f.isEmpty()) { System.out.println("The fruit list is empty."); return; } System.out.println("Here is the fruit list:"); for (int i = 0; i < f.size(); i++) { System.out.println("- " + f.get(i)); } } public static String addFruit() { System.out.print("Enter the name of the fruit: "); return scan.nextLine(); } public static String deleteFruit() { System.out.print("Enter the name of the fruit you want to delete: "); return scan.nextLine(); } }
额外优化说明
- 把Scanner声明为静态成员,避免重复创建
- 删除了addFruit/deleteFruit方法中多余的参数(不需要传入String再返回)
- 增加了删除时的存在性判断,避免删除不存在元素时的误导提示
- 优化了displayFruit的输出格式,空列表时给出明确提示
内容的提问来源于stack exchange,提问作者Orion Ponce
相关产品推荐
相关产品推荐

