I'm writing a program which allows the user to input his data then outputs it. Its 3/4 correct but when it arrives at outputting the address it only prints a word lets say only 'Archbishop' from 'Archbishop Street'. How do I fix this?
import java.util.*; class MyStudentDetails{ public static void main (String args[]){ Scanner s = new Scanner(System.in); System.out.println("Enter Your Name: "); String name = s.next(); System.out.println("Enter Your Age: "); int age = s.nextInt(); System.out.println("Enter Your E-mail: "); String email = s.next(); System.out.println("Enter Your Address: "); String address = s.next(); System.out.println("Name: "+name); System.out.println("Age: "+age); System.out.println("E-mail: "+email); System.out.println("Address: "+address); } }
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line \n).
Why is Scanner skipping nextLine() after use of other next functions? The nextLine() method of java. util. Scanner class advances this scanner past the current line and returns the input that was skipped.
The nextLine() method of the java. util. Scanner class scans from the current position until it finds a line separator delimiter. The method returns the String from the current position to the end of the line.
This approach is working, but I don't how, can anyone explain, how does it works..
String s = sc.next(); s += sc.nextLine();
Initialize the Scanner this way so that it delimits input using a new line character.
Scanner sc = new Scanner(System.in).useDelimiter("\\n");
Refer the JavaDoc for more details
Use sc.next() to get the whole line in a String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With