0% found this document useful (0 votes)
8 views15 pages

module3

The document explains how to accept input from the keyboard in Java using the Scanner class from the java.util package. It details the creation of a Scanner object, methods for reading different types of input (like nextLine() for strings and nextInt() for integers), and provides examples of using these methods. Additionally, it covers output methods in Java and the differences between print(), println(), and printf().

Uploaded by

mrpctechnologies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

module3

The document explains how to accept input from the keyboard in Java using the Scanner class from the java.util package. It details the creation of a Scanner object, methods for reading different types of input (like nextLine() for strings and nextInt() for integers), and provides examples of using these methods. Additionally, it covers output methods in Java and the differences between print(), println(), and printf().

Uploaded by

mrpctechnologies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

ACCEPTING INPUT FROM THE KEYBOARD

In Java, there are many ways to read strings from input. The simplest one is to make use of
the class Scanner, which is part of the java.util library and has been newly introduced in
Java 5.0. Using this class, we can create an object to read input from the standard input
channel System.in (typically, the keyboard), as follows:

Scanner scanner = new Scanner(System.in);


Then, we can use the nextLine() method of the Scanner class to get from standard input the
next line (a sequence of characters delimited by a newline character), according to the
following schema:
import java.util.Scanner;

public class KeyboardInput {


public static void main (String[] args) {
...
Scanner scanner = new Scanner(System.in);
String inputString = scanner.nextLine();
...
System.out.println(inputString);
...
}
}

 import java.util.Scanner; - imports the class Scanner from the library java.util
 Scanner scanner = new Scanner(System.in); - creates a new Scanner object, that is
connected to standard input (the keyboard)
 String inputString = scanner.nextLine();
1. temporarily suspends the execution of the program, waiting for input from the
keyboard;
2. the input is accepted as soon as the user digits a carriage return;
3. (a reference to) the string entered by the user (up to the first newline) is
returned by the nextLine() method;
4. (the reference to) the string is assigned to the variable inputString.

We can also read in a single word (i.e., a sequence of characters delimited by a whitespace
character) by making use of the next() method of the Scanner class. We will see later that
the Scanner class is also equipped with other methods to directly read various types of
numbers from standard input.

https://www.inf.unibz.it/~calvanese/teaching/06-07-ip/lecture-notes/uni02/node33.html

 SCANNER CLASS

Java Scanner

Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java,
we can get input from the user in primitive types such as int, long, double, byte, float, short,
etc.

The Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.

Java Scanner Class Declaration

1. public final class Scanner


2. extends Object
3. implements Iterator<String>

How to get Java Scanner

To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class. For Example:

1. Scanner in = new Scanner(System.in);

To get the instance of Java Scanner which parses the strings, we need to pass the strings in
the constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");

Java Scanner Class Constructors

SN Constructor Description

1) Scanner(File source) It constructs a new Scanner that


produces values scanned from the
specified file.

2) Scanner(File source, String It constructs a new Scanner that


charsetName) produces values scanned from the
specified file.

3) Scanner(InputStream source) It constructs a new Scanner that


produces values scanned from the
specified input stream.

4) Scanner(InputStream source, String It constructs a new Scanner that


charsetName) produces values scanned from the
specified input stream.

5) Scanner(Readable source) It constructs a new Scanner that


produces values scanned from the
specified source.

6) Scanner(String source) It constructs a new Scanner that


produces values scanned from the
specified string.

7) Scanner(ReadableByteChannel source) It constructs a new Scanner that


produces values scanned from the
specified channel.

8) Scanner(ReadableByteChannel source, It constructs a new Scanner that


String charsetName) produces values scanned from the
specified channel.

9) Scanner(Path source) It constructs a new Scanner that


produces values scanned from the
specified file.

10 Scanner(Path source, String It constructs a new Scanner that


) charsetName) produces values scanned from the
specified file.

Java Scanner Class Methods

The following are the list of Scanner methods:


SN Modifier & Type Method Description

1) void close() It is used to close this


scanner.

2) pattern delimiter() It is used to get the Pattern


which the Scanner class is
currently using to match
delimiters.

3) Stream<MatchResult> findAll() It is used to find a stream


of match results that match
the provided pattern string.

4) String findInLine() It is used to find the next


occurrence of a pattern
constructed from the
specified string, ignoring
delimiters.

5) string findWithinHorizon() It is used to find the next


occurrence of a pattern
constructed from the
specified string, ignoring
delimiters.

6) boolean hasNext() It returns true if this


scanner has another token
in its input.

7) boolean hasNextBigDecimal() It is used to check if the


next token in this scanner's
input can be interpreted as
a BigDecimal using the
nextBigDecimal() method
or not.
8) boolean hasNextBigInteger() It is used to check if the
next token in this scanner's
input can be interpreted as
a BigDecimal using the
nextBigDecimal() method
or not.

9) boolean hasNextBoolean() It is used to check if the


next token in this scanner's
input can be interpreted as
a Boolean using the
nextBoolean() method or
not.

10 boolean hasNextByte() It is used to check if the


) next token in this scanner's
input can be interpreted as
a Byte using the
nextBigDecimal() method
or not.

11 boolean hasNextDouble() It is used to check if the


) next token in this scanner's
input can be interpreted as
a BigDecimal using the
nextByte() method or not.

12 boolean hasNextFloat() It is used to check if the


) next token in this scanner's
input can be interpreted as
a Float using the
nextFloat() method or not.

13 boolean hasNextInt() It is used to check if the


) next token in this scanner's
input can be interpreted as
an int using the nextInt()
method or not.
14 boolean hasNextLine() It is used to check if there
) is another line in the input
of this scanner or not.

