How does this program actually work...?
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
You only need to use scan.next()
to read a String
.
Incase you don't want to use nextint, you can also use buffered reader, where using inputstream
and readline
function read the string.
if you don't want to use parser :
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
scan.nextLine(); // This line you have to add (It consumes the \n character)
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is=" + s);
Simple solution to consume the \n character:
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is ="+a);
scan.nextLine();
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is="+s);
}
}
This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:
You can use the next method on the scanner object as
scan.next();
s=scan.nextLine();
It returns input was skipped.
so you might use
s=scan.next();