当扫描仪名称不正确时跳过一行 class
Skipping a line when it doesn't have the correct name with the scanner class
public void populateFromFile(String filename)
{
try
{
Scanner sc = new Scanner(new File(filename));
//variables
String firstName;
String lastName;
String emailAddress;
String startYear;
String startMonth;
String clubName;
Member tmp;
//skip first line
sc.nextLine();
sc.useDelimiter(";");
sc.skip(
while (sc.hasNext())
{
sc.next();
firstName = sc.next();
lastName = sc.next();
emailAddress = sc.next();
startYear = sc.next();
int year = Integer.parseInt(startYear);
startMonth = sc.next();
int month = Integer.parseInt(startMonth);
clubName = sc.next();
tmp = new Member(firstName,lastName,emailAddress,month,year);
if(clubName == name)
{
addMember(tmp);
}
}
sc.close();
}
catch(Exception e){
System.out.println(e);
};
}
I'm trying to find a way how I only can add the 'Members' who are from the correct club. But when I am trying to put an if statement in the while loop the program runs forever. Do you have any other idea how I could do this?
这是我根据您的问题创建的示例。这应该可以解决您的问题。
String str = "x;a1;b1;c1;d1\ny;a2;b2;c2;d2\nx;a3;b3;c3;d4";
Scanner s = new Scanner(str);
while(s.hasNextLine()){
Scanner s2 = new Scanner(s.nextLine());
s2.useDelimiter(";");
String h = s2.next();
String a = s2.next();
String b = s2.next();
String c = s2.next();
String d = s2.next();
if (h.equals("x")){
System.out.printf("%s|%s|%s|%s\n", a,b,c,d);
}
}
输出为:
a1|b1|c1|d1
a3|b3|c3|d3
public void populateFromFile(String filename)
{
try
{
Scanner sc = new Scanner(new File(filename));
//variables
String firstName;
String lastName;
String emailAddress;
String startYear;
String startMonth;
String clubName;
Member tmp;
//skip first line
sc.nextLine();
sc.useDelimiter(";");
sc.skip(
while (sc.hasNext())
{
sc.next();
firstName = sc.next();
lastName = sc.next();
emailAddress = sc.next();
startYear = sc.next();
int year = Integer.parseInt(startYear);
startMonth = sc.next();
int month = Integer.parseInt(startMonth);
clubName = sc.next();
tmp = new Member(firstName,lastName,emailAddress,month,year);
if(clubName == name)
{
addMember(tmp);
}
}
sc.close();
}
catch(Exception e){
System.out.println(e);
};
}
I'm trying to find a way how I only can add the 'Members' who are from the correct club. But when I am trying to put an if statement in the while loop the program runs forever. Do you have any other idea how I could do this?
这是我根据您的问题创建的示例。这应该可以解决您的问题。
String str = "x;a1;b1;c1;d1\ny;a2;b2;c2;d2\nx;a3;b3;c3;d4";
Scanner s = new Scanner(str);
while(s.hasNextLine()){
Scanner s2 = new Scanner(s.nextLine());
s2.useDelimiter(";");
String h = s2.next();
String a = s2.next();
String b = s2.next();
String c = s2.next();
String d = s2.next();
if (h.equals("x")){
System.out.printf("%s|%s|%s|%s\n", a,b,c,d);
}
}
输出为:
a1|b1|c1|d1
a3|b3|c3|d3