扫描仪没有拿起文件的内容?

时间:2014-11-23 03:28:13

标签: java arraylist java.util.scanner

我的程序中有一个小问题/错误,无法正确扫描内容。 我相信我正在使用正确的命令? 例如:java homework5 hwk5sample1.txt 为什么没有任何内容被扫描并存储在我的ArrayList

import java.io.*;
import java.util.*;
import java.lang.*;

public class homework5 {

  public static int penny = 1;
  public static int nickle = 5;
  public static int dime = 10;
  public static int quarter = 25;
  public static int halfDollar = 50;
  public static int dollar = 100;
  public static int change;

  public static void main(String[] args)
    throws FileNotFoundException {

    ArrayList<Integer> coinTypes = new ArrayList<Integer>();

    File f = new File (args[0]);
    Scanner input = new Scanner(f);
       while (input.hasNextInt()) {
            System.out.println("Found next int"); //used for debugging
            int i = input.nextInt();
            coinTypes.add(i);
            if (input.hasNextLine()) {
               change = input.nextInt();
                System.out.println("Found change"); //used for debugging
                System.out.println("Change: " + change);
            }
       }
    System.out.println(coinTypes); //used for debugging
  }
}

注意额外的System.out.println()用于向我显示扫描仪找到指定内容的输出,显然没有显示任何内容。有什么问题?

output: []

这是我在命令

中使用的hwk5sample1.txt文件
// Coins available in the USA, given in cents.  Change for $1.43?
1 5 10 25 50 100
143

任何和所有帮助表示赞赏!谢谢

编辑在我的作业说明中,它需要能够忽略这样的评论并仍然有效,因为测试人员将使用类似的文件

1 个答案:

答案 0 :(得分:3)

添加input.nextLine()以阅读该评论专栏

CODE

input.nextLine();
while (input.hasNextInt()) {
    System.out.println("Found next int"); // used for debugging
    int i = input.nextInt();
    coinTypes.add(i);
    if (input.hasNextLine()) {
        change = input.nextInt();
        System.out.println("Found change"); // used for debugging
        System.out.println("Change: " + change);
    }
}

输出

Found next int
Found change
Change: 5
Found next int
Found change
Change: 25
Found next int
Found change
Change: 100
Found next int
[1, 10, 50, 143]