Вы находитесь на странице: 1из 7

Java User Input

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

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scannerclass documentation. In our example, we will use the nextLine() method,
which is used to read Strings:

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter username");

String userName = myObj.nextLine();

System.out.println("Username is: " + userName);

Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:

Method Description

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 int 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

Java Packages & API


A package in Java is used to group related classes. Think of it as a folder in a
file directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

 Built-in Packages
 The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.
 The library contains components for managing input, database
programming, and much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.
 The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
 To use a class or a package from the library, you need to use
the import keyword:

Syntax
import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:

Example
import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of


the java.util package.

To use the Scanner class, create an object of the class and use any of the
available methods found in the Scannerclass documentation. In our example, we
will use the nextLine() method, which is used to read a complete line:

Example

import java.util.Scanner;
class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input

String name = myObj.nextLine();

// Numerical input

int age = myObj.nextInt();

double salary = myObj.nextDouble();

// Output input by user

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

BufferedReader in Java
BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it
can get the efficient reading of characters, arrays, etc. It inherits the reader class and makes the code
efficient since we can read the data line-by-line with the readline() method. There are a few pointers we
have to keep in mind while working with BufferedReader class in Java.

 We may have to specify the buffer size even though the default is large enough for any purpose.
 With each request made of a reader a corresponding, a read request is also made of an
underlying character.
 It is always advised to wrap a BufferedReader class around any reader such as
InputStreamReaders.
 For the programs that use DataInputaStreams for textual input, an appropriate BufferedReader
replaces the DataInputStream to localize it.

BufferedReader Class Declaration


1 public class BufferedReader extends Reader

Java BufferedReader Constructors


Constructor Description
This constructor creates a buffering character-
BufferedReader(Reader reader) input stream that works on a default-size input
buffer.
It uses the specified size for the input buffer for
BufferedReader(Reader reader, int size)
buffering the character-input stream.

Methods And Description


Following are the methods with the description that we have for the Java BufferedReader class.
Method Description
int read() Reads a single character
String readLine() It reads a line of text
Repositions the stream to the position where the
void reset()
mark method was last called
int read(char[]  cb, int off , int len) Reads the characters in a portion of an array
It tests the input stream support for reset and mark
boolean markSupported()
method
It checks whether the input stream is ready for
boolean ready()
reading
long skip(long n) skips the characters
void close() It closes the input stream
void mark(int readAheadLimit) Used to mark the current position in the stream
Example:
import java.io.*;
1 public class Example{
2 public static void main(String args[] throws Exception)
3 {
4 FileReader f = new FileReader("filelocation");
BufferedReader b = new BufferedReader(f);
5
 
6 int i ;
7 while((i = b.read()) != -1){
8 System.out.println((char) i);
9 }
b.close();
10 f.close();
Difference Between Scanner And BufferedReader
BufferedReader Scanner
Synchronous and should be used with multiple Not synchronous and not used with multiple
threads threads
Buffer memory is larger Buffer memory is smaller
Faster than Scanner Slower because it does parsing of the input data
There are a lot of problems with the nextline()
There is no ambiguity related to nextline() method
method.
Uses buffering to read characters from the It is a simple text scanner which parses primitive
character-input stream types and strings

BufferedReader in JDK7 Example


1 import java.io.*;
public class Example{
2
public static void main(String[] args){
3 try( BufferedReader b = new BufferedReader(new fileReader("filename")));
4 {
5 String s;
6 while((s = b.readLine()) != null){
7 System.out.println(s);
}
8 }
9 catch(IOException e)
10 {
11 e.printStackTrace();
}
12 }
13 }
14

Вам также может понравиться