I am new to Java programming. I was reading about Scanner class and I decided to compile a simple program:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
By using the object obj, I can only read the integer input and doesn't let me read the String input. Why can't we use the same object of Scanner class for taking the input since the only use of object is to call a method like nextLine().
Whereas if I use this code,
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj2.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
Using a different object obj2 for string and obj for integer,I get my desired output. Any help would be appreciated!