Java, using scanner, exception

前端 未结 1 619
醉梦人生
醉梦人生 2021-01-29 08:03

Could someone show me what i\'m doing wrong, this part of code should scan for name of restaurant, menu name and names of menu items and their prices, but it\'s giving me some s

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 08:34

    First lets get the problem of your string testing out of the way:

    Don't == or != to test strings in Java. Unless you really, really know what you are doing, == and != are liable to give your the wrong answer. Use s.equals(s2) or !s.equals(s2).

    Your original code uses both == and != to compare strings, and this is a situation where the test will be unreliable. Fix all of these ...

    Reference:

    • How do I compare strings in Java?

    Now we have the problem of what is causing InputMismatchException to be thrown. You have told us that it is coming from a simple println, but that is virtually impossible. In reality, the stacktrace says that exception is being thrown by a nextDouble() call, and that will be happening because (as the javadoc says) "... the next token does not match the Float regular expression, or is out of range".

    What is the cause? Well it could be two things:

    • It could be that the user has entered something that is not a number in the right syntax. For example, "four" or "my brain hurts".

      A properly written program should deal with this ... by telling the user he/she has made a mistake. (For example, use the hasDouble() method to test if the next token is acceptable as a double.)

    • It could be that a logic error in your code means that you are attempting to read the answer to some other question (or something) as a number.

    I can't tell you which of those is the real cause, because frankly I don't trust the "evidence" that you have provided. I doubt that that is the real code, and it certainly doesn't match the stacktrace. Furthermore, you haven't told us what the "user" is typing to cause this to happen.

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