User Input in Java

User Input in Java

User Input in Java


The Scanner class is used to get user input, and it is found in the java.util package

import java.util.Scanner;                                    // importing Scanner

class User_Input {

public static void main(String[] args) {

nextBoolean()  ➔  Reads a boolean value from the user.

nextByte()     ➔   Reads a byte value from the user.

nextDouble()   ➔  Reads a double value from the user.

nextFloat()      Reads a float value from the user.

nextInt()         Reads a integer value from the user.

nextLine()     ➔  Reads a String value from the user.

nextLong()     ➔  Reads a long value from the user.

nextShort()      Reads a short value from the user.


Example : Program to print percentage of marks in 5 subjects.

Scanner var = new Scanner(System.in);

System.out.print("Enter Your marks in Physics : ");

int physics = var.nextInt();

System.out.print("Enter Your marks in Math : ");

int math = var.nextInt();

System.out.print("Enter Your marks in Chemistry : ");

int chemistry = var.nextInt();

System.out.print("Enter Your marks in English : ");

int english = var.nextInt();

System.out.print("Enter Your marks in CS : ");

int cs = var.nextInt();

int percentage = (physics + math + chemistry + english + cs)/5;

System.out.println("Your Percentage is : " +percentage+"%");


Example : Taking String i.e. Name as User input

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

String user_name = var.nextLine();

}}





Disqus Comments