In this post, we are going to learn how to get input from the User. Then will do some programming exercises to enhance our programming knowledge.
There are Different - Different ways to get an input from the console -- Go HERE.
but right now will stick to Scanner Class, because it is the most common and easiest way.
but right now will stick to Scanner Class, because it is the most common and easiest way.
using Scanner Class will get the input from the user,
- present in java.util package
- which allows the user to read values of various types.
- There are far more methods in class Scanner than you will need in this course.
Syntax:-
Scanner - is a class in java.
sc - is an object of Scanner class (you can give any name).
new - is an operator which is used to make an object of a class.
Scanner() - is a constructor in Scanner Class(Don't Worry will talk it later).
System - is a class in java, represents your computer system (helps to provide us system-level methods)
in - stands for input (s).
System.in - getting input from the system and it passes as an argument to Scanner Constructor.(Don't Worry, if you are unable to get it).
# Scanner Class has Somes Methods to get Different kinds of values from the console.
- For different types of values different, types of methods are available.
- For int type nextInt() method is used,
- For double type nextDouble() method used,
- All the methods called by using Scanner Object (sc.method name).
- for example (String value) -- we have to use next() or nextLine().
String s; // variable -- where data store
Scanner sc = new Scanner(System,in); // creating Scanner class object
s = sc.next(); // getting input from user and assgin it to "s" variable
sc.close(); // good practic to close resourses.
Question -- WAP to Take two number from the user and return its sum.
Answer --
# Code
package scannerClass;
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st number : ");
int num1 =sc.nextInt();
System.out.println("Enter 2nd number : ");
int num2 = sc.nextInt();
int add=num1+num2;
System.out.println("Sum = "+add);
}
}
package scannerClass;
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st number : ");
int num1 =sc.nextInt();
System.out.println("Enter 2nd number : ");
int num2 = sc.nextInt();
int add=num1+num2;
System.out.println("Sum = "+add);
}
}