+ 1
Read a String after an Integer
Hello, my program throws an error... i think it is because I put first an Integer and then a String... but im not sure. Can anyone help? https://code.sololearn.com/ca8A15A24a13/?ref=app
14 Réponses
+ 2
Sandeep Kushwaha
Diego Becerril
Martin Taylor
Better change Scanner delimiters regex
Scanner s = new Scanner(System.in)
// ADDED
.useDelimiter("\n")
;
and to recover original, call reset()
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Scanner.html#useDelimiter(java.lang.String)
Added to my code.
https://code.sololearn.com/c1UK7uiKcrxp/?ref=app
+ 1
That's fine as long as you input a number on the first line hit enter and input a string on the second line then run, it should be ok.
+ 1
Diego Becerril you pass your funtion a string and the strings length
Your first if statment sees this and if the string length does not equal 0 then it falls to the else statement and its repeating its self there.
+ 1
Martin Taylor, yeah i was thinking that... how can i solve it?
+ 1
Martin
I agree with you, the program also must treat errors produced by a bad input to retrofit user about. Eg. Showing error and request same input again using a do-while and catching exceptions, or infer defaults...
In Scanner: NoSuchElementException when EOF and InputMismatchException on bad type.
In Integer:
NullPointerException y
NumberFormatException when no match
Due to this it's wellknown you should have in one hand your program and the other the api docs 😂😂
Resuming... Input all in line e.g.
9 Hola amigos del Java
It works with my patch
0
Yeah, the problem is when I enter the number 9 the program stops giving me a StackOvdrFlowError
0
Yes, but what can i do? I mean... all seems to be good, why the error?
0
Easy... swap condition... and code seems cleaner
Pseudocode:
==========
If i > 0 {
despR(s, i-1);
}
Print (c at i)
0
Yeah, i think all its good, but the error is that when I enter the 9 the program doesnt even allow me to enter the String
0
Martin Taylor I think that it only happens here in Playground because Scanner read by default any of Character.isWhitespace() including CRLF
Also there are a particularity about nextInt respect parseInt. First only consume digits while parseInt accepts formatted in e-notation. Even, if first part are valid num and found other non valid... the rest it's ignored.
a bit of light
- https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Scanner.html
- https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)
**** input popup
Diego Becerril here some optimizations in the line I explained you
https://code.sololearn.com/c1UK7uiKcrxp/?ref=app