【问题标题】:While loop with nextLine condition带有 nextLine 条件的 while 循环
【发布时间】:2014-04-30 06:06:49
【问题描述】:

我正在为一个使用数据库数据的类开发一种方法。我正在尝试使用while loop.nextLine 为我的数组values[] 做一个System.out.println 我希望有人可以提供一些建议。我知道还有其他方法可以做到这一点,但我希望不要使用任何额外的变量。如果那不可能,我完全理解,但我认为这里有人必须知道一种方法。感谢您的帮助,这是我的方法

    public void query(String table,String... column)
{
    System.out.println("name of table is: " + table);
    System.out.println("column values are: ");

    while(column[].nextLine())
        {
            System.out.println(column.nextLine());
        }

}//end method query()

【问题讨论】:

    标签: java arrays next


    【解决方案1】:

    nextLine() 不是数组的方法。不仅如此,你还用错了。你应该这样做(如果这些方法存在的话):while (column.hasNextLine())

    假设您想使用 while 循环来打印您的字符串数组:

    int i = 0;
    while(i < column.length)
    {
        System.out.println(column[i]);
        i++; // increment the index
    }
    

    或者您可以使用for-each 循环(或“enhanced-for”循环,不管它叫什么):

    for (String c : column) {
        System.out.println(c);
    }
    

    甚至是经典的 for 循环:

    for (int i = 0; i < column.length; i++) {
        System.out.println(column[i]);
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 enhanced-for(也称为 for-each)循环:

      for (String s : column) {
          System.out.println(s);
      }
      

      或者普通的for循环:

      for (int i = 0; i < column.length; i++) {
          System.out.println(column[i]);
      }
      

      如果您使用while,则必须保留索引计数:

      int i = 0;
      while (i < column.length) {
          System.out.println(column[i]);
          i++;
      }
      

      注意:

      记住column 是一个数组:String[] column

      【讨论】:

      • for-each 似乎是最优雅的解决方案,感谢您的帮助,您的回答是最全面的。谢谢
      • 是的,它是最优雅的。如果您不需要保留索引/位置的计数,请使用它。
      【解决方案3】:

      nextLine()Scanner 的方法,而不是String 的方法。如果您已经有一个 Strings 数组,您可以使用(增强的)for 循环遍历它们:

      public void query(String table, String... column) {
          System.out.println("name of table is: " + table);
          System.out.println("column values are: ");
      
          for (Strinc c : column) {
              System.out.println(c);
          }
      }
      

      【讨论】:

      • 只是为了说明column不是字符串引用,它类似于String[]
      • @JigarJoshi 实际上,我将其视为一个数组。
      猜你喜欢
      • 1970-01-01
      • 2022-11-12
      • 2015-05-18
      • 2017-12-09
      • 1970-01-01
      • 2014-12-22
      • 2015-06-25
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多