使用Scanner读取文件时的InputMismatchException

时间:2015-04-07 09:56:25

标签: java file java.util.scanner

我有file.txt:

7 10 5
ADD_FLIGHT SV221 Jeddah NewYork 30 7000
ADD_FLIGHT SV223 Jeddah London 30 4000
ADD_FLIGHT SV225 Jeddah Paris 30 3500
ADD_FLIGHT SV227 Jeddah Cairo 30 2000
ADD_PASS Mohammed Ali 33 M 0555788778
ADD_PASS Sara Maghrabi 30 F 0555111111
ADD_PASS Hani Ali 20 M 0555223344
ADD_PASS Mohammed Hafeth 33 M 0555889876
ADD_PASS Ahmad Sami 44 M 0555768768
ADD_FLIGHT SV332 Jeddah Riyadh 20 500
ADD_FLIGHT SV334 Jeddah Dammam 20 600
ADD_FLIGHT SV367 Jeddah Dubai 25 2000
ADD_PASS Salwa Ali 33 F 0555765672
ADD_PASS Faisal Amri 20 M 0555111111
ADD_PASS Mona Saleem 33 F 0555222112
ADD_PASS Ali Ali 33 M 0555743344
ADD_PASS Marwa Ahmad 33 F 0555545855

如果文件包含ADD_flight语句,我想从文件中读取信息并将信息放入对象数组中。此外,乘客从文件中读取信息乘客,如果文件包含,则将信息放入对象数组中ADD_PASD语句。

我不知道为什么我的代码中有错误说明:

File fin = new File("input.txt");
Scanner input = new Scanner(fin);

int c=0;
while (input.hasNextLine()){
     String s=input.nextLine();
     if (input.hasNext("ADD_FLIGHT")){
        inputFlight ( input,  flight ,fin );  
     }
     else if (input.hasNext("ADD_PASS")){
         inputPass( input,  passenger,fin );
          listFlightDetails( flight);
          listPassengerDetails(passenger);
     }}}//end the mine 


public static void inputFlight (Scanner input, Flight[] flight ,File fin ) throws IOException{
if (indexFlight<flight.length)  {
   flight[indexFlight]=new Flight();
   String flightCode=input.next();
    flight[indexFlight].setflightCod(flightCode);
        String ctyfrom=input.next();
    flight[indexFlight].setcityFrom(ctyfrom);
        String ctyto=input.next();
    flight[indexFlight].setCityTo(ctyto);
             int total=input.nextInt();
                  flight[indexFlight].setTotalSeats(total);
             double price=input.nextDouble();
                  flight[indexFlight].setprice(total);

indexFlight++;

}}
     public static void inputPass( Scanner input,  Passenger[] passenger ,File fin ) throws IOException{
if (indexPassenger<passenger.length)  {
   passenger[indexPassenger]=new Passenger();
   String name=input.next();
    passenger[indexPassenger].setname(name);
        int age=input.nextInt();
    passenger[indexPassenger].setage(age);
        char gender=input.nextLine().charAt(0);
    passenger[indexPassenger].setgender(gender);
            String d=input.next();
                  passenger[indexPassenger].setphone(d);

indexPassenger++;

}}
      public static void listFlightDetails(Flight[] flight) {
       for (int i = 0; i < indexFlight; i++) {
           if (flight[i].getflightCod() != null) {
               System.out.println("Enter " + i + " for Flight code :" + flight[i].getflightCod() + " , " + flight[i].getcityFrom() + " , " + flight[i].getCityTo());


}}}
public static void listPassengerDetails(Passenger[] passenger) {
       for (int i = 0; i < indexPassenger; i++) {
           if (passenger[i].getname() != null) {
               System.out.println("Enter " + i + " for  Passenger  :" + passenger[i].getname() + " , " + passenger[i].getgender());
           }

 }

}

如何更正代码? 这个错误来了

Exception in thread "main" java.util.InputMismatchException
   at java.util.Scanner.throwFor(Scanner.java:864)
   at java.util.Scanner.next(Scanner.java:1485)
   at java.util.Scanner.nextInt(Scanner.java:2117)
   at java.util.Scanner.nextInt(Scanner.java:2076)
   at FlightSystem.FlightSystem.inputFlight(FlightSystem.java:65)
   at FlightSystem.FlightSystem.main(FlightSystem.java:34)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
This error for pass

    Enter 0 for Flight code :SV223 , Jeddah , London
        Enter 0 for Flight code :SV223 , Jeddah , London
        Enter 0 for Flight code :SV223 , Jeddah , London
        Enter 1 for Flight code :SV227 , Jeddah , Cairo
        Enter 0 for Flight code :SV223 , Jeddah , London
        Enter 1 for Flight code :SV227 , Jeddah , Cairo
        Exception in thread "main" java.util.InputMismatchException
           at java.util.Scanner.throwFor(Scanner.java:864)
           at java.util.Scanner.next(Scanner.java:1485)
           at java.util.Scanner.nextInt(Scanner.java:2117)
           at java.util.Scanner.nextInt(Scanner.java:2076)
           at FlightSystem.FlightSystem.main(FlightSystem.java:39)
        Java Result: 1

3 个答案:

答案 0 :(得分:1)

为了简单起见,我们可以尝试以下方式:

while (input.hasNextLine()) {
    String s=input.nextLine();
    if(s.startsWith("ADD_FLIGHT")) {
        // Add to list of Flight DTO
    }
    else if(s.startsWith("ADD_PASS")) {
        // Add to list of passanger DTO
    }

    s = null;
}

我怀疑你的文本文件的第一行:

flightCode is coming as : ADD_FLIGHT
ctyfrom coming as : SV223
ctyto is coming as : Jeddah
and total is coming as "NewYork" which can't be converted into int.

