+ 1

Help me

My code is throwing errors for no reason UnU Plz help mešŸ˜“ https://code.sololearn.com/cKiB6lcLmeNP/?ref=app

30th Sep 2021, 3:08 PM
Rishi
Rishi - avatar
5 Answers
+ 2
Rishi, It's the same problem we get in C++ when reading a line (using std::getline()) after reading value using std::cin. There's that '\n' character left behind in the input stream after reading <age> by Scanner.nextInt() and <salary> by Scanner.nextDouble(). So we need to get rid of it by calling Scanner.nextLine() which will consume the leftover '\n' character. name=input.nextLine(); age=input.nextInt(); input.nextLine(); // consume the '\n' occupation=input.nextLine(); salary=input.nextDouble(); input.nextLine(); // consume the '\n' bank=input.nextLine();
30th Sep 2021, 3:40 PM
Ipang
+ 2
Ipang plz tell me more about this problem. I've heard a lot about this issue but never really understood it. Like, every time I enter something, like an int to the input stream, the extraction leaves a '\n'. This is all I understood. But what if I entered another int and extract it, there's already a '\n' there followed by my int, then why doesn't the integer extraction fail? Or it should say like, '\n' character encountered in place of an integer. Right? Explain briefly about this plzšŸ™Œ
30th Sep 2021, 4:08 PM
Rishi
Rishi - avatar
+ 1
Rishi nextInt() search an integer from current position in stream of input ,if found reads until a non-int value encounters and stops there.. next line() read all charecters from current position to end or upto \n encounters so after reading position of current reading pointer goes to next line... So for ex: age=input.nextInt(); str=input.nextLine(); If input is like : 35 abcd 35 will goes to age and next all text goes to str.( abcd)includes space. if you input like: 35 abcd Then 35 will read into age and \n will read by nextLine() and str=""; abcd will not read into str; so this is problem here. So you input like 35 abcd As a solution ,you read everyline of separately by nextLine() use proper convertion like age= Integer.parseInt( input.nextLine() ); str = input.nextLine(); Hope it helps.....
30th Sep 2021, 6:33 PM
Jayakrishna šŸ‡®šŸ‡³
0
JayakrishnašŸ‡®šŸ‡³ what if my input is like (empty newline (\n)) 12 Hello What will the nextInt() function do when it sees an empty newline character before the integer?
1st Oct 2021, 4:54 AM
Rishi
Rishi - avatar
0
age=input.nextInt(); str=input.nextLine(); If this is code then nextInt() reads 12 and ignores spaces and \n charecters before it or not starts its work until an integer encounters... But str="" empty because, current input stream position is just after 12 and \n charecter is read by nextLine(); Works fine for input 12 Hello So you have to take care arranging of input taking lines in an order of taking similar data types or use conversion methods as I mentioned previous post.. hope it helps..
1st Oct 2021, 1:43 PM
Jayakrishna šŸ‡®šŸ‡³