Java Scanner 类读取字符串

发布于 2024-09-04 11:39:24 字数 2403 浏览 5 评论 0 原文

我创建了一个扫描器类来读取文本文件并获取我想要的值。假设我有一个文本文件包含。

人员列表:长度3

1:Fnjiei:ID 7868860:年龄 18

2:Oipuiieerb:ID 334134:年龄 39

3:Enekaree:ID 6106274:年龄 31

我试图获取姓名、身份证号码和年龄,但每次我尝试运行我的代码,它给了我一个例外。这是我的代码。 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();
        }
    }
}

如果我的代码需要更改,我深表歉意。

已编辑它给了我一个数字格式异常! 我不知道这些值之间会有多少空白。

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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温柔嚣张 2024-09-11 11:39:25
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();
     }

上面的代码片段显示了基本思想。另请记住,这可能不是最佳解决方案。

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.

北座城市 2024-09-11 11:39:24

这是一种仅使用 Scanner API 的解决方案,其中重要的一个是 findInLine。它可以处理输入格式中的细微语法变化,但它的可读性非常好,不需要花哨的正则表达式或魔术数组索引。

    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);
    }

这将打印:

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

API 链接

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

梦里°也失望 2024-09-11 11:39:24

这似乎更短:

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();
            }
        }
    }

对于您向我们提供的输入,它会打印以下内容:

数量:1 姓名:Fnjiei ID:7868860 年龄:18

人数:2 姓名:Oipuiieerb ID:334134 年龄:39

数量:3 姓名:Enekaree ID:6106274 年龄:31

有关 split 方法的更多信息,请参阅 此处。我基本上首先使用 : 作为分隔符来分割该行,然后,我使用 \\s+ 再次分割该行,它基本上分割一个字符串并返回一个包含单词的数组由空格分隔。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文