你可以让Sysout验证它,或者也可以放一个调试点。

如果我的疑问是正确的,请在方法input.next();

中的String flightCode=input.next();行前面添加inputFlight()

答案 1 :(得分:0)

我试过用Regex这样做。见下面的代码:

List<String> filecontent = Files.readAllLines(Paths.get("abc.txt"), Charset.defaultCharset());

//regex for ADD_FLIGHT 
Pattern addFlight = Pattern.compile("ADD_FLIGHT (.+) (.+) (.+) (.+) (.+)");
//regex for ADD_PASS
Pattern addPass = Pattern.compile("ADD_PASS (.+) (.+) (.+) (.+) (.+)");

for(int i=0;i<filecontent.size();i++)
{
    Matcher m1 = addFlight.matcher(filecontent.get(i));
    while(m1.find())
    {
        //System.out.println(m1.group(0));
        //**Add each piece of data given in each line to your object array here**
        System.out.println(m1.group(1)); //SV221 
        System.out.println(m1.group(2)); //Jeddah 
        System.out.println(m1.group(3)); //NewYork 
        System.out.println(m1.group(4)); //30
        System.out.println(m1.group(5)); //7000
    }
    Matcher m2 = addPass.matcher(filecontent.get(i));
    while(m2.find())
    {
        //**Add each piece of data given in each line to your object array here**
        //System.out.println(m2.group(0)); //entire sentence
        System.out.println(m2.group(1)); //marwa
        System.out.println(m2.group(2)); //ahmad
        System.out.println(m2.group(3)); //33
        System.out.println(m2.group(4)); //F
        System.out.println(m2.group(5)); //0555545855
    }
}

将每条信息添加到一个对象数组中 - obj.firstname,obj.lastname等。在每一行上执行模式匹配。

PS:我对正则表达式并不好,但这很有用。

答案 2 :(得分:0)

您的代码

if (input.hasNext("ADD_FLIGHT")){
        inputFlight ( input,  flight ,fin );  
     }

指向此行的 ADD_FLIGHT SV221 Jeddah NewYork 30 7000

现在,在您的inputFlight(...)方法中,请仔细阅读以下代码的注释。我解释了为什么你有InputMisMatchException。

public static void inputFlight (Scanner input, Flight[] flight ,File fin ) throws IOException{
if (indexFlight<flight.length)  {
   flight[indexFlight]=new Flight();
   String flightCode=input.next();// This line takes ADD_FLIGHT instead of flight code SV221 
    flight[indexFlight].setflightCod(flightCode);
        String ctyfrom=input.next();//This line takes SV221 instead of Jeddah
    flight[indexFlight].setcityFrom(ctyfrom);
        String ctyto=input.next();//This line takes Jeddah instead of NewYork
    flight[indexFlight].setCityTo(ctyto);
             int total=input.nextInt();//This line takes NewYork instead of 30 thus InputMisMatchException occurs.
                  flight[indexFlight].setTotalSeats(total);
             double price=input.nextDouble();
                  flight[indexFlight].setprice(total);

indexFlight++;

}}

** int total = input.nextInt(); //此行使用NewYork而不是30,因此会发生InputMisMatchException。因为您尝试获取Int但输入从文件中获取字符串。< / p>

要避免异常,只需在阅读其他字符串之前添加input.next();即可。这是代码。

public static void inputFlight (Scanner input, Flight[] flight ,File fin ) throws IOException{
if (indexFlight<flight.length)  {
   String not_in_use=input.next()//**for moving input cursor to next (flight code)**
   flight[indexFlight]=new Flight();
   String flightCode=input.next();
    flight[indexFlight].setflightCod(flightCode);
        String ctyfrom=input.next();
    flight[indexFlight].setcityFrom(ctyfrom);
        String ctyto=input.next();
    flight[indexFlight].setCityTo(ctyto);
             int total=input.nextInt();
                  flight[indexFlight].setTotalSeats(total);
             double price=input.nextDouble();
                  flight[indexFlight].setprice(total);

indexFlight++;

}}

对于inputPass(...)方法,请指明您的文件 ADD_PASS Salwa Ali 33 F 0555765672 。请仔细阅读以下代码的评论。

public static void inputPass( Scanner input,  Passenger[] passenger ,File fin ) throws IOException{
    if (indexPassenger<passenger.length)  {
       passenger[indexPassenger]=new Passenger();
       String name=input.next();//Taking ADD_PASS instead of Salwa
        passenger[indexPassenger].setname(name);
            int age=input.nextInt();//Trying to take an integer but found string Salwa thus occurred InputMisMatchException. 
        passenger[indexPassenger].setage(age);
            char gender=input.nextLine().charAt(0);
        passenger[indexPassenger].setgender(gender);
                String d=input.next();
                      passenger[indexPassenger].setphone(d);

    indexPassenger++;

    }}

** int age = input.nextInt(); //尝试取整数但找到字符串Salwa因此发生了InputMisMatchException。

试试这个,

public static void inputPass( Scanner input,  Passenger[] passenger ,File fin ) throws IOException{
    if (indexPassenger<passenger.length)  {
       String not_in_use=input.next();//avoiding ADD_PASS
       passenger[indexPassenger]=new Passenger();
       String first_name=input.next();//taking first name
       String last_name=input.next();//taking last name
        passenger[indexPassenger].setname(first_name+" "+last_name);
            int age=input.nextInt();//taking age
        passenger[indexPassenger].setage(age);
            String gender=input.next();//taking gender
        passenger[indexPassenger].setgender(gender.toCharArray()[0]);
                String d=input.next();//taking phone number
                      passenger[indexPassenger].setphone(d);

    indexPassenger++;

    }}