Reputation: 1417
I'm a beginner in Java and I just wrote a program to get the user's name, phone number and address. The problem is after reading the phone number the program will not proceed to read the address, it's like if it's skipping it. Here is my code:
public static void main(String [] arge){
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name, phone number and address");
String name = sc.nextLine();
long phone = sc.nextLong();
String address = sc.nextLine();
System.out.println("\n *** Here is your info ***");
System.out.println("Name: "+name+"\nPhone number: "+phone+"\n Address: "+address);
}
Upvotes: 1
Views: 3526
Reputation: 45070
long phone = sc.nextLong();
change this to
long phone = Long.parseLong(sc.nextLine());
Because after giving the phone number, the enter you hit is being consumed as the nextLine
which is set to your address
. Thus, the blank address(in the sense, the program doesn't prompt to you enter the address).
Another way to make your code work(without changing anything, YES without any changes!) is to provide your phone number and address in the same line as input. Scanner will take the space as the default delimiter and do the job for you. This is because nextLong()
will only scan for a long value.
Upvotes: 3
Reputation: 199
Try this.
import java.util.Scanner;
class ScannerTest{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}
Upvotes: 0
Reputation: 5366
try to read values one by one
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name");
String name = sc.nextLine();
System.out.println("Enter your phone number");
long phone = sc.nextLong();
sc.nextLine();//to catch the buffer"ENTER KEY" value
System.out.println("Enter your address");
String address = sc.nextLine();
System.out.println("\n *** Here is your info ***");
System.out.println("Name: "+name+"\nPhone number: "+phone+"\n Address: "+address);
Upvotes: 0
Reputation: 3368
Try this:
String name = sc.nextLine();
long phone = Long.parseLong(sc.nextLine());
String address = sc.nextLine();
Upvotes: 0
Reputation: 68715
Your program will read all the three inputs. But i believe you are hitting enter key after doing the input for phone number. Try doing the input as mentioned here:
myName
100000 myAddress
sc.nextLong() method will accept the long value and then sc.nextLine() will wait for input on the same line. And if you press enter after entering the long value, sc.nextLine() will simply read empty.
Upvotes: 0