使用for循环将字符串存储在锯齿状数组中

时间:2017-09-22 20:21:30

标签: java arrays string for-loop jagged-arrays

我遇到了这个question,想要重新创建它,但是用一串字符串而不是整数填充它。我想使用数组而不是ArrayList只是因为我是初学者并且想用数组练习更多。我几乎复制了代码,但我一直在输出中出错。这是我的代码:

Scanner input = new Scanner(System.in);
    System.out.print("Enter number of arrays: "); 
    int x = input.nextInt();
    String [][] array = new String[x][0]; 

    for(int i = 0; i < x; i++){
       System.out.print("Enter number of elements for array: ");
       int s = input.nextInt();
       array[i] = new String[s]; 

       for(int j = 0; j < s ; j++){ 
          System.out.print("Enter string: ");
          String word = input.nextLine();
          array[i][j] = word;
       }
    }

我的输出是:

Enter number of arrays: 2
Enter number of elements for array: 3
Enter string: Enter string: hello
Enter string: hi
Enter number of elements for array: 2
Enter string: Enter string: goodbye

为什么打印&#34;输入字符串&#34;每次两次?这个逻辑对我来说很有意义,所以我不确定导致输出错误的原因。它是for循环还是只是字符串的工作方式?对代码的解释和帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

逻辑是正确的,但nextInt()方法只读取数字而不是&#39;输入&#39;你在其后输入的字符,所以当你拨打nextLine()方法时,第一次在你的循环中它会读到&#39;输入&#39;字符,第二个读取您的输入,所以第三个。 要避免此问题,您可以在nextLine()之后调用nextInt(),而不将其分配给变量,以便它读取待处理字符:

 for(int i = 0; i < x; i++){
   System.out.print("Enter number of elements for array: ");
   int s = input.nextInt();
   input.nextLine();
   array[i] = new String[s]; 

   for(int j = 0; j < s ; j++){ 
      System.out.print("Enter string: ");
      String word = input.nextLine();
      array[i][j] = word;
   }

答案 1 :(得分:1)

问题只在于input.nextInt()没有抓住换行符。如果您只是在每个input.nextInt()行之后粘贴input.nextLine(),它应该可以工作。