Java TimeSorter:使用扫描仪读取时间(格式为hh:mm a.m.)文件
这就是我所做的Java TimeSorter:使用扫描仪读取时间(格式为hh:mm a.m.)文件,java,time,colon,Java,Time,Colon,这就是我所做的 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 out
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();
试试看
{
扫描仪keyb=新扫描仪(System.in);
System.out.print(“输入输入文件的名称->”;
字符串inFileName=keyb.next();
System.out.print(“输入输出文件的名称->”;
字符串outFileName=keyb.next();
ArrayList花名册=新建ArrayList();
Scanner fileIn=new Scanner(新文件(inFileName));
while(fileIn.hasNext())
{
int hours=fileIn.nextInt();
int minutes=fileIn.nextInt();
字符串meridian=fileIn.next();
花名册。添加(新时间(小时、分钟、子午线));
}
fileIn.close();
基本上,我要做的是读取'appointment.txt'文件,该文件具有上午11:30的所有不同时间,以便按顺序排序并保存不同的文件名。但是由于冒号(:)在小时和分钟之间,我的while循环无法正确读取时间并出错。什么会使我的while循环工作?你的
while
-循环工作不正常,因为你检查了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()
,与最初一样。帮助我们:请给出输入示例并打印您获得的此错误的详细信息(stacktrace)