15 boolean hasNextLong() It is used to check if the


) next token in this scanner's
input can be interpreted as
a Long using the
nextLong() method or not.

16 boolean hasNextShort() It is used to check if the


) next token in this scanner's
input can be interpreted as
a Short using the
nextShort() method or not.

17 IOException ioException() It is used to get the


) IOException last thrown
by this Scanner's readable.

18 Locale locale() It is used to get a Locale of


) the Scanner class.

19 MatchResult match() It is used to get the match


) result of the last scanning
operation performed by
this scanner.

20 String next() It is used to get the next


) complete token from the
scanner which is in use.

21 BigDecimal nextBigDecimal() It scans the next token of


) the input as a BigDecimal.

22 BigInteger nextBigInteger() It scans the next token of


) the input as a BigInteger.
23 boolean nextBoolean() It scans the next token of
) the input into a boolean
value and returns that
value.

24 byte nextByte() It scans the next token of


) the input as a byte.

25 double nextDouble() It scans the next token of


) the input as a double.

26 float nextFloat() It scans the next token of


) the input as a float.

27 int nextInt() It scans the next token of


) the input as an Int.

28 String nextLine() It is used to get the input


) string that was skipped of
the Scanner object.

29 long nextLong() It scans the next token of


) the input as a long.

30 short nextShort() It scans the next token of


) the input as a short.

31 int radix() It is used to get the default


) radix of the Scanner use.

32 void remove() It is used when remove


) operation is not supported
by this implementation of
Iterator.

33 Scanner reset() It is used to reset the


) Scanner which is in use.
34 Scanner skip() It skips input that matches
) the specified pattern,
ignoring delimiters

35 Stream<String> tokens() It is used to get a stream of


) delimiter-separated tokens
from the Scanner object
which is in use.

36 String toString() It is used to get the string


) representation of Scanner
using.

37 Scanner useDelimiter() It is used to set the


) delimiting pattern of the
Scanner which is in use to
the specified pattern.

38 Scanner useLocale() It is used to sets this


) scanner's locale object to
the specified locale.

39 Scanner useRadix() It is used to set the default


) radix of the Scanner which
is in use to the specified
radix.

Example 1

Let's see a simple example of Java Scanner where we are getting a single input from the user.
Here, we are asking for a string through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }

Output:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal

https://www.javatpoint.com/Scanner-class

 DISPLAYING OUTPUT

java Basic Input and Output

In this tutorial, you will learn simple ways to display output to users and take input from
users in Java.

Java Output

In Java, you can simply use

System.out.println(); or

System.out.print(); or

System.out.printf();

to send output to standard output (screen).

Here,

 System is a class
 out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class, public, and static in later
chapters.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {

System.out.println("Java programming is interesting.");


}
}

Output:

Java programming is interesting.

Here, we have used the println() method to display the string.

Difference between println(), print() and printf()

 print() - It prints string inside the quotes.


 println() - It prints string inside the quotes similar like print() method. Then the cursor moves
to the beginning of the next line.
 printf() - Tt provides string formatting (similar to printf in C/C++ programming).

Example: print() and println()

class Output {
public static void main(String[] args) {

System.out.println("1. println ");


System.out.println("2. println ");

System.out.print("1. print ");


System.out.print("2. print");
}
}

Output:

1. println
2. println
1. print 2. print

In the above example, we have shown the working of the print() and printf() methods. To
learn about the printf() method, visit Java printf().

Example: Printing Variables and Literals

class Variables {
public static void main(String[] args) {

Double number = -10.6;

System.out.println(5);
System.out.println(number);
}
}

When you run the program, the output will be:

5
-10.6

Here, you can see that we have not used the quotation marks. It is because to display integers,
variables and so on, we don't use quotation marks.
Example: Print Concatenated Strings

class PrintVariables {
public static void main(String[] args) {

Double number = -10.6;

System.out.println("I am " + "awesome.");


System.out.println("Number = " + number);
}
}

Output:

I am awesome.
Number = -10.6

In the above example, notice the line,

System.out.println("I am " + "awesome.");

Here, we have used the + operator to concatenate (join) the two strings: "I am
" and "awesome.".
And also, the line,

System.out.println("Number = " + number);

Here, first the value of variable number is evaluated. Then, the value is concatenated to the
string: "Number = ".

Java Input

Java provides different ways to get input from the user. However, in this tutorial, you will
learn to get input from user using the object of Scanner class.
In order to use the object of Scanner, we need to import java.util.Scanner package.
import java.util.Scanner;

To learn more about importing packages in Java, visit Java Import Packages.
Then, we need to create an object of the Scanner class. We can use the object to take input
from the user.

// create an object of Scanner


Scanner input = new Scanner(System.in);

// take input from the user


int number = input.nextInt();

Example: Get Integer Input From the User

import java.util.Scanner;

class Input {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = input.nextInt();
System.out.println("You entered " + number);

// closing the scanner object


input.close();
}
}

Output:

Enter an integer: 23
You entered 23
In the above example, we have created an object named input of the Scanner class. We then
call the nextInt() method of the Scanner class to get an integer input from the user.
Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next() methods to
get long, float, double, and string input respectively from the user.
Note: We have used the close() method to close the object. It is recommended to close the
scanner object once the input is taken.

Example: Get float, double and String Input

import java.util.Scanner;

class Input {
public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Getting float input


System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);

// Getting double input


System.out.print("Enter double: ");
double myDouble = input.nextDouble();
System.out.println("Double entered = " + myDouble);

// Getting String input


System.out.print("Enter text: ");
String myString = input.next();
System.out.println("Text entered = " + myString);
}
}

Output:

Enter float: 2.343


Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!

https://www.programiz.com/java-programming/basic-input-output

You might also like