我有一个文本文件,其中包含不同的时间,如下所示:
12:30 am 4:50 PM 6:15 A.M. 8:09 p.m.
等等
我想解析这个小时,分钟和子午线的文件.我尝试使用正则表达式"[: ]"
,但我一直IOException("Invalid meridian.")
被我甩了...... 我做了一个例外.
这是一些代码:
try { System.out.println("Enter the name of the input file: "); inputFile = in.nextLine(); System.out.println("Enter the name of the output file: "); outputFile = in.nextLine(); Scanner fileIn = new Scanner(new File(inputFile)); while (fileIn.hasNext()) { String[] vals = fileIn.nextLine().split("[: ]"); int hours = Integer.parseInt(vals[0]); int minutes = Integer.parseInt(vals[1]); String meridian = vals[2]; times.add(new Time(hours, minutes, meridian)); } fileIn.close(); System.out.println("Unsorted times: "); for (Time i: times) System.out.println(i); } catch(IOException e) { e.printStackTrace(); System.exit(90); }
这里是IOException最初构想的地方(在Time构造函数中):
if (!(meridian.toUpperCase().equals("AM") && meridian.toUpperCase().equals("A.M.") && meridian.toUpperCase().equals("PM") && meridian.toUpperCase().equals("P.M."))) throw new IOException("Invalid meridian.");
可能是什么问题呢?(つ◕_◕)つ
你的逻辑不正确.它永远不会同时等于所有4个字符串.你想要||
括号内的逻辑或:
if (!(meridian.toUpperCase().equals("AM") || meridian.toUpperCase().equals("A.M.") || meridian.toUpperCase().equals("PM") || meridian.toUpperCase().equals("P.M.")))
这样,如果它等于一个预期的情况,那么不会抛出异常.