Java如何将单行输入的多个int类型整数存储到Stack栈中
Java读取单行多个整数存入Stack的实现方案
现有代码的问题
- 调用
sc.nextInt()获取栈大小后,没有消费输入流中残留的换行符,会干扰后续输入的读取逻辑 - 循环逻辑冗余,for循环嵌套while循环的结构完全不必要
- 单次循环内连续调用两次
sc.nextInt(),每次循环会读两个数字入栈,会导致计数混乱、输入读取不符合预期
修正后的实现代码
方案1:基于Scanner的nextInt读取(兼容多行/单行输入)
import java.util.Scanner; import java.util.Stack; public class StackPractice { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements to place on the stack [1-10]:"); int stackSize = sc.nextInt(); // 清除nextInt遗留的换行符 sc.nextLine(); Stack<Integer> stack = new Stack<>(); System.out.println("Enter " + stackSize + " element(s):"); int count = 0; while (count < stackSize && sc.hasNextInt()) { stack.push(sc.nextInt()); count++; } System.out.println(stack); sc.close(); } }
方案2:整行读取后拆分(严格匹配单行输入需求)
如果要求必须从单行读取所有数字,不会读取用户换行后的内容,用这个方案更稳妥:
import java.util.Scanner; import java.util.Stack; public class StackPractice { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of elements to place on the stack [1-10]:"); int stackSize = sc.nextInt(); sc.nextLine(); Stack<Integer> stack = new Stack<>(); System.out.println("Enter " + stackSize + " element(s):"); // 直接读取完整一行输入 String inputLine = sc.nextLine().trim(); // 按任意空白字符分割成数字字符串 String[] numArr = inputLine.split("\\s+"); // 最多读取stackSize个数字入栈 int validCount = Math.min(numArr.length, stackSize); for (int i = 0; i < validCount; i++) { stack.push(Integer.parseInt(numArr[i])); } System.out.println(stack); sc.close(); } }
关键逻辑说明
- 调用
sc.nextLine()清理换行残留是关键操作,避免后续读取输入时出现空内容的问题 - 方案2的分割逻辑用
\\s+作为正则,可以兼容多个空格、制表符分隔的输入场景,容错性更高
内容的提问来源于stack exchange,提问作者Aurelius
相关产品推荐
相关产品推荐

