SCANNER
While creating applications or websites using Java, it’s
ultimately necessary to obtain the input data from the user. In such cases,
this scanner functions holds the possible solution.
System.out function prints out the output whereas, System.in function
is used to get the input values. The data type of the variable must necessarily
match the data type of the input value. While using Scanner variable, we
have to import java.util.Scanner library.
Steps to declare an integer using Scanner function
1. 1. Declare a variable to int data type
int x;
2. 2. To obtain the input data from user, System.in function is used along with the new keyword
Scanner input=new Scanner(System.in);
3. 3. Finally, the integer variable declared in Step 1, is assigned with the input using nextInt( ) function.
x x= input.nextInt();
Simple Java code to determine a person is eligible to vote using Scanner function
import java.util.Scanner;
class java {
public static void main(String args[]) {
//Output
System.out.println("enter your age");
//Input
int age;
Scanner input=new Scanner(System.in);
age= input.nextInt();
//Output
System.out.print("You are ");
//Ternary Conditional Statement
String output= age >=18 ? "eligible to vote" : "not eligible to vote";
System.out.print(output);
}
}
To learn the concept of Ternary Conditional Statement,
you can CHECK HERE.
Output
1. 1. Declare a variable to string data type
String x;
2. 2. To obtain the input data from user, System.in function is used along with the new keyword
Scanner input=new Scanner(System.in);
3. 3. Finally, the integer variable declared in Step 1, is assigned with the input using next( ) function.
x= input.next();
For strings, in step 3 we have to use next( ) function
whereas for integer data type, we have to use nextInt( ) function.
Note: Using Next keyword, only a single word can be printed. If you are
interested in printing several words, nextInt( ) function can be used.
Java code to print name using Scanner function
import java.util.Scanner;
class java {
public static void main(String args[]) {
//Output
System.out.println("enter your name");
//Input
String name;
Scanner input=new Scanner(System.in);
//To obtain several strings
name= input.nextLine();
//Output
System.out.print("Have a great day " + name);
}
}
Output
PREVIOUS




2 Comments
Nice
ReplyDeletetHANKS
Delete