Java使用Scanner扫描文件时else if分支无法正常执行问题求助
Java文件扫描分支逻辑问题修复方案
核心问题定位
你的代码跑不通主要是3个逻辑漏洞:
- 输入判断循环中
else if(no)分支的break被你注释了,导致用户输入no之后不会跳出循环,会先打印「无效输入」再重新要求输入姓氏,永远走不到后面的文件读取逻辑 - 无论用户选yes还是no,代码都强制执行了
discount = scan.nextDouble()要求输入折扣值,和你要的「选no就不用自定义折扣」的逻辑完全不符 Scanner的nextDouble()方法不会吃掉输入后的换行符,如果后面用nextLine()会直接读到空字符串,触发逻辑异常
修复思路
- 先在分支外层初始化折扣的默认值:选no的话直接用0折扣(不减免),选yes的话再接收用户输入修改折扣值,解决变量跨分支访问的问题
- 补全
else if(no)分支的break,保证合法输入后直接跳出输入循环 - 把折扣输入的逻辑移到yes分支内部,选no的时候跳过这一步
- 所有文件读取逻辑统一放在输入判断循环之后,不需要重复写在分支内,因为此时discount已经有确定的有效值
- 调用
nextDouble()后手动加一行scan.nextLine()吃掉残留的换行符,避免后续输入异常
修复后完整代码
import java.io.FileReader; import java.util.Scanner; import java.io.FileNotFoundException; public class Coursework2 { public static void main(String[] args) throws FileNotFoundException { Scanner reader = new Scanner(new FileReader("seats.txt")); Scanner scan = new Scanner (System.in); // 初始化默认折扣为0,即选no时无折扣 double discount = 0; boolean loopFlag = true; // 输入校验循环 while (loopFlag) { System.out.println("Please enter your Surname:"); String name = scan.nextLine(); System.out.println("Good morning, Manager " + name + " Would you like to apply a specific discount rate?"); String decision = scan.nextLine(); if (decision.equalsIgnoreCase("yes") || decision.equalsIgnoreCase("y")) { System.out.println("That's great, Mananger " + name + "."); System.out.println("How much discount would you like? (1-100)"); discount = scan.nextDouble(); // 吃掉nextDouble残留的换行符 scan.nextLine(); loopFlag = false; } else if (decision.equalsIgnoreCase("no") || decision.equalsIgnoreCase("n")) { System.out.println("Alright, " + name + " Here's all the seats without discounts:"); loopFlag = false; } else { System.out.println("Invalid Input, please try again. Restarting."); } } // 统一执行文件读取逻辑 while (reader.hasNext()) { String table = reader.next(); double price = reader.nextDouble(); int bookings = reader.nextInt(); double newdiscount = (((price/100.00*discount)*bookings)); double newincome = (price*bookings-(((price/100.00*discount)*bookings))); System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings ); System.out.printf("Discount: £%.2f, Income: £%.2f %n", newdiscount, newincome); String decision; do { System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings ); decision = scan.next(); } while (decision.equalsIgnoreCase("No")); System.out.printf("Seat type: %s, Price: £%.2f, Bookings: %d %n",table, price, bookings ); } reader.close(); scan.close(); } }
内容的提问来源于stack exchange,提问作者MrKalius
相关产品推荐
相关产品推荐

