Home » Java programming language

Different ways to take input from the user in Java (Examples)

Java User input: Here, we are going to learn about the various ways to take input from the user in Java.
Submitted by Preeti Jain, on July 01, 2019

Here is the some of the popular ways to take input from the user in Java,

  1. By Using BufferedReader Class
  2. By Using Console Class
  3. By Using Scanner Class

1) Example of user input using BufferedReader

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {

        // Create an object of BufferedReader rdr
        BufferedReader rdr =
            new BufferedReader(new InputStreamReader(System.in));

        // Display message for user
        System.out.print("Enter your Job: ");
        // BufferedReader object rdr read input from standard input stream 
        // and wrapped in BufferedReader
        String job = rdr.readLine();
        System.out.println("You are a " + job);
    }
}

Output

Enter your Job: Technical writer
You are a Technical writer

2) Example of user input using Console class

public class Main {
    public static void main(String[] args) {
        // Display message for user
        System.out.print("Enter your Job: ");
        // Using Console class to take input from user
        String job = System.console().readLine();

        System.out.println("You are a " + job);
    }
}

Output

Enter your Job: Technical writer
You are a Technical writer

3) Example of user input using Scanner class

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        // Display message for user
        System.out.print("Enter your name: ");
        String name = input.nextLine();
        System.out.println("My name is " + name);

        // Display message for user
        System.out.print("Enter your MCA percent: ");
        float per = input.nextFloat();
        System.out.println("My percent in MCA is:  " + per);
    }
}

Output

Enter your MCA percent: 98
My percent in MCA is:  98.0





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.