java输入有问题,输入一个int后,第一个字符串为什么没输入进去

public class Main {

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    String[] a=new String[10000];
    for(int i=1;i<=n+1;i++) {
        a[i]=sc.nextLine();
    }
    System.out.println(a[1].length());
    
}

}

为什么输入int后第一个字符串不会被输入进去

img


照理说不是一个输入两个字符串吗为什么输入一个字符串而且第一个字符串长度是0了

  • 由于输入整数后又输入了一个回车,nextInt()读入整数后不会管后面的回车,所以回车被循环里的nextLine接收了,自然a[1]中存储的是换行符。
  • 处理回车的问题可以在读入整数后再读入一行字符将余留的回车吸收掉~
    比如:
    public class Solution {
      public static void main(String[] args) {
          Scanner sc=new Scanner(System.in);
          int n=sc.nextInt();
    //        吸收输入整数后留下的换行符
          String temp = sc.nextLine();
          String[] a=new String[10000];
          for(int i=1;i<=n+1;i++) {
              a[i]=sc.nextLine();
          }
          System.out.println(a[1].length());
      }
    }
    
    如果对你有帮助,请点击采纳,能再来个关注就更nice了,感激不尽~~~

下面链接有详细解释:
https://blog.csdn.net/qq_38367575/article/details/120420633