有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否正确地将名称和级别存储到数组?

此存储名称和级别是否正确地分配到数组

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Enter name and grade and save in an array
        Scanner input = new Scanner(System.in);
        String [] name = new String [50];
        int [] grade = new int[50];       

        for (int i = 0; i < 50; i++){
            System.out.println("Enter students name: ");
            String studentName = input.nextLine();

            name[i] = studentName;

            System.out.println("Enter students grade = ");
            int studentGrade = input.nextInt();

            grade [i] = studentGrade;

        }
    }
}

共 (4) 个答案

  1. # 1 楼答案

    是的,您的数据已正确存储在阵列中。但是,有一些注释可以帮助您学习:

    • 如果您想知道变量包含什么类型的数据,请使用print()或它的相关项将其打印到屏幕上。这甚至适用于数组-你不是在写C
    • 使用两个数组来存储应该配对的对象会起作用,但通常是个坏主意。(如果你对其中一个排序而不是另一个呢?现在它们不匹配且不可用!)
    • 您计划如何使用这些数据?只要读入一对数组就是。。。毫无意义
  2. # 2 楼答案

    这里有一个自己测试这个程序的方法

    for (int i = 0; i < 50; i++){
      System.out.println("Enter students name: ");
      String studentName = input.nextLine();
    
      name[i] = studentName;
    
      System.out.println("Enter students grade = ");
      int studentGrade = input.nextInt();
    
      grade [i] = studentGrade;
    
      // Using print statements to check the values in your array...
      System.out.println("Name stored in name array is " + name[i]);
      System.out.println("Grade stored in grade array is " + grade[i]);
    }
    
  3. # 3 楼答案

    对。为什么运行此代码后不能打印数组以检查是否正常

    要打印数组,假设arr,只需执行以下操作:

    for(int i = 0; i < arr.length; i++) //go over all i's from 0 to the array length
        system.out.print(arr[i]); // and print the value of the array in the i'th place each time
    
  4. # 4 楼答案

    我想是的,但是你最好使用hashmap,因为你想存储一个名字和这个名字的等级
    数组中的这些值没有链接,例如,您不能对它们进行排序