Reputation: 33
I am trying to understand Scanner class in java, out of some examples trying I am in ambiguity with below two programs, where I dont see any difference logically but output is telling that there is something I am missing. Please help me on this
public static void main(String args[]) {
Scanner scanner1=new Scanner(System.in);
String s=scanner1.nextLine();
scanner1.close();
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line
System.out.println("" + scanner.nextLine());
// check if there is a next line again
System.out.println("" + scanner.hasNextLine());
// print the next line
System.out.println("" + scanner.nextLine());
// check if there is a next line again
System.out.println("" + scanner.hasNextLine());
// close the scanner
scanner.close();
}
above program is printing below output
Hello World! \n 3+3.0=6
Hello World! \n 3+3.0=6
false
While the below program which i dont see any difference with above is showing the different output
public static void main(String[] args) {
String s="Hello World! \n 3 + 3.0 = 6";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line
System.out.println("" + scanner.nextLine());
// check if there is a next line again
System.out.println("" + scanner.hasNextLine());
// print the next line
System.out.println("" + scanner.nextLine());
// check if there is a next line again
System.out.println("" + scanner.hasNextLine());
// close the scanner
scanner.close();
}
output of above program is
Hello World!
true
3 + 3.0 = 6
false
Upvotes: 2
Views: 245
Reputation: 1011
If \n is written in the file you can't use nextLine() [with two backslash it will give you java.util.NoSuchElementException]because there is not \n (end of line) but instead there is \n (two backslash). To read the file and replace the \n in the text with actual EOL,you can use the sc.useDelimiter("\\n") for new line but then it might break the functionalities of scanner's some method.
Scanner s = new Scanner("Hello World! \\n 3 + 3.0 = 6");
s.useDelimiter("\\\\n");
System.out.println(s.next());
System.out.println(s.next());
will give you the output like
Hello World!
3 + 3.0 = 6
Upvotes: 2
Reputation: 393811
I'm assuming that in the first snippet you are typing Hello World! \n 3+3.0=6
to the standard input. "\n" is not parsed as new line in this case (it is parsed as the character '\' followed by the character 'n'). You have to actually press the enter button after typing "Hello World! " in order for the scanner to split the input into two lines.
On the other hand, when the Scanner takes the input from a String, "\n" is treated as a new line character.
Oh, and it does appear you have a typo in your first snippet. I was assuming you are using a Scanner that takes its input from System.in
(you probably got the code of the two snippets mixed up).
Upvotes: 0