这是我做了多远。
try { Scanner keyb = new Scanner(System.in); System.out.print("Enter the name of the input file-> "); String inFileName = keyb.next(); System.out.print("Enter the name of the output file-> "); String outFileName = keyb.next(); ArrayList<Time> roster = new ArrayList<Time>(); Scanner fileIn = new Scanner(new File(inFileName)); while (fileIn.hasNext()) { int hours = fileIn.nextInt(); int minutes = fileIn.nextInt(); String meridian = fileIn.next(); roster.add(new Time(hours,minutes,meridian)); } fileIn.close();基本上,我要做的是读取'appointment.txt'文件,该文件具有在11:30 am表单中的所有不同时间,以便按顺序对其进行排序并保存不同的文件名。 但由于小时和分钟之间的冒号(:),我的while循环无法正确读取时间并产生错误。 什么会使我的while循环工作?
Here is how far I've done.
try { Scanner keyb = new Scanner(System.in); System.out.print("Enter the name of the input file-> "); String inFileName = keyb.next(); System.out.print("Enter the name of the output file-> "); String outFileName = keyb.next(); ArrayList<Time> roster = new ArrayList<Time>(); Scanner fileIn = new Scanner(new File(inFileName)); while (fileIn.hasNext()) { int hours = fileIn.nextInt(); int minutes = fileIn.nextInt(); String meridian = fileIn.next(); roster.add(new Time(hours,minutes,meridian)); } fileIn.close();Basically, what I have to do is read 'appointment.txt' file that has all different time that is in 11:30 a.m. form to sort it in order and save it different file name. But because of colon(:) in between hour and minutes, my while loop can't read time correctly and make error. What would make my while loop working?
最满意答案
你的while -loop没有正常工作,因为你检查了fileIn.hasNext() ,但之后以不同的方式使用fileIn.nextInt()和fileIn.next() 。
你可能想要使用的是:
while (fileIn.hasNextLine()) { String line = fileIn.nextLine(); String[] bigParts = line.split(" "); String[] timeParts = bigParts[0].split(":"); roster.add(new Time( Integer.parseInt(timeParts[0]), Integer.parseInt(timeParts[1]), bigParts[1] )); }这将逐行读取文件,然后读取它已读取的行。 接下来将文本分为三部分,首先是 (空白),然后:冒号)。
更新:添加了Integer.parseInt()因为它最初也是如此。
Your while-loop is not correctly working because you check for fileIn.hasNext(), but afterwards use fileIn.nextInt() and fileIn.next() in different ways.
What you probably want to use is:
while (fileIn.hasNextLine()) { String line = fileIn.nextLine(); String[] bigParts = line.split(" "); String[] timeParts = bigParts[0].split(":"); roster.add(new Time( Integer.parseInt(timeParts[0]), Integer.parseInt(timeParts[1]), bigParts[1] )); }This reads the file line by line, then takes the line it has read. Following it splits the text up in three parts, first by (blank), then by : (colon).
UPDATE: Added Integer.parseInt() as it was originally done aswell.
更多推荐
发布评论