Have some problem with " useDelimiter("[,\n]"); ". How can it correct?

Viewed 56
public void getConformFileDate(int year,int month,int date,int numOfday,int sr,int dr,int tr,int fr,int kr,int qr){
    
    String PIN = "" ; String check_in = ""; String NDates =""; String Rmonth = "" ; String Ryear = "" ;String people = "" ; String price = "" ;
    String single = "" ; String doub = ""; String triple =""; String fam = "" ; String king = "" ;String queen = "" ;
    
    try{
        x = new Scanner(new File(conf));
        x.useDelimiter("[,\n]");
        
        while(x.hasNext()){
            PIN       = x.next();
            check_in  = x.next();
            NDates    = x.next();
            Rmonth    = x.next();
            Ryear     = x.next();
            people    = x.next();
            price     = x.next();
            single    = x.next();
            doub      = x.next();
            triple    = x.next();
            fam       = x.next();
            king      = x.next();
            queen     = x.next();
            
            checkWithConformFile(Ryear,Rmonth,check_in,NDates,year,month,date,numOfday,single,doub,triple,fam,king,queen,sr,dr,tr,fr,kr,qr);
            //sumcroom = sumcroom + croom;
        }
        
        x.close();
        
    }
    catch(Exception e){
        System.out.println(e);
    }
}

after I convert some String values(like Rmonth,Ryear) to int Type and compare with my input values. If my input value are not in my text file it give true output. But my input values are in my text file it gives error.

error: "ava.lang.NumberFormatException: For input string: "3

my text File:

000001,2,7,9,2020,1,8000,1,0,0,0,0,0 000002,1,5,9,2020,2,12000,1,1,0,0,0,0 000003,9,12,10,2020,5,26000,1,0,0,1,0,0enter image description here

2 Answers

Your string can not be converted to a number. If your string is "3, then it is an invalid as an integer.

Problem:

In your code (shown below), you are calling next() 13 times for one call to x.hasNext() and therefore only the first call to next() i.e. PIN = x.next(); will be valid while others may be invalid because x.hasNext() is not checked for them.

while(x.hasNext()) {
      PIN       = x.next();
      check_in  = x.next();
      ...
      ...
      ...      
      checkWithConformFile(Ryear,Rmonth,check_in,NDates,year,month,date,numOfday,single,doub,triple,fam,king,queen,sr,dr,tr,fr,kr,qr);
  }

Solution:

You need to call x.hasNext() before each call to next() as shown below:

while(x.hasNext()) {
      PIN       = x.next();
      if(x.hasNext()){
            check_in  = x.next();
      }   
      if(x.hasNext()){
            NDates    = x.next();
      } 
      ...
      ...
      ...
      checkWithConformFile(Ryear,Rmonth,check_in,NDates,year,month,date,numOfday,single,doub,triple,fam,king,queen,sr,dr,tr,fr,kr,qr);
}
Related