Java Scanner class reading strings

Posted by Max on Stack Overflow See other posts from Stack Overflow or by Max
Published on 2010-06-07T10:18:49Z Indexed on 2010/06/07 10:22 UTC
Read the original article Hit count: 189

Filed under:
|

I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains

  1 :     Fnjiei : ID   7868860 : Age  18
  2 : Oipuiieerb : ID    334134 : Age  39
  3 :   Enekaree : ID   6106274 : Age  31

I'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:)

    public void readFile(String fileName)throws IOException{
    Scanner input = null;
    input = new Scanner(new BufferedReader(new FileReader(fileName)));
    try {
        while (input.hasNextLine()){
            int howMany = 3;
            System.out.println(howMany);
            String userInput = input.nextLine();
            String name = "";
            String idS = "";    
            String ageS = "";
            int id;
            int age;
            int count=0; 
            for (int j = 0; j <= howMany; j++){
                for (int i=0; i < userInput.length(); i++){
                    if(count < 2){ // for name
                        if(Character.isLetter(userInput.charAt(i))){
                            name+=userInput.charAt(i); // store the name
                        }else if(userInput.charAt(i)==':'){
                            count++;
                            i++;
                        }
                    }else if(count == 2){ // for id
                        if(Character.isDigit(userInput.charAt(i))){
                            idS+=userInput.charAt(i); // store the id
                        }
                        else if(userInput.charAt(i)==':'){
                            count++;
                            i++;
                        }
                    }else if(count == 3){ // for age
                        if(Character.isDigit(userInput.charAt(i))){
                            ageS+=userInput.charAt(i); // store the age
                        }
                    }
                    id = Integer.parseInt(idS); // convert id to integer
                    age = Integer.parseInt(ageS); // convert age to integer
                    Fighters newFighters = new Fighters(id, name, age);
                    fighterList.add(newFighters);
                }
                userInput = input.nextLine();
            }
        }
    }finally{
        if (input != null){
            input.close();
        }
    }
}

My appology if my mere code begs to be changed.

© Stack Overflow or respective owner

Related posts about java

Related posts about scanner