2014-02-23 60 views
0

我在寫一個Java程序,要求用戶輸入每個學生的標記(對於2個科目)(總共4名學生)。基本上,這是一個二維數組操作。在Java中接受二維數組作爲輸入

我被困在需要用戶輸入輸入的地步。我在想input.nextInt()的普通方法不起作用。這是我的代碼到目前爲止。有人可以幫忙嗎?

package Chapter2_Arrays; 
import java.util.*; 
public class Arrays_ExTwo { 

    static final int numberOfSubjects=2; 
    static final int numberOfStudents=4; 

    static int [][] marks=new int[numberOfSubjects][numberOfStudents]; 

    static Scanner in=new Scanner(System.in); 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     System.out.println("Welcome to Cincinnati Elementary"); 
     System.out.println("There are "+ " "+ numberOfSubjects+ " "+ "subjects being taught"); 
     System.out.println("There are "+" "+numberOfStudents+" "+" number of students in the class"); 
     System.out.println("Enter the subject number followed by the marks of all the students for the subject"); 
     for(int i=0;i<numberOfSubjects;i++) 
     { 
      for(int j=0;j<numberOfStudents;j++) 
      { 
       marks[i][j]=in. 
      } 
     } 

    } 

} 
+1

爲什麼你認爲'in.nextInt()'將無法正常工作?你試過了嗎? – Keppil

+2

顯示您想要輸入的格式... – Devavrata

回答

0

試試這個:

package Chapter2_Arrays; 
import java.util.*; 
public class Arrays_ExTwo { 

    static final int numberOfSubjects=2; 
    static final int numberOfStudents=4; 

    // byte is a number from -128 to 127; that's big enough for 1-6 marks; you can use char for 'A'-'F' marks. 
    static byte [][] marks=new byte[numberOfSubjects][numberOfStudents]; 

    static Scanner in=new Scanner(System.in); 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     System.out.println("Welcome to Cincinnati Elementary"); 
     System.out.println("There are "+ " "+ numberOfSubjects+ " "+ "subjects being taught"); 
     System.out.println("There are "+" "+numberOfStudents+" "+" number of students in the class"); 

     for(int i=0;i<numberOfSubjects;i++) 
     { 
      System.out.println("Enter the marks of students for subject no. "+(i+1)+":"); 
      for(int j=0;j<numberOfStudents;j++) 
      { 
       marks[i][j]=in.nextByte(); 
       System.out.println("Mark of student no. " + (j+1) + " for subject no. " + (i+1) + "was set to " + marks[i][j]); 
      } 
     } 

    } 

} 
+1

爲什麼要使用字節數組? –

+1

如果您使用1到6的標記,並且將int存儲在-2000000000和2000000000之間的數字,則可以使用byte而不是int來節省內存 - >計算速度更快,字節仍然適合1..6的範圍。 – ciuak