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

Java中结合用户输入的while循环程序超时问题排查

问题:Java找最大整数程序超时无输出

编写的Java代码用于从用户输入中找出最大整数,在Zybooks平台测试时出现程序超时错误,输入2 77 17 4 -1时无任何输出,预期输出为77。代码逻辑为:当输入值大于0时,若该值大于当前最大值则更新最大值,直到输入负数时返回最大值,但无法定位问题所在。

用户代码

import java.util.Scanner;

public class Max {
   
   public int findMax() {
      Scanner scan = new Scanner(System.in);
      int userInput = scan.nextInt();
      int largestInt = 0;
      
      while (userInput > 0) {
         if (userInput > largestInt) {
            largestInt = userInput;
         }
      }
      return largestInt;
   }
   
   public static void main(String[] args) {
      Max test = new Max();
      System.out.println(test.findMax());
   }
}

测试详情

1: 输出对比
0 / 1
程序超时
输出不一致,高亮如下:
输入:2 77 17 4 -1
你的输出:(空)
预期输出:77

问题原因与修复

核心问题:死循环

代码中的while循环存在死循环:第一次读取输入2后,循环内部没有再次调用scan.nextInt()读取新的输入值,userInput始终保持为2,满足userInput > 0的条件,导致循环永远无法终止,最终触发超时错误。

修复后的代码

import java.util.Scanner;

public class Max {
   
   public int findMax() {
      Scanner scan = new Scanner(System.in);
      int userInput = scan.nextInt();
      // 初始值设为第一个输入值,避免所有输入为负数时返回0的错误
      int largestInt = userInput;
      
      while (userInput > 0) {
         if (userInput > largestInt) {
            largestInt = userInput;
         }
         // 每次循环读取新的输入,更新userInput
         userInput = scan.nextInt();
      }
      return largestInt;
   }
   
   public static void main(String[] args) {
      Max test = new Max();
      System.out.println(test.findMax());
   }
}

额外优化说明

  • 原代码中largestInt初始化为0,如果所有输入都是负数(比如直接输入-1),会错误返回0,修复后将初始值设为第一个输入值,更符合逻辑。
  • 循环内部必须添加userInput = scan.nextInt();,才能持续读取后续输入,直到遇到负数终止循环。

内容的提问来源于stack exchange,提问作者Beef

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:05:19