简体   繁体   English

从单个用户输入填充和排序并行数组

[英]Filling and sorting parallel arrays from single user input

I have to accept a single user input of a string and an int ten times, separate them at the space into two parallel arrays. 我必须接受一个字符串和int的单个用户输入十次,将它们在空间中分成两个并行数组。 I then have to sort them, find average, etc. Everything I have found on parallel arrays has two different inputs for the string and int. 然后我必须对它们进行排序,找到平均值等。我在并行数组上找到的所有东西都有两个不同的输入字符串和int。 How can I separate the single input into the two arrays? 如何将单个输入分成两个数组?

public static void main(String args[]){

    //double[] gradeArray = new double[10];

//String[] nameArray = new String[10];


    String name = " "; //name substring
    String num = " "; //int substring
    String s = " "; //input String
    int grade = Integer.parseInt(num); //parsing the numerical string to an int

    int x = s.indexOf(' '); //index of " " space

    name = s.substring(0, x);
    num =s.substring(x + 1);

    Scanner input = new Scanner(System.in);
    int[] gradeArray = new int[10];

    String[] nameArray = new String[10];
    //looping to gather 10 user inputs
    for(int k = 0; k < 10; k++){
        System.out.println("Input Student name and grade: ");
        s = input.nextLine();

        //not sure how to sepearate String s into String name and String num
    }


    System.out.println("Highest Grade: " + Grades.highestGrade(gradeArray));
    System.out.println("Lowest Grade: " + Grades.lowestGrade(gradeArray));
    System.out.println("Class Average: " + Grades.classAverage(gradeArray));

    for(int i = 0; i < nameArray.length; i++){
        System.out.print(nameArray[i] + ", ");
        System.out.print(gradeArray[i]);
        System.out.println();

    //  System.out.print(sort());



    }

How can I separate the single input into the two arrays? 如何将单个输入分成两个数组?

First, we will use the already declared array of double to store the grades. 首先,我们将使用已经声明的double数组来存储成绩。

double[] gradeArray = new double[10];

Second, we will use the already declared array of String to store the names. 其次,我们将使用已经声明的String数组来存储名称。

String[] nameArray = new String[10];

Now, going on to the for loop, we can use the String#split() method to separate the name and the grade on the delimiter " " considering that there will be whitespace between the name and grade as you've mentioned. 现在,继续到for循环,我们可以使用String#split()方法来分隔分隔符" "上的namegrade ,考虑到你提到的namegrade之间会有空格。

for(int k = 0; k < 10; k++){
      System.out.println("Input Student name and grade: ");
      s = input.nextLine();
      String[] tempArray = s.split(" ");
      nameArray[k] = tempArray[0]; // store name to nameArray
      gradeArray[k] = Double.parseDouble(tempArray[1]);  // store grade to gradeArray
}

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

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