简体   繁体   English

Java Scanner类读取字符串

[英]Java Scanner class reading strings

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 人员名单:长度3

1 : Fnjiei : ID 7868860 : Age 18 1:Fnjiei:ID 7868860:年龄18岁

2 : Oipuiieerb : ID 334134 : Age 39 2:Oipuiieerb:ID 334134:年龄39岁

3 : Enekaree : ID 6106274 : Age 31 3:Enekaree:ID 6106274:年龄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. 我正在尝试获取名称和ID号和年龄,但每次我尝试运行我的代码时它都会给我一个例外。 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. 来自java大师的任何建议?:)它能够读取一行.......但不超过一行文本。

    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. 我的应用程序,如果我的代码只是需要改变。

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 . 这是一个仅使用Scanner API的解决方案,重要的是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 API链接

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 人数:1姓名:Fnjiei ID:7868860年龄:18岁

Count: 2 Name: Oipuiieerb ID:334134 Age:39 数量:2姓名:Oipuiieerb ID:334134年龄:39

Count: 3 Name: Enekaree ID:6106274 Age:31 数量:3姓名:Enekaree ID:6106274年龄: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. 我基本上首先使用: as delimiter拆分该行,然后,我再次使用\\\\s+拆分,它基本上拆分一个字符串并返回一个包含由空格分隔的单词的数组。

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. 上面的代码段显示了基本的想法。另外请记住,这可能不是最佳解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM