scanner in java integer code example
Example 1: scanner in java
import java.util.Scanner; //Import Scanner in java
class classname{
public void methodname(){
Scanner s_name = new Scanner(System.in); //Scanner declaration
//Use Scanner object to take input
int val1 = s_name.nextInt(); //int
float val2 = s_name.nextFloat(); //float
double val3 = s_name.nextDouble(); //double
string name = s_name.nextLine(); //string
char ch = s_name.nextLine().charAt(0); //character
}}
Example 2: how to use scanners in java
import java.util.Scanner;
Public class Scanner {
Public static void main(String[] args) {
// Scanner *scanner name here* = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Type anything and the scanner will take that input and print it");
String next = scan.next();
System.out.println(next);
}
}
Example 3: read integer input java
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
Example 4: read int from keyboard java
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
/*Is better to create another instance of Scanner if you have to use both nextline
and nextInt because they can conflict each other
*/
}