水仙数判断问题:为什么代码会陷入死循环?

水仙数问题的常见困难

您提供的求水仙数的 java 代码中存在以下问题:

判断错误

代码中将判断语句 is 放置在 is() 方法中,导致在判断过程中重新调用 reader.nextint(),阻塞了程序。这样代码中永远不能继续执行。

修改后代码

您提供的代码,经修改后如下:

public class c1t3 {
    public static Integer shuru() {
        Scanner reader = new Scanner(System.in);
        System.out.println("123");
        int date = reader.nextInt();
        return date;

} public static void main(String[] args){ System.out.println("请输入一个三位数的整数"); String a= shuru().toString(); String[]b=a.split(""); int[] math=new int[b.length]; for(int i=0;i

修改内容

  • 将判断语句从 is() 方法中移出,直接写在 main() 方法中。
  • 将 shuru() 方法中的输入输出语句修改为 system.out.println("123");,避免在判断过程中阻塞程序。