It allows reading input from the keyboard.
java.util package is used in scanner class
e.g:
Example 1:
java.util package is used in scanner class
e.g:
import java.util.*;
or
import java.util.Scanner;
System.in(keyboard): It
represents the standard input stream
System.out(monitor): It represents the standard output stream
Methods of scanner class:
Methods of scanner class:
There are different types of predefined methods which are used in Scanner class like
public byte nextByte()
public byte nextByte()
It is used to read a value of type byte
public
short nextShort()
It is
used to read a value of type short
public
long nextLong()
It is used to read a value of type long
public
int nextInt()
It is
used to read a value of type int
public
float nextFloat()
It is
used to read a value of type float
public
double nextDouble()
It is
used to read a value of type double
public String next()
It returns the next token/word in the input as a string.
public String nextLine()
It is used to read strings.
charAt(0)
It returns the first character in that string.
It returns the first character in that string.
next().charAt(0)
It is used to read a single characterExample 1:
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input first number:\n
");
int num1 = sc.nextInt();
System.out.print("Input second number:\n
");
int num2 = sc.nextInt();
System.out.println("sum is:"+ (num1 +
num2));
}
}
Output:
Input first number:
12
Input second number:
13
sum is:25
Example 2:
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name \n");
String name = sc.next();
System.out.print("Enter Age \n");
int age = sc.nextInt();
System.out.print("Enter
Gender(M OR F) \n");
char gender= sc.next().charAt(0);
System.out.print("Enter
Mark \n");
double marks = sc.nextDouble();
System.out.println("Student information:\n"+"name
:"+name+"\nage:"+age+"\ngender:"+ gender+"\nmarks"+marks);
}
}
Output:
Enter Name
Dev
Enter Age
25
Enter Gender(M OR F)
M
Enter Mark
67
Student information:
Name:Dev
Age:25
Gender:M
Marks:67
No comments:
Post a Comment