![](/img/trans.png)
[英]Why does parsing '23:00 PM' with SimpleDateFormat(“hh:mm aa”) return 11 a.m.?
[英]TimeSorter: Read time(form of hh:mm a.m.) file using Scanner
這是我所做的一切。
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格式的所有不同時間,以對其進行排序並保存為其他文件名。 但是由於在小時和分鍾之間存在冒號(:),我的while循環無法正確讀取時間並產生錯誤。 什么會使我的while循環正常工作?
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()
因為它最初也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.