16 How to load data dynamically from keyword using java.util.Scanner in Java?

Introduced in jdk 1.5 under the class java.util to overcome drawbacks of command line argument.

If I want to communicate with keyboard then
  Scanner scan = new Scanner( System.in );
In this I had past one parameter System.in which represents keyboard.

Methods Available in java.util.Scanner class for input data through keyboard:

1) next() 
2) nextLine()
3) nextInt()
4) nextByte()
5) nextShort()
6) nextBoolean()
7) nextFloat()
8) nextDouble()
9) nextLong()


For Ex: In this I am reading string and int data from the keyboard.
ScanDemo.java

import java.util.Scanner;
class ScanDemo{

public static void main(String s[] ){

Scanner scan = new Scanner(System.in);

/* In the format of String */
System.out.println("\n Enter some string data: ");
String s1 = scan.nextLine();
System.out.println("\n s1: "+s1);

/* In the format of Int */
System.out.println("\n Enter some integer data: ");
int i=scan.nextInt();
System.out.println("\n i:"+i);
}

}

Output: 


2) For Ex: In this I am reading string first using next() method and then another string using nextLine()  from the keyboard.

ScanDemo.java

import java.util.Scanner;
class ScanDemo{

public static void main(String s[] ){

Scanner scan = new Scanner(System.in);

System.out.println("\n Enter Some String data: ");
String b = scan.next();
System.out.println("\n b: "+b);

System.out.println("\n Enter Some String data: ");
String a = scan.nextLine();
System.out.println("\n a: "+a);

System.out.println("\n\n Program Ends");
}

}


Output: 

In this problem is that all methods except nextLine()  all passing the [enter] to the next statement so in this a is taking [enter] key.

So to overcome this problem we have to take one more nextLine() method observe below:

import java.util.Scanner;
class ScanDemo{

public static void main(String s[] ){

Scanner scan = new Scanner(System.in);

System.out.println("\n Enter Some String data: ");
String b = scan.next();
System.out.println("\n b: "+b);

                 scan.nextLine();
 
System.out.println("\n Enter Some String data: ");
String a = scan.nextLine();
System.out.println("\n a: "+a);

System.out.println("\n\n Program Ends");
}

}


In this the enter is read by the nextLine() method. 
Previous
Next Post »