Wednesday 14 February 2018

Scanner Class In Java

It allows reading input from the keyboard.
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:
There are different types of predefined methods which are used in Scanner class like

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.
next().charAt(0)
It is used to read a single character

Example 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

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...