Now we will move onto next step,previously,we were using Command line arguments and the input to the program was also given by us,but now we are going to show you how to take input from a user.In this method,we need a Scanner class.Scanner class contains an Input function i.e. 'System.in' which will take the user input.For using this Scanner class,we need to import a Java package using the import statement i.e. 'import java.util.Scanner'.You need not to worry about the packages,they will be explained later.
Here is an example of simple code to get input from user:
WAP to get input from user at run time in Java:
import java.util.Scanner; //Scanner class package is imported
public class Even {
public static void main(String args[]) {
System.out.println("Enter first number ");
Scanner input = new Scanner(System.in); //Declaration of Scanner
int a = input.nextInt(); //Input from the user
System.out.println("Enter second number ");
int b = input.nextInt();
if(a>b)
{
System.out.println("A is greater");
}
else
System.out.println("B is greater");
}
}
The output goes here:
Here is an example of simple code to get input from user:
WAP to get input from user at run time in Java:
import java.util.Scanner; //Scanner class package is imported
public class Even {
public static void main(String args[]) {
System.out.println("Enter first number ");
Scanner input = new Scanner(System.in); //Declaration of Scanner
int a = input.nextInt(); //Input from the user
System.out.println("Enter second number ");
int b = input.nextInt();
if(a>b)
{
System.out.println("A is greater");
}
else
System.out.println("B is greater");
}
}
The output goes here:
0 comments: