How does this program actually work...?
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
use a temporary scan.nextLine();
this will consume the \n character
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
import java.util.*;
public class ScannerExample {
public static void main(String args[]) {
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);
System.out.println("enter a string");
s = scan.next();
System.out.println("string is=" + s);
}
}
This is a common misunderstanding which leads to confusion if you use the same Scanner for nextLine() right after you used nextInt().
You can either fix the cursor jumping to the next Line by yourself or just use a different scanner for your Integers.
OPTION A: use 2 different scanners
import java.util.Scanner;
class string
{
public static void main(String a[]){
int a;
String s;
Scanner intscan =new Scanner(System.in);
System.out.println("enter a no");
a=intscan.nextInt();
System.out.println("no is ="+a);
Scanner textscan=new Scanner(System.in);
System.out.println("enter a string");
s=textscan.nextLine();
System.out.println("string is="+s);
}
}
OPTION B: just jump to the next Line
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);
}
}
.nextInt()
gets the next int
, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.
You can insert another .nextLine()
after you get the int
to fix this. Or (I prefer this way), read the int
in as a string
, and parse it to an int
.
Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......