掃描器讀取錯誤的數據,文本文件格式是:爲什麼我的程序不能正確識別姓?
111,Smith,Sam, 40,10.50 330,Jones,Jennifer,30,10.00
的程序是:
public class P3 {
public static void main(String[] args) {
String file=args[0];
File fileName = new File(file);
try {
Scanner sc = new Scanner(fileName).useDelimiter(", ");
while (sc.hasNextLine()) {
if (sc.hasNextInt()){ int id = sc.nextInt();}
String lastName = sc.next();
String firstName = sc.next();
if (sc.hasNextInt()){ int hours = sc.nextInt(); }
if (sc.hasNextFloat()){ float payRate=sc.nextFloat(); }
System.out.println(firstName);
}
sc.close();
} catch(FileNotFoundException e) {
System.out.println("Can't open file "
+ fileName + " ");
}
}
}
輸出是:
40,10.50
330,Jones,Jennifer,30,10.00
它應該是:
Sam
Jennifer
我該如何解決?
那麼史密斯和瓊斯呢? –
if is System.out.println(lastName); –
它應該打印史密斯和瓊斯 –