![](/img/trans.png)
[英]How do I return an int data from a static void method to main method?
[英]How do I store void method result into int array method
我正在嘗試將公共靜態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++;
}
試試這個:
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()之后打印成績的代碼。
您無需將grades[] static
聲明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();
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.