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
I tried following code but this is not stopping as there is no break condition so it always waiting for input , may be you could add a condition for break
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s="";
while(scan.hasNext())
{
s=scan.nextLine();
}
System.out.println("String: " +s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
next()
will only store the input up to the first token. if there are two words "Hi there" it means there are two tokens separated by space (delimiter). Every time you call the next() method it reads only one token.
if input is "Hi there !"
Scanner scan = new Scanner(System.in);
String str = scan.next()
System.out.println(str);
Output
Hi
So if you both the words you need to call next()
again to get the next token which is inefficient for longer string input
nextLine()
on the other hand grabs the entire line that the user enters even with spaces
Scanner scan = new Scanner(System.in);
String str = scan.nextLine()
System.out.println(str);
Output
Hi there !
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
Instead of using System.in
and System.out
directly, use the Console class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:
String address = System.console().readLine("Enter your Address: ");
next() is read until the space of the encounter, and the nextLine() is read to the end of the line.
Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();
String s="Hi";
String s1="";
//For Reading Line by hasNext() of scanner
while(scan.hasNext()){
s1 = scan.nextLine();
}
System.out.println(s+s1);
/*This Worked Fine for me for reading Entire Line using Scanner*/