【问题标题】:Java Array 2D not working with parametersJava Array 2D 不使用参数
【发布时间】:2019-03-12 15:38:23
【问题描述】:

我是社区的新人,我需要 Java 中的 Array 2d 方面的帮助 是学校的项目 这是我的问题

我用静态长度构建 Array 2D 并且可以工作,但是带有参数的相同代码不起作用。

首先打印 System.out.print("Insert Name");

之后不执行语句matrix[i][0] = input.nextLine();

第三次打印 System.out.print("插入姓氏");

现在可以工作,但索引 [0],[0] 为空

打印示例:

一个

b b

c c

谢谢!!!

import java.util.*;

public class Students {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner input = new Scanner(System.in);

    System.out.println("Insert number of Students");

    int numStudents = input.nextInt();

    String[][] matrix = new String[numStudents][2];

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

        System.out.print("Insert Name");

        matrix[i][0] = input.nextLine();                                                                            

        for (int j = 1; j < 2; j++) {

            System.out.print("Insert Last Name");

            matrix[i][j] = input.nextLine();

        }
    }

    for(int z=0; z<numStudents ;z++) {

        System.out.println();

        for(int h=0; h<2;h++) {

            System.out.printf(matrix[z][h]);
            System.out.printf(" ");
        }

    }

   }
  }

【问题讨论】:

标签: java arrays eclipse parameters 2d


【解决方案1】:

我认为这应该适合你。 无需嵌套 for 循环即可读取姓氏。

   public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);

        System.out.println("Insert number of Students");

        int numStudents = input.nextInt();
        input.nextLine();
        String[][] matrix = new String[numStudents][2];

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

            System.out.println("Insert Name");
            matrix[i][0] = input.nextLine();
            System.out.println("Insert Last Name");
            matrix[i][1] = input.nextLine();
        }

        for (int z = 0; z < numStudents; z++) {
            System.out.println();
            for (int h = 0; h < 2; h++) {
                System.out.print(matrix[z][h]);
                System.out.print(" ");
            }
            System.out.println();
        }
    }

【讨论】:

    【解决方案2】:

    使用字符串值= input.next();而不是 input.nextLine(); 要么 使用额外的 input.nextLine();在 input.nextInt() 之后; 即

    int numStudents = input.nextInt();
    input.nextLine()
    

    发生这种情况是因为 input.nextInt() 只读取一个整数并且没有完成该行。

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 1970-01-01
      • 2022-12-01
      • 2021-07-06
      • 2019-01-06
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多