0

scanner.nextLine();

I'm having a problem with this program I made that's just supposed to take a name, address, and phone number and add them to an arraylist. The first time I call the method to take a name, it works perfectly, then moves on to address, phone number, and then prompts me to chose what I want to do with that information. Problem is, if I choose to add more information by calling the TakeName() method, the input is skipped, but the print statement is printed, and the TakeAddress() method is called immediately. The same problem occurs when I try to use the Find() method. It just skips over my input, but still displays the print statements as it should. Here's my code, I would've made an actual project on SoloLearn, but it handles inputs differently than NetBeans does. public void TakeName(){ String name; System.out.print("Enter a name: "); name = input.nextLine(); Names.add(name.trim()); TakeAddress(); } public void TakeAddress(){ String address; System.out.print("Enter an address: "); address = input.nextLine(); Addresses.add(address.trim()); TakePhone(); } public void TakePhone(){ String phone; System.out.print("Enter a phone number: "); phone = input.nextLine(); PhoneNums.add(phone.trim()); System.out.print("Information Added."); Select(); } public void Select(){ int select; System.out.println(); System.out.println("1. Add more information\n2. Find information\n3. Show all\n4. End Program"); select = input.nextInt(); System.out.println(); switch (select){ case 1: TakeName(); break; case 2: Find(); break; case 3: Show(); break; default: System.out.println("Program Ended."); } }

17th Dec 2017, 10:16 PM
Zackary Lee
Zackary Lee - avatar
3 Answers
+ 5
You have a floating newline character in your input stream. nextInt() will only read in the numerical part from the stream and leaves the '\n'. Same goes for nextDouble(), nextFloat(), etc. You can solve this issue a couple of ways. One is the consume the newline character by adding a call to next() or nextLine() after a call to nextInt() in which the following call is a nextLine() that is used for actual input. You can also just use nextLine() in place of your nextInt() call and then parse it for the integer input.
17th Dec 2017, 11:08 PM
ChaoticDawg
ChaoticDawg - avatar
+ 7
Could you please use the Code Playground so we can see the output? It makes it easier for us to help you.
17th Dec 2017, 10:24 PM
Learnsolo
+ 1
@<Learnsolo>, I wasn't able to figure out how to get the user input's working correctly, since the code playground takes all inputs at the beginning of the program, and my program can take multiple other inputs depending on what the user does.
17th Dec 2017, 11:49 PM
Zackary Lee
Zackary Lee - avatar