[英]Accepting a 2D array as input in Java
我正在编写一个 java 程序,要求用户输入每个学生(总共 4 个学生)的分数(2 个科目)。 基本上,它是一个二维数组操作。
我被困在需要让用户输入的地方。 我在想 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.
}
}
}
}
尝试这个:
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]);
}
}
}
}
试试这个:
import java.util.Scanner;
public class temp {
public static void main(String[] args) {
int[][] my_array = create2DArray(4, 2);
takeUserInput(my_array);
displayElements(my_array);
}
public static int[][] create2DArray(int numRows, int numCols){
int[][] arrayInput = new int[numRows][numCols];
return arrayInput;
}
public static void takeUserInput(int[][] arrayInput){
Scanner sc = new Scanner(System.in);
for(int i = 0; i < arrayInput.length; i++){
for(int x = 0; x < arrayInput[i].length; x++) {
System.out.print("Enter number for the Index "+ i + "," + x + " ");
arrayInput[i][x] = sc.nextInt();
}
}
}
public static void displayElements(int[][] arrayInput){
for(int i = 0; i < arrayInput.length; i++){
for(int x = 0; x < arrayInput[i].length; x++) {
System.out.println(arrayInput[i][x]);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.