Java Scanner hasNext() doesn't return false

前端 未结 1 2041
醉话见心
醉话见心 2020-12-12 02:29

I am trying to read input continuously from the user until the user types quit. I am testing it by just typing \'quit\' but console.hasNext() doesn\'t seem to be returning f

相关标签:
1条回答
  • 2020-12-12 02:59

    If your Scanner is declared as System.in, it will be asking System.in if there is a next value to be received. The in class will then wait for the user to input something, then return true.

    Reserve hasNext() for things like files, where the input size is fixed. That way, when Scanner queries the file, it has a definite hasNext().

    Instead, I suggest grabbing the next value as a String, then checking if it matches the integer format. If it does, then convert it, otherwise, handle it however you'd like.

    0 讨论(0)
提交回复
热议问题