二维字符串数组跳过第一个值

two dimensional String array skipping first value

我正在尝试从用户输入的二维字符串数组中插入一些值,我正在使用两个代码来测试它,但它们都跳过第一列并且不存储任何内容。这是代码和结果图像。

第一个密码:

      Scanner sc= new Scanner(System.in); 
      System.out.print("Enter Number of Students ");  
      int a= sc.nextInt();
      String [][] StudentDetail = new String[a][2];
      System.out.println("Enter Details of "+ a+ " students"); 

       for (int row = 0; row < StudentDetail.length; row++) {
       System.out.print("Enter  name: ");
       StudentDetail[row][0] = sc.nextLine();

       System.out.print("Enter a ID ");
       StudentDetail[row][1] = sc.nextLine();

       }
    System.out.println( StudentDetail[0][0] ); 
               System.out.println( StudentDetail[0][1] );
        }
    

第二个密码:

 for (int i=0; i<a; i++) {
           
      System.out.println("Enter Details of student "+ (i+1));
      for (int j=0;j<2;j++){
      StudentDetail[i][j] = sc.nextLine();
            
           }
       }

第一个代码的结果:

问题不在于数组和维度。 这是关于扫描仪。在 next() of nextInt() 方法之后第一次使用 nextLine 时,它只读取最后一行的 EOL,而不是下一行, 正如您自己注意到的那样,下一行就可以了。 为了解决这个问题,你应该只做一个 ‍sc.nextLine()‍; 而不使用它的 return 值。

您的代码将是这样的:

      Scanner sc= new Scanner(System.in); 
      System.out.print("Enter Number of Students ");  
      int a= sc.nextInt();
      String [][] StudentDetail = new String[a][2];
      System.out.println("Enter Details of "+ a+ " students"); 
    
      sc.nextLine(); // to ignore the EOL after int in the first line

      for (int row = 0; row < StudentDetail.length; row++) {
             System.out.print("Enter  name: ");
             StudentDetail[row][0] = sc.nextLine();

             System.out.print("Enter a ID ");
             StudentDetail[row][1] = sc.nextLine();

       }
       System.out.println( StudentDetail[0][0] ); 
       System.out.println( StudentDetail[0][1] );

如需了解更多信息,您可以考虑阅读以下链接:

Scanner is skipping nextLine() after using next() or nextFoo()?

https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/

看到这个问题:Scanner is skipping nextLine() after using next() or nextFoo()?

基本上,您的代码不会跳过第一列。相反,它在第一列中存储了一个空字符串,这就是您在输出中看不到任何内容的原因。这是由于 nextInt() 在询问学生人数时没有读入最后的换行符造成的。您可以通过在 nextInt() 调用之后添加对 scanner.nextLine() 的调用来解决此问题,例如:

  Scanner sc= new Scanner(System.in); 
  System.out.print("Enter Number of Students ");  
  int a= sc.nextInt();
  sc.nextLine();
  String [][] StudentDetail = new String[a][2];
  System.out.println("Enter Details of "+ a+ " students"); 

这将消耗换行符,使循环中对 nextLine() 的调用实际上 return 是正确的结果。