【问题标题】:Accepting a 2D array as input in Java在 Java 中接受二维数组作为输入
【发布时间】:2014-03-24 23:20:53
【问题描述】:

我正在编写一个 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.
            }
        }

    }

} 

【问题讨论】:

  • 为什么你认为in.nextInt() 行不通?你试过了吗?
  • 显示你想要输入的格式...

标签: java arrays 2d


【解决方案1】:

试试这个:

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 到 6 的标记,并且你放置 int 存储一个介于 -2000000000 和 2000000000 之间的数字,你可以通过使用 byte 而不是 int 来节省内存 -> 更快的计算和 byte 仍然适合 1..6 范围。
猜你喜欢
  • 2021-12-07
  • 2023-03-10
  • 2012-03-08
  • 2017-02-21
  • 2020-04-12
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多