2014-11-22 20 views
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(); 

但是,我收到此錯誤消息,指出它是需要字符串的不兼容類型。我如何使它能夠掃描下一行並將其設置爲整數?感謝您的幫助!

+0

你必須閱讀這個'1 5 10 25 50 100'或'143' – Joe 2014-11-22 01:40:56

回答

1

解析字符串到整數change = Integer.parseInt(input.nextLine());

+1

謝謝你這似乎是解決方案 – GEARZ 2014-11-22 01:46:45

0

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