Java code hangs at Scanner hasNextLine

后端 未结 2 1578
轻奢々
轻奢々 2021-01-22 17:41

First off, I\'m new to java and trying to complete an assignment from school on creating a vending machine. My program is taking in 2 files as cli arguments, one for products, a

相关标签:
2条回答
  • 2021-01-22 18:19

    Remove semicolon from the line

     while (moneyTemp.hasNextLine());
    

    Semicolom make the while loop complete its body without doing anything means its like while(){} when while condition is true do nothing and since your condition is hasNextLine() it checks for same line again and again causing infinite loop.

    0 讨论(0)
  • 2021-01-22 18:39

    By adding the semicolon (;), you are implicitly having the while loop execute an empty block. hasNextLine() doesn't doesn't change the InputStream the scanner is based on, so since there's nothing in the while loop's body, there's nothing to change the state, and the loop will just continue forever.

    Just drop the semicolon from the while loop, and you should be fine:

    while (moneyTemp.hasNextLine()) // no ; here!
    {
        numMoney++;
        moneyTemp.nextLine();               
    }
    
    0 讨论(0)
提交回复
热议问题