Java程序字符串越界问题求助:如何实现重复运行?
解决贷款计算程序重复运行时的字符串越界问题
问题根源
使用nextDouble()、nextInt()这类Scanner方法读取数值后,输入末尾的换行符会被留在输入缓冲区里。后续调用nextLine()时,它会直接读取这个换行符,得到空字符串,此时调用charAt(0)必然抛出StringIndexOutOfBoundsException。
修复方案
结合程序重复运行的需求,用do-while循环实现逻辑最合理,以下两种修复方式任选其一:
方案1:清除残留换行符
在读取完贷款年限后,额外调用一次keyboard.nextLine()吃掉缓冲区里的换行符,再读取用户的Y/N选择:
import java.util.Scanner; import java.io.*; public class LoanReport { public static void main(String[] args) throws IOException { double loanBalance; double interestRate; int loanYears; String answer; char again; Scanner keyboard = new Scanner(System.in); do { System.out.print("Enter the loan amount: "); loanBalance = keyboard.nextDouble(); System.out.print("Enter the annual interest rate: "); interestRate = keyboard.nextDouble(); System.out.print("Enter the years of the loan: "); loanYears = keyboard.nextInt(); // 吃掉nextInt()留下的换行符,避免后续nextLine()读空 keyboard.nextLine(); Amortization am = new Amortization(loanBalance, interestRate, loanYears); am.saveReport("LoanAmortization.txt"); System.out.println("Report saved to the file LoanAmortization.txt."); System.out.print("Would you like to run another report? Enter Y for yes or N for no: "); answer = keyboard.nextLine(); // 处理用户直接回车的情况,默认不继续 again = answer.isEmpty() ? 'n' : answer.charAt(0); } while (again == 'Y' || again == 'y'); System.exit(0); } }
方案2:用next()读取选择
next()方法会自动跳过所有空白字符(包括换行),直接读取有效输入,从根源避免空字符串问题:
import java.util.Scanner; import java.io.*; public class LoanReport { public static void main(String[] args) throws IOException { double loanBalance; double interestRate; int loanYears; String answer; char again; Scanner keyboard = new Scanner(System.in); do { System.out.print("Enter the loan amount: "); loanBalance = keyboard.nextDouble(); System.out.print("Enter the annual interest rate: "); interestRate = keyboard.nextDouble(); System.out.print("Enter the years of the loan: "); loanYears = keyboard.nextInt(); Amortization am = new Amortization(loanBalance, interestRate, loanYears); am.saveReport("LoanAmortization.txt"); System.out.println("Report saved to the file LoanAmortization.txt."); System.out.print("Would you like to run another report? Enter Y for yes or N for no: "); answer = keyboard.next(); again = answer.charAt(0); } while (again == 'Y' || again == 'y'); System.exit(0); } }
补充说明
- 方案1里加了空字符串判断,防止用户直接按回车时再次触发越界异常,更健壮。
- do-while循环天生适合这种“至少执行一次,再根据条件重复”的场景,比你注释里的while循环更贴合需求。
内容的提问来源于stack exchange,提问作者ihateranch808
相关产品推荐
相关产品推荐

