Java 如何扫描整数文件的下一行?

Java 如何扫描整数文件的下一行?,java,recursion,java.util.scanner,Java,Recursion,Java.util.scanner,在我的程序中,我试图使用扫描仪扫描一个充满整数的文件。这是一个家庭作业,要求我写一个程序,显示用给定的硬币组成预定金额的所有方法,测试人员使用这样的文件 // Coins available in the USA, given in cents. Change for $1.43? 1 5 10 25 50 100 143 我的输出需要有最后一行(代表总金额的行,例如143) 看起来像这样: change: 143 1 x 100 plus 1 x 25 plus 1 x 10 plus 1

在我的程序中,我试图使用扫描仪扫描一个充满整数的文件。这是一个家庭作业,要求我写一个程序,显示用给定的硬币组成预定金额的所有方法,测试人员使用这样的文件

// Coins available in the USA, given in cents.  Change for $1.43?
1 5 10 25 50 100
143
我的输出需要有最后一行(代表总金额的行,例如143) 看起来像这样:

change: 143
1 x 100 plus 1 x 25 plus 1 x 10 plus 1 x 5 plus 3 x 1
1 x 100 plus 0 x 25 plus 4 x 10 plus 0 x 5 plus 3 x 1
1 x 100 plus 0 x 25 plus 3 x 10 plus 2 x 5 plus 3 x 1
1 x 100 plus 0 x 25 plus 2 x 10 plus 4 x 5 plus 3 x 1
1 x 100 plus 0 x 25 plus 1 x 10 plus 6 x 5 plus 3 x 1
1 x 100 plus 0 x 25 plus 0 x 10 plus 8 x 5 plus 3 x 1
2 x 50 plus 1 x 25 plus 1 x 10 plus 1 x 5 plus 3 x 1
2 x 50 plus 0 x 25 plus 4 x 10 plus 0 x 5 plus 3 x 1
...
我的挣扎是我有一个初始化的变量

Integer change;
我把它设置为

change = input.nextLine();

但是,我收到这个错误消息,指出它是一个不兼容的类型,需要一个字符串。我如何才能扫描下一行并将其设置为整数?谢谢你的帮助

将字符串解析为整数
change=Integer.parseInt(input.nextLine())

这是来自Java的扫描仪吗?如果是这样,试试这个

Scanner scantron = new Scanner( 'input file' );

// can be dynamically added to easier than normal arrays
ArrayList<Integer> coins = new ArrayList<Integer>();

int change;

// toggle flag for switching from coins to change
boolean flag = true; 

while(scantron.hasNextLine())
{
    // if this line has no numbers on it loop back to the start
    if(!scantron.hasNextInt()) continue; 

    // getting the first line of numbers 
    while(flag && scantron.hasNextInt()) coins.add(scantron.nextInt());

    // set the flag that the coins have been added
    flag = false;

    // if this is the first time the flag has been seen ignore this
    // otherwise the next line should have the change
    if(!flag) change = scantron.nextInt();
}
Scanner scantron=新扫描仪(“输入文件”);
//可以动态添加到比普通阵列更简单的阵列中
ArrayList硬币=新的ArrayList();
智力变化;
//切换标志,用于从硬币切换到更改
布尔标志=真;
while(scantron.hasnetline())
{
//如果这条线上没有数字,则循环回到起点
如果(!scantron.hasNextInt())继续;
//获取第一行数字
while(flag&&scantron.hasnetint())coins.add(scantron.nextInt());
//设置已添加硬币的标志
flag=false;
//如果这是第一次看到该标志,请忽略此项
//否则,下一行应该有更改
如果(!flag)change=scantron.nextInt();
}

您必须阅读此
1 5 10 25 50 100
143
谢谢这似乎是解决方案