【问题标题】:How do I store void method result into int array method如何将 void 方法结果存储到 int 数组方法中
【发布时间】:2014-05-29 11:02:24
【问题描述】:

我正在尝试将 public static void readGrades() 的结果存储到方法数组 int[]grades 中。但我没有这样做。我尝试了 ArrayList 和其他东西,但不幸的是。

public static int[]grades;
public static void main(String[] args) {
        readGrades();
}
public static void readGrades(){
    Scanner in=new Scanner(System.in);
    System.out.print("How many students there are : ");
    int numberOfStudents=in.nextInt();
    for(int i=1;i<=numberOfStudents;i++){
    System.out.print("Enter the grade of the students : ");
    int grades1=in.nextInt();
    grades1++;
}

【问题讨论】:

  • 你需要学习如何在java中使用数组。您还没有将数据存储在 Grades[] 数组中。这段代码>> int grades1=in.nextInt();等级1++; >> 只是创建一个变量并在下一次迭代中重新初始化它 }
  • 你不能因为void方法不返回任何东西。
  • @Christian 如果您仔细查看代码,您会发现grades 是静态字段,所以这个方法是一种静态设置器,这意味着它应该返回 void。
  • @Pshemo 如果其中一个不是静态的,那基本上是不可能的?
  • @Pshemo 是的,它的工作方式类似于 setter,但它是 doesn't return anything. Nor void

标签: java arrays


【解决方案1】:

试试这个:

public static int[] grades;
public static void main(String[] args) {
        readGrades();
}
public static void readGrades(){
    Scanner in=new Scanner(System.in);
    System.out.print("How many students there are : ");
    int numberOfStudents=in.nextInt();
    grades=new int[numberOfStudents];
    for(int i=0;i<numberOfStudents;i++){
        System.out.print("Enter the grade of the students : ");
        int grade=in.nextInt();
        grades[i]=grade;
     }
}

你必须知道这会将数据存储在 grades 数组中,你可以在调用方法 readGrades() 之前使用它,尝试编写在 readGrades() 之后打印成绩的代码。

【讨论】:

  • 干杯,它帮助了我:)
  • 这将使 index[0] 未使用。
  • @Sanjeev 是的,我知道。您可以通过从 numberOfStudents 中删除 +1 并在循环中设置 i=0 和 i 来更改它
【解决方案2】:

您不需要声明grades[] static,也可以使用locally declared int[] 来声明,如下所示:

public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.print("How many students there are : ");
        int numberOfStudents=in.nextInt();
        int[] grades = new int[numberOfStudents];
        readGrades(grades, in);
        // here you can write code to play with grades array
}
public static void readGrades(int[] grades, Scanner in){
    for(int i=0;i<numberOfStudents;i++){
         System.out.print("Enter the grade of the students : ");
         grades[i]=in.nextInt();
    }
}

希望这会有所帮助。

【讨论】:

  • 这也很有帮助,干杯。但是我被要求像我展示的那样做。
猜你喜欢
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2017-12-17
相关资源
最近更新 更多