如何将1d字符串数组放入循环中?

时间:2015-10-03 08:35:11

标签: arrays string 2d

我在第一,第二,第三,......条目中输入名称时遇到问题...例如我的代码输出会产生这样的结果:

Ouput:
Input Name 1 : Input student hw score 1 : 2
Input student test score 1 : 3
Input finaltest score 1 : 2

所以问题是我无法在循环中输入任何名称,所以我该如何解决这个问题?

public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Contoh : ");
        int noOfRows;
        int noOfColumns;
        int[][] noOfArrays;
        String names[];

        System.out.print("Input no of students : ");
        noOfRows  = sc.nextInt();
        noOfColumns = noOfRows;


       //////////////////////////////////
        names = new String[noOfRows];   

        ///////////////////////
        noOfArrays = new int[noOfRows][noOfColumns];

        System.out.println("====================");

        for(int i = 0 ; i<noOfRows ;i++)
        {
                System.out.print("Name "+(i+1)+" : ");
                names[i] = sc.nextLine();
                System.out.print("Input students hw score "+(i+1)+" : ");
                noOfArrays[i][0] = sc.nextInt();
                System.out.print("Input student test score "+(i+1)+" : ");
                noOfArrays[i][1] = sc.nextInt();
                System.out.print("Input finaltest score "+(i+1)+" : ");
                noOfArrays[i][2] = sc.nextInt();
        }

    }

2 个答案:

答案 0 :(得分:0)

更改names[i] = sc.nextLine(); ----&gt; names[i] = sc.next();

这样可行。

另外,
您的课程仅适用于3人以上的学生。

答案 1 :(得分:0)

我没有这么深入的java知识,这是我的(可能不是很好)工作的例子。只需添加sc.nextLine()省略eol。

    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Contoh : ");
        int noOfRows;
        int noOfColumns;
        int[][] noOfArrays;


        System.out.print("Input no of students : ");
        noOfRows  = sc.nextInt();
        noOfColumns = noOfRows;


       //////////////////////////////////
        String names[] = new String[noOfRows];   
;
        ///////////////////////
        noOfArrays = new int[noOfRows][noOfColumns];

        System.out.println("====================");

        for(int i = 0 ; i<noOfRows ;i++)
        {       
                sc.nextLine();
                System.out.print("Name "+(i+1)+" :");
                names[i] = sc.nextLine();
                System.out.print("Input students hw score "+(i+1)+" : ");
                noOfArrays[i][0] = sc.nextInt();
                System.out.print("Input student test score "+(i+1)+" : ");
                noOfArrays[i][1] = sc.nextInt();
                System.out.print("Input finaltest score "+(i+1)+" : ");
                noOfArrays[i][2] = sc.nextInt();

        }

    }