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

为何while(scan.hasNext())会跳过if(word.compareTo(small) < 0)语句?

问题分析与修复方案

问题根源

  1. Scanner光标残留:第一个循环用scan.nextFloat()读到-1就终止,但光标停在-1所在行的换行符上。第二个循环第一次执行scan.nextLine()时,会先读这个空行,导致第一个处理的word是空字符串。
  2. 初始值逻辑错误:small和larg初始化为空字符串"",而String的compareTo规则是非空字符串和空字符串比较必然返回正数。比如"banana".compareTo("")结果为正,所以word.compareTo(small) < 0永远不会触发,small一直是空值。

修复后的代码

public static void main(String[] args) throws IOException {
    PrintWriter createFile = new PrintWriter("temperature.txt");
    createFile.println("82.5\n30\n92\n78\n32\n98.8\n-1\nbanana\ngrapes\nanimal\nStop\n45");
    createFile.close();

    float c;
    String cel;
    String stop = "Stop";

    String small = "";
    String larg = "";
    File f = new File("temperature.txt");
    Scanner scan = new Scanner(f);
    FileWriter fw = new FileWriter("celsius.txt", true);
    PrintWriter pw = new PrintWriter(fw);
    
    // 处理温度转换的循环
    while (scan.hasNext()) {
        if (scan.hasNextFloat()) {
            float can = scan.nextFloat();
            if (can == (-1)) {
                break;
            } else {
                c = (can - 32) * 5 / 9;
                cel = String.format("%.2f", c);
                pw.println(cel);
            }
        } else {
            // 防止遇到非float内容时出错,直接跳过
            scan.next();
        }
    }
    // 吃掉-1后面的换行符,避免读取空行
    scan.nextLine();

    // 处理单词排序的循环
    while (scan.hasNext()) {
        String word = scan.nextLine().trim(); // 去掉首尾空格,避免空字符串干扰
        if (word.equalsIgnoreCase("stop")) {
            break;
        }
        // 第一次读取有效单词时初始化small和larg
        if (small.isEmpty()) {
            small = word;
            larg = word;
        } else {
            if (word.compareTo(small) < 0) {
                small = word;
            }
            if (word.compareTo(larg) > 0) {
                larg = word;
            }
        }
    }

    pw.println("First word will be: " + small);
    pw.println("Last word will be: " + larg);
    
    // 处理最后数字的循环
    while (scan.hasNextDouble()) {
        double num = scan.nextDouble();
        if (num >= 1 && num <= 50) {
            while (num <= 59) {
                pw.print(Math.pow(num, 2) + ", ");
                num++;
            }
            num++;
            pw.print(Math.pow(num, 2));
        }
    }
    pw.close();
    
    // 输出结果文件内容
    Scanner input = new Scanner(new File("celsius.txt"));
    while (input.hasNext()) {
        System.out.println(input.nextLine());
    }
}

关键修改说明

  • 在第一个循环结束后添加scan.nextLine(),清除残留的换行符,确保第二个循环读到的第一个内容是banana而非空行。
  • 第二个循环中先判断small是否为空,第一次读到有效单词时直接把small和larg都设为当前单词,之后再进行比较。
  • 给word添加trim(),避免可能的空格导致的空字符串问题。
  • 第三个循环改用scan.hasNextDouble(),避免非数字内容导致报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:48:09