2015-05-14 20 views
1

如何將數組傳遞給方法以便我可以在另一個方法中使用switch語句中的方法?java中的方法和數組

package assignment8exam; 

import java.util.Scanner; 

/** 
* 
* @author Anders 
*/ 
public class Course { 

    Scanner sc = new Scanner(System.in); 

    public void MainMenu() { 

     System.out.println("Enter data about a studen, start by entering how many"); 

     int numbers = sc.nextInt();// amount of student 

     for (int i = 0; i < numbers; i++) { 

      System.out.println("Enter name of student"); 
      Scanner name = new Scanner(System.in); 

      String names = name.nextLine(); 
      String studentNames[] = new String[numbers]; 
     } 

     for (int j = 0; j < numbers; j++) { 

      System.out.println("Enter grade of student"); 
      Scanner gradeSc = new Scanner(System.in); 

      int grade = gradeSc.nextInt(); 
      int studentGrade[] = new int[numbers]; 
     } 

     System.out.println("What do you want"); 
     System.out.println("Exit application 1"); 
     System.out.println("Print out all names of the students 2"); 
     System.out.println("Print out all the grades of the students 3"); 
     System.out.println("Print out pairs consisting of 「name­grade 4"); 

     Scanner choice = new Scanner(System.in); 
     int order = choice.nextInt(); 

     switch (order) { 

      case 1: 
       System.exit(1); 
      case 2: 
       PrintOutNames(numbers); /* so i can use this one with studentName array*/ 

     } 
    } 

    public void PrintOutNames(int numbers) { 

     for (int i = 0; i < numbers; i++) { 

      System.out.println(studentNames[i].length); // How do i activate the array studentNames?? 

     } 

    } 
} 
+3

只要改變你的方法簽名'PrintOutNames(INT數字,字符串[] studentNames)'然後通過在陣列中,當你調用該方法。 –

+1

您的'studentNames'數組只存在於for循環中。與'studentGrade'數組一樣。改變這將有所幫助。你的代碼也有一個[切換開關](http://stackoverflow.com/questions/188461/switch-statement-fallthrough-should-it-be-allowed)問題。 – Obicere

回答

0

傳遞一個數組爲參數的方法是通過具有方法簽名採取的陣列,當調用方法只是通過正確類型的陣列中進行,如public static int find_sum(int [ ] value),然後,例如find_sum(intArray);

0

你可以做到這一點作爲一個例子:

private void PassArray(){ 
    String[] myArray = new String[4]; // Some array 
    PrintA(myArray); 
} 

private void PrintA(String[] a){ 
    //do whatever with array here 
} 

請注意,如果你只是傳遞一個串入上面的方法,你會怎麼做:

private void PrintA(String a) { 
    // Whatever 
} 
1

除非我錯過了一些很大的東西,否則你無法每次將studentName數組設置爲除新數組之外的任何其他數據。

String studentNames[] = new String[numbers]; 

您只是每次都將它設置爲空數組。

0

我可能會錯過這裏的東西,但我沒有看到你把姓名或陣列中的成績。這可以通過將以下代碼放入循環中來完成:

enter code here studentNames [i] = names;然後

輸出可以用:

for(x=0;x<studentNames.length;i++){ 
System.out.println(studentNames[x]); 
}