My lecturer gave us a simple assignment of reading from a text file(as a database) and computing allowances based on age and gender. When I read a line from the txt file, I read each word and stored in a string. But it is a bit confusing for me, what if i have a line in my file say-
bucky roberts M 23
now i have firstname = bucky;
lastname = roberts;
sex = M
and age = 23
.
Now, based on the above fields if i make a computation, it works fine.
But what if my lecturer says rewrite the same line to be -
bucky M 23
firstname = bucky
lastname = M
sex = 23
and age = null
Thats how the program reads the line from the file. Now, if i make a if-else statement based on age, i will get an error of java.util.MismatchException
. How do i resolve this issue and at the same time find a way such that even if my lecturer tempers with the database, the program runs fine. Here is a part of the code below:-
AdultMale.java class:-
public class AdultMale extends Male {
public void getAllowance() {
readfromFile();
while(in.hasNext())
{
firstname = in.next();
lastname = in.next();
gender = in.next();
age = in.nextInt();
if(gender.equals("M") || gender.equals("Male") || gender.equals("male") ||gender.equals("m"))
{
AdultAllowance();
}
}
in.close();
}
}
Male.java class:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Male extends Members{
Scanner in;
public void getAllowance() {
}
public void readfromFile()
{
try {
in = new Scanner(new File("Dbase.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void AdultAllowance()
{
if(age>=18)
{
total = 500;
total = total + 1000;
System.out.println(firstname + "\t" +lastname+"\t"+ age + "\t"+ gender+"\t"+total);
total = 0;
}
}
public void MinorAllowance()
{
if(age <18)
{
total = 500;
total = total + 200;
System.out.println(firstname + "\t"+lastname+"\t" + age + "\t"+ gender+"\t"+total);
total = 0;
}
}
}
Members class:-
public abstract class Members {
String firstname,lastname,gender;
int age;
double total ;
}
My txt database is called - "Dbase.txt" which contains the following:-
Sam Bell M 17
Becky roberts F 23
Bucky taylor M 21
Sammy lyson F 16
Terry gibson F 23
答案 0 :(得分:1)
阅读整行,然后使用它。所以,这样的东西应该工作(未经测试的代码,用textpad编写)。这将处理所有情况。
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] arr = line.split("\\s+");
for(String str : arr) {
if(str.equalsIgnoreCase("M") || str.equalsIgnoreCase("Male")); // check for gender for each line in file.
gender = "M";
}
else if(str.matches("\\d+")) { // check for age.
age = Integer.parseInt(str);
}
else if(firstName!=null || !firstName.isEmpty()) // for string that is not age or gender.
{
firstName = str;
}
else{
lastname = str;
}
}
}