简体   繁体   中英

How to scan the next line of a file of integers?

In my program, I am trying to use a Scanner to scan a file full of integers. This is a homework assignment asking me to write a program that shows all ways of making up a predetermined amount of money with the given coins, and the tester uses files like this.

// Coins available in the USA, given in cents.  Change for $1.43?
1 5 10 25 50 100
143

My output needs to have the very last line (the line representing the total amount of money ex: 143) to appear like this:

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
...

my struggle is that I have an initialized variable,

Integer change;

and I have it set to

change = input.nextLine();

However, I get this error message stating that it is an incompatible type requiring a String. How do I make it to where I can scan the next line and set it to an integer? Thank you for any and all help!

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

Is this the Scanner from Java? If so try this. . .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM