开发者

Java Scanner class reading strings

开发者 https://www.devze.com 2023-01-02 07:50 出处:网络
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.

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.

List of people: length 3

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?:) It was able to read one single line....... but no more than a single line of text.

    public void readFile(String fileName)throws IOException{
    Scanner开发者_如何学Python 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.

Edited It gives me a number format exception!!! I dont know how many empty space would be there between these values.


Here's a solution that uses only Scanner API, the important one being findInLine. It can handle minor syntactic variations in the input format, and yet it's very readable, requiring no need for fancy regex or magic array indices.

    String text =
        "List  of @#%^$ people : length  3  !@%# \n" + 
        "1 :   Fnjiei   : ID 7868860 ::: Age 18\n" +
        "   2: Oipuiieerb : ID 334134 : Age 39 (old, lol!) \r\n" + 
        " 3 : Enekaree : ID 6106274 => Age 31\n";
    Scanner sc = new Scanner(text);

    sc.findInLine("length");
    final int N = sc.nextInt();

    for (int i = 0; i < N; i++) {
        sc.nextLine();
        sc.findInLine(":");
        String name = sc.next();
        sc.findInLine("ID");
        long id = sc.nextLong();
        sc.findInLine("Age");
        int age = sc.nextInt();
        System.out.printf("[%s] %s (%s)%n", id, name, age);
    }

This prints:

[7868860] Fnjiei (18)
[334134] Oipuiieerb (39)
[6106274] Enekaree (31)

API links

  • Scanner.findInLine(Pattern pattern)
    • Attempts to find the next occurrence of the specified pattern ignoring delimiters.
    • Use this Pattern.compile overload if performance is an issue


This seems to be shorter:

public void readFile(String fileName)throws IOException
    {
        Scanner input = null;
        input = new Scanner(new BufferedReader(new FileReader(fileName)));
        String userInput;
        try
        {
            while (input.hasNextLine())
            {
                userInput = input.nextLine().trim();
                if (userInput.length() > 0)
                {
                    String[] userInfo = userInput.split(":");
                    int count = Integer.parseInt(userInfo[0].trim());
                    String name = userInfo[1].trim();
                    int id = Integer.parseInt(userInfo[2].trim().split("\\s+")[1].trim());
                    int age = Integer.parseInt(userInfo[3].trim().split("\\s+")[1].trim());

                    System.out.println("Count: " + count + " Name: " + name + " ID:" + id + " Age:" + age);
                }
                Fighters newFighters = new Fighters(id, name, age);
                fighterList.add(newFighters);
            }


        }
        finally
        {
            if (input != null)
            {
                input.close();
            }
        }
    }

For the input you have us, it prints this:

Count: 1 Name: Fnjiei ID:7868860 Age:18

Count: 2 Name: Oipuiieerb ID:334134 Age:39

Count: 3 Name: Enekaree ID:6106274 Age:31

More information about the split method can be found here. I basically first split the line by using the : as delimiter, then, I split again using the \\s+, which basically splits a string and return an array containing the words that were separated by white spaces.


Scanner input = null;
input = new Scanner(new BufferedReader(new FileReader("filename")));

    try{
       while(input.hasNextLine()){
         String userInput = input.nextLine();
         String[] data = userInput.split(":");
         System.out.println("Name: "+data[1]+" ID:"+data[2].split("\\s+")[2]+
            "  Age:"+data[3].split("\\s+")[2]);

            }
        }finally{

            if(input != null) 
             input.close();
     }

Above snippet shows the basic idea.Also please keep in mind that this might not be the optimal solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消