import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class gTextFile {
static LinkedList<gText> list = new LinkedList<gText>();
public static void main(String[] args) throws FileNotFoundException {
Scanner scnOne = new Scanner(System.in);
String eCode;
System.out.print("Employee Code: ");
eCode = scnOne.nextLine();
readFile();
gEmpName("eCode");
}
public static void readFile() throws FileNotFoundException {
File nFile = new File("C:\\JAVAP\\GetTextFile\\employee.txt");
Scanner scnTwo = new Scanner(nFile);
String oTemp;
while(scnTwo.hasNext()) {
oTemp = scnTwo.next();
String EmCode[] = oTemp.split(" ");
String Name[] = EmCode[1].split(",");
String idCode = EmCode[0];
String lastname = Name[0];
String firstname = Name[1];
//System.out.println("FName " + firstname);
//System.out.println("LName " + lastname);
gText gT = new gText(firstname, lastname, idCode);
list.add(gT);
}
scnTwo.close();
}
public static void gEmpName(String EmpCode) {
Iterator<gText> itr = list.iterator();
while(itr.hasNext()) {
gText gT = itr.next();
if(gT.id.equals(EmpCode)){
System.out.println("Employee Name: " + gT.Fname + " " + gT.Lname);
}
}
}
}
public class gText {
String Fname;
String Lname;
String id;
gText(String First, String Last, String ID) {
this.Fname = First;
this.Lname = Last;
this.id = ID;
}
public String gFName() {
return Fname;
}
public String gLName() {
return Lname;
}
public String gId() {
return id;
}
}
我的代码有什么问题?当我运行程序时,特定的代码没有显示出来。总是说有问题。当我输入员工代码时,这总是会在控制台中显示出来。员工代码:A11-0001线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:gTextFile.readFile(gTextFile.java:28)处为1,gTextFile.main(gTextFile.java:17)处为1
在方法中使用oTemp = scnTwo.nextLine();
而不是。使用时,您所获得的只是第一个空格之前的内容,在您的情况下,仅是员工代码,因此用于获取完整行。有关和之间的区别的更多说明,请参见下面的链接oTemp = scnTwo.next();
readFile()
next()
nextLine()
next()
nextLine()
Scanner类的next()和nextLine()方法之间有什么区别?
另外,您可能希望使用gEmpName(eCode);
而不是gEmpName("eCode");
以下是代码:
public class gTextFile {
static LinkedList<gText> list = new LinkedList<gText>();
public static void main(String[] args) throws FileNotFoundException {
Scanner scnOne = new Scanner(System.in);
String eCode;
System.out.print("Employee Code: ");
eCode = scnOne.nextLine();
readFile();
gEmpName(eCode);
}
public static void readFile() throws FileNotFoundException {
File nFile = new File("/home/path/abc.txt");
Scanner scnTwo = new Scanner(nFile);
String oTemp;
while(scnTwo.hasNext()) {
oTemp = scnTwo.nextLine();
String EmCode[] = oTemp.split(" ");
String Name[] = EmCode[1].split(",");
String idCode = EmCode[0];
String lastname = Name[0];
String firstname = Name[1];
gText gT = new gText(firstname, lastname, idCode);
list.add(gT);
}
scnTwo.close();
}
public static void gEmpName(String EmpCode) {
Iterator<gText> itr = list.iterator();
while(itr.hasNext()) {
gText gT = itr.next();
if(gT.id.equals(EmpCode)){
System.out.println("Employee Name: " + gT.Fname + " " + gT.Lname);
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句