【问题标题】:How to print one line from ArrayList based on a textfile?如何根据文本文件从 ArrayList 打印一行?
【发布时间】:2017-05-02 14:30:19
【问题描述】:

现在我们可以从文本文件中打印出一行 按行号。问题是当我们能够打印出 再次行号(产品),直到我们达到产品的限制 我们的文本文件。我们如何停止循环,使其只打印一行 我们选择?

static ArrayList<Product> printOneLine() {
    ArrayList<Product> oneLineList = new ArrayList<Product>();
    Scanner oneLine = readDetails("Products-JavaBikes.txt");

    while (oneLine.hasNextLine()) {
        oneLineList.add(getProduct(oneLine.nextLine()));

        Scanner input = new Scanner (System.in);            
        System.out.print("Please enter a number:");

        for (int i = input.nextInt(); i < oneLineList.size();) {                    
            System.out.println(oneLineList.get(i));
            break;
        }   
    }
    return oneLineList;
}

【问题讨论】:

  • 您是否有理由在行迭代循环中询问数字,而不是在开始时只询问一次,然后使用结果来查找正确的行?
  • 您应该从用户界面获取号码,然后您可以返回 oneList.get(userEnteredLineNumber);
  • 那个for循环没有意义,我想你正在寻找一个if语句。 for 循环是 for 循环,如果你在第一次迭代中无条件地中断,那么你做错了什么。此外,您可能想调试您的代码,甚至只是逐步思考它在做什么 - 从长远来看,我们只是告诉您如何修复您的代码对您没有帮助。

标签: java arrays loops text-files


【解决方案1】:

你的问题有点不清楚。但是我认为您正试图在找到输入的产品时打破您的 while 循环。我将多余的 for 循环更改为 if 语句,以便您可以中断 while 循环。您的 break 只是从 for 循环中中断,而不是 while 循环。

static ArrayList<Product> printOneLine() {
    ArrayList<Product> oneLineList = new ArrayList<Product>();
    Scanner oneLine = readDetails("Products-JavaBikes.txt");

    while (oneLine.hasNextLine()) {
        oneLineList.add(getProduct(oneLine.nextLine()));

        System.out.print("Please enter a number:");
        Scanner input = new Scanner (System.in);            

        if(input.nextInt() < oneLineList.size()) {                    
            System.out.println(oneLineList.get(i));
            break;
        }   
    }
    return oneLineList;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多