Taking input using Scanner class

Interactive Input

  • We can take the input from user using two ways

    • Using Scanner class from java.util package

    • Using BufferedReader class from java.io package


Methods of Scanner class

  • String next()

  • int nextInt()

  • double nextDouble()

  • float nextFloat()


Example

WAP to input name and age of a person and check it as valid voter.





WAP to get a name and basic of an employee and print DA based on following rules using ternary operator

60% for basic>=10000

40% for basic>=6000

20% for others


Ternary operator (?:)

It can be understood as short form of if else statements

condition? true part : false part;


Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.*; // This package contains Scanner class

class DAPrint

{

public static void main(String args[])

{

Scanner sc=new Scanner(System.in); // We will make object of Scanner class to take input

System.out.print("Name : ");

String name=sc.next(); // next() function is used to take string as an input


System.out.print("Basic : ");

int basic=sc.nextInt(); // nextInt() function is used to take integer as an input


double da=basic>=10000?0.6*basic : basic>=6000?0.4*basic : 0.2*basic;

System.out.println("Dear "+name+" your DA is "+da);

}

}


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner; //Instead of importing package we are importing Scanner class only

class PowerTest

{

public static void main(String... args) // Note ... after String

{

Scanner sc=new Scanner(System.in);

System.out.print("Number : ");

double num=sc.nextDouble(); // nextDouble() takes double as input


System.out.print("Power : ");

double p=sc.nextDouble(); //non-static or instance method


double result=Math.pow(num,p); //static or class method

System.out.printf("%.2f to the power %.2f is %.2f",num,p,result);

}

}


Using import static keyword

  • Used to import static members of a class

import static java.lang.System.*;

import static java.lang.Math.*;

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Scanner;

import static java.lang.System.*;

import static java.lang.Math.*;

class ImportStaticTest

{

public static void main(String... args)

{

Scanner sc=new Scanner(in);

out.print("Number : ");

double num=sc.nextDouble();


out.print("Power : ");

double p=sc.nextDouble();


double result=pow(num,p);

out.printf("%.2f to the power %.2f is %.2f",num,p,result);

}

}