+ 16
Looking for a safe way to read multiple inputs using Java Scanner in Code Playground
What would be the recommended way to read multiple inputs (just assume numbers) in Code Playground? How can we make the code be more fault tolerant when handling multiple inputs? I'm interested in `NoSuchElementException` handling in particular. Do we put try...catch block inside a loop, or possibly another better way? Pardon me as I have no particular code in regards to this issue. I'm just looking forward to know some feasible techniques. My goal is to know how to make a code exits the input-reading loop safely when there is no more input to read. Thank you in advance ๐ P.S. I did search with 'NoSuchElementException' search term, unfortunately the results didn't help. (Edited)
17 odpowiedzi
+ 8
In order to check for further input in the the input stream with Scanner and to avoid the NoSuchElementException, you can use the .hasNext() method for your loop condition.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
https://www.educative.io/edpresso/how-to-resolve-the-javautilnosuchelementexception-in-java
+ 6
You'll still have to handle the inputs and verify that they are what you are needing and are the correct type (or can be converted to).
Personally I would most like use the .hasNext() then check if it is and can be converted to they desired type so I handle the errors gracfully etc.
That being said if it was guaranteed to be the correct type (int) then hasNextInt() would be fine. For instance, if you were using a GUI that only allowed an int to be entered in the input box(s).
+ 6
Coder Kitten
It was not until you posted your answer did I realise my question went like one of those best language polling, sorry ๐
I was not really thinking about "On Error Resume Next", it's a bad practice even a retired VB coder knows (so over it now ๐).
I was looking forward to instead, break out of the loop altogether, safely and gracefully, for when input read, or conversion fail (case when input is read as String)
Big Thanks ๐
+ 5
Coder Kitten
I don't know (yet) how to implement a Container class in Java. I thought about using array, but considering I don't know how many times the loop will run (how many inputs will be given), the size of array is unpredictable.
So I came up with an idea to make a simple input validator class which handles the conversion internally by using try-catch block in a static method.
Optional is now one of my new topic, it's new and foreign for now ...
https://code.sololearn.com/cAcinytEFAMK/?ref=app
+ 5
Coder Kitten
Nice idea ๐
However, at the moment I'd like to hear and learn more ideas for handling multiple inputs safely. For the scenario, <number> are read in, added to <sum>, then discarded, I'm not sure about the need for storing the numbers.
+ 4
In Python:
while True:
try:
x = input()
list.append(x)
except EOFerror:
break
+ 4
Havent finished Java yet...
+ 4
ChaoticDawg
Thank you very much ๐
This is what I have for now, so how do I handle the 'InputMismatchException' for this? do I put the .nextInt() call inside a `try` block? or do I take input as String and use some conversion utility?
https://code.sololearn.com/cFF9wiR72t2A/?ref=app
+ 4
Tibor Santa
I have to be honest I was kind of puzzled as I read the code. I'm not familiar with Java streams, or functional programming, I learned just bits of the basics.
But know that your contribution to this duscussion will help many learners here to improve. That is the power of sharing! ๐
Thank you very much ๐
+ 3
Thanks for answering ๐ง๐ฉ๐ณโ๐ดโ๐ทโ'๐ผโ๐ชโ๐ธโ๐นโ๐ชโ๐ทโ ๐
Got an idea how to achieve the same in Java?
+ 3
ChaoticDawg
Would it matter whether we use while loop or do...while loop? should we check .hasNext() ahead of time or later?
Does .hasNextInt() paired with .nextInt() work the same with .hasNext()?
+ 3
Yes, I would use a try-catch here. Maybe, give some feedback and then move on to the next iteration. Remember, end users will do stupid things with your programs. Things that you wouldn't normally expect. So handle anything and everything that could make your program behave in a way that isn't intended (crash etc).
+ 3
Ipang I though this topic was quite interesting for further exploration, and I came up with a stream-based solution. This code shows also how Scanner can process files and strings, and also making basic statistics from a bunch of numbers.
https://code.sololearn.com/cOmbgk1qejM5/?ref=app
+ 3
A little explanation on my code. I used two ideas to handle exceptions. First, the Scanner is created as an auto-closable resource, this helps with the IOException and also protects against the error that beginners often do, creating multiple Scanner instances using the same input stream (System.in)
Then parsing the numbers is in a separate method that returns null when the data is not recognized as a number. So an exception does not break my stream, but it is logged anyway. These null values are filtered out from the final result.