java - 将字符串存储在数组中并分割字符串

标签 java arrays

我在大学作业中遇到了 Java 问题。我们得到了一个文件,其中列出了一组信息(还有更多,这只是一个格式示例):

57363 乔伊·莱德 D D C P H H C D
72992 劳拉·诺德 H H H D D H H H
71258 艾琳 超过 C F C D C C C P

对于我来说,我无法弄清楚如何将其存储在数组中,并且我需要将其拆分,因为需要将字母转换为数字并求平均值,然后需要将其存储到第二个数组。

我对 Java 很陌生,所以很多需要在代码开始时导入的内容类型对我来说都是未知的,因此在任何回复中解释代码更改将不胜感激。到目前为止我的代码如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class StudentGPA_16997761 {

  public static void main(String[] args) throws FileNotFoundException {
    Scanner kb = new Scanner(System.in);

    //get file
    System.out.print("Please enter the name of the file containing student information: ");
    String gradeFile = kb.next();
    Scanner grades = new Scanner(new File(gradeFile));

    if (new File(gradeFile).exists()) {
      while (grades.hasNextLine()) {
        System.out.println(grades.nextLine());
      }
    }

    //student identification number, a first name, a surname, then 8 individual alphabetic characters that represent the
    //unit grades for the student. Hence, each line of data in the text file represents a student and the grades
    //they achieved in 8 units of study

    //need to make array to hold student information
    //need to make array that holds student id and GPA

  }
}

我知道它是有效的,因为 System.out.println 打印出我期望读取的行,但我不知道如何存储它们。我想我也许能够让分割工作,但这仍然需要首先数组/数组列表......

最佳答案

您可以使用分隔符将字符串拆分为数组。在您的示例中,如果所有名字和姓氏本身都不包含空格,您可以执行以下操作:

while (grades.hasNextLine()) {
    String line = grades.nextLine();
    String[] parts = line.split(" ");

    // get the basics
    String id = parts[0];
    String firstname = parts[1];
    String lastname = parts[2];

    // extract the grades
    int size = parts.length - 3;
    String[] gradelist = new String[size];
    System.arraycopy(parts, 3, gradelist, 0, size);

    // do something with the grades
}

关于java - 将字符串存储在数组中并分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26291534/

相关文章:

java - Selenium 可以截取 JUnit 测试失败的屏幕截图吗?

java - 在java中打印对角三角形

arrays - 从数据可能不存在的数组中获取元素

javascript - 多维数组

c++ - 如何使用 std::auto_ptr 声明动态数组?

ruby - 查找数组是否包含另一个数组的任何成员的最快方法?

java - JPA 数据存储库结果丢失其数据类型

java - 我在使用 Android Studio 导入 ViewPager 时遇到问题?

java - 使用泛型调用父类的 super()

java - 从 arrayList 中删除随机索引