【问题标题】:store strings in a jagged array using for loop使用 for 循环将字符串存储在锯齿状数组中
【发布时间】:2018-03-04 12:03:09
【问题描述】:

我遇到了这个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

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

【问题讨论】:

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


    【解决方案1】:

    逻辑是正确的,但是 nextInt() 方法只读取数字而不是您在其后键入的“输入”字符,因此当您调用 nextLine() 方法时,第一次在循环中读取“输入”字符,第二个读取您的输入,第三个读取。 为避免此问题,您可以在 nextInt() 之后调用 nextLine(),而无需将其分配给变量,以便读取待处理字符:

     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;
       }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-30
        • 2011-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 2021-12-14
        • 1970-01-01
        相关资源
        最近更新 更多