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

Java中如何终止while循环?NoSuchElementException异常解决实例

Java Scanner输入报错问题修复说明

测试输入示例(Codezinger平台)

5  
=  
- 0.70  
- 2.40   
- 1.20   
+ 20.00   
3  
- 5.00   
- 0.50    
=    
0

报错原因

两个报错均为输入读取逻辑错误导致:

  • char character = sc.next().charAt(0); 报java.util.NoSuchElementException:do-while循环未更新N变量,输入读完后仍持续调用Scanner读取方法,无可用输入时抛出该异常
  • double pay=sc.nextDouble(); 报输入不匹配错误:for循环条件为i <= N,会多读取1次输入,把下一组用例的N值当成操作符读取,后续读取double时拿到的是操作符符号,类型不匹配报错

错误代码(主类)

import java.text.DecimalFormat;
import java.util.Scanner;

public class TestMyPrintCard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = 1;
        DecimalFormat df = new DecimalFormat("0.00");

        int N = sc.nextInt();
        sc.nextLine();

        do {
            System.out.println("Case #" + x + ":");
            MyPrintCard c1 = new MyPrintCard(); 

            for (int i = 0; i <= N; i++) {
                char character = sc.next().charAt(0); // char input =,+,- // 此处报错
                if (character == '=' ) {
                    System.out.println("RM" + df.format(c1.getBalance()));
                } else if (character == '+') {      
                    double topup = sc.nextDouble();
                    c1.topupCard(topup);
                } else if (character == '-') {
                    double pay = sc.nextDouble(); // 此处报错
                    c1.payService(pay);             
                }   
            } //end for

            x++;
        } while (N != 0);   
    }
}

配套MyPrintCard类代码

import java.text.DecimalFormat;

public class MyPrintCard {
    private double balance; //声明
    DecimalFormat df = new DecimalFormat("0.00");
    
    MyPrintCard() { //构造函数初始化
        balance = 10.00;        
    }
    
    //getter方法
    public double getBalance() {
        return balance;
    }
    
    public void topupCard(double amt) {
        balance += amt;
        System.out.println("RM" + df.format(balance));          
    }
    
    public void payService(double amt) {    
        if (balance > 5) {
            balance -= amt;
            System.out.println("RM" + df.format(balance));                  
        } else      
            System.out.println("invalid");
    }   
}

修正后的主类代码

import java.text.DecimalFormat;
import java.util.Scanner;

public class TestMyPrintCard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = 1;
        DecimalFormat df = new DecimalFormat("0.00");

        int N = sc.nextInt();
    
        while (N != 0) {
            System.out.println("Case #" + x + ":");
            MyPrintCard c1 = new MyPrintCard(); 
            for (int i = 0; i < N; i++) {
                char character = sc.next().charAt(0); // 接收=、+、-类字符输入
                if (character == '=' ) {
                    System.out.println("RM" + df.format(c1.getBalance()));
                } else if (character == '+') {      
                    double topup = sc.nextDouble();
                    c1.topupCard(topup);
                } else if (character == '-') {
                    double pay = sc.nextDouble();
                    c1.payService(pay);
                }   
            } //end for

            N = sc.nextInt();
            x++;
        }

        sc.close();
    }
}

核心修改点

  • 循环结构从do-while改为前置判断的while循环,避免N为0时仍执行逻辑
  • for循环条件从i <= N改为i < N,严格匹配每组用例的操作条数,不会多读输入
  • 去掉多余的sc.nextLine()调用,next()/nextDouble()会自动跳过空白符包括换行符
  • while循环末尾新增N = sc.nextInt()更新循环变量,读取下一组用例的N值,输入为0时正常终止循环
  • 新增sc.close()释放Scanner资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:04