本文介绍了java将方法拆分为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下数据:

3.3 John
3.9 Jim
3.5 Kathy
3.2 Steve
2.4 Stacy
2.8 Faith

代码:

File StudentGrade = new File("data.txt");
    Scanner reader = new Scanner(StudentGrade);
    int size = reader.nextInt();
    //debug: System.out.println(size);

    String[] gradeArr = new String[size];// array created for grades
    //debug: System.out.println(gradeArr);
    String[] nameArr = new String[size];//array created for name
    String[] temp = new String[100];// array created for temporary array
    int index = 0;//index indicator

    while (reader.hasNextLine()) {
        String s = reader.nextLine();
        //System.out.println(s);
        temp = s.split("\\s+");
        gradeArr[index] = temp[0];
        nameArr[index] = temp[1];
        System.out.println("grades= "+ gradeArr[index]+ " name = "+ nameArr);
        index++;
    }

必须将其拆分为2个数组,一个用于数字,另一个用于数字是为了名字。
我可以将数字转换为 temp [] ,但是我不知道如何将名称转换为另一个数组。请教我。

It has to be split to 2 arrays, one is for the numbers, another is for names.I can get the numbers to temp[], but I don't know how to convert names to another array. Please teach me.

推荐答案

调用 split( \\s +),结果数组如下所示:

When you call split("\\s+"), the result array would look like this:

gradeArr[0] = 3.3;
gradeArr[1] = John;

因此,如果您调用 gradeArr [1]

您需要在<$ c之后调用 reader.nextLine(); $ c> reader.nextInt(); 。您需要在 int 之后读取回车符,这样您才能在.text文件的下一行。

You need to call reader.nextLine(); after your reader.nextInt();. You need to read the enter character after the int so you would be on the next line of the .text file.

以下代码有效:

File StudentGrade = new File("E:/workspace/Test/src/main/java/data.txt");
        Scanner reader = new Scanner(StudentGrade);
        int size = reader.nextInt();
        // debug: System.out.println(size);
        reader.nextLine();
    String[] gradeArr = new String[size];// array created for grades
    // debug: System.out.println(gradeArr);
    String[] nameArr = new String[size];// array created for name
    String[] temp = new String[100];// array created for temporary array
    int index = 0;// index indicator

    while (reader.hasNextLine()) {
        String s = reader.nextLine();
        // System.out.println(s);
        temp = s.split("\\s+");
        gradeArr[index] = temp[0];
        nameArr[index] = temp[1];
        System.out.println("grades= " + gradeArr[index] + " name = " + nameArr[index]);
        index++;
    }

这是结果:

grades= 3.3 name = John
grades= 3.9 name = Jim
grades= 3.5 name = Kathy
grades= 3.2 name = Steve
grades= 2.4 name = Stacy
grades= 2.8 name = Faith

数据.text:

6
3.3 John
3.9 Jim
3.5 Kathy
3.2 Steve
2.4 Stacy
2.8 Faith

这篇关于java将方法拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:26