top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Scanner Class in java

Introduction

Scanner class is one of the most talked about topics in Java. It is located in the java.util package and is used to obtain the user input. If you are a programming enthusiast, here is a tutorial on scanner class in Java!

Overview

This tutorial discusses Java scanners, Java scanner class constructors, Java scanner class methods, and much more. Read on to learn more about the scanner class in Java!

Java Scanner Class Declaration

The "scanner" class in Java reads input from various sources, such as the terminal, files, and strings. To use the Scanner class, first, declare an instance of it.

Learn how to declare a scanner object through this example:

import java.util.Scanner;
public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int num = scanner.nextInt();
        System.out.println("You entered: " + num);
        System.out.print("Enter a line of text: ");
        scanner.nextLine(); 
        String str = scanner.nextLine();
        System.out.println("You entered: " + str);
        scanner.close();
    }
}

How to Use Java Scanner?

In Java, you can create a scanner object to read input from various sources. These sources are the console, files, or strings. To specify the source of input, you pass an appropriate input stream or source to the scanner constructor.

For instance, if you want to read input from the console, you can create a scanner object. Then pass the “System.in” input stream to its constructor like this:

Scanner scanner = new Scanner(System.in);

This creates a scanner object named scanner that reads input from the console.

On the other hand, if you want to read input from a string, you can create a scanner object and then pass the string to its constructor like this:

Scanner scanner = new Scanner("Hello, UpGrad!");

This creates a scanner object that parses the string "Hello, UpGrad!". It also allows you to read its contents using the Scanner methods, such as “next()”, “nextInt()”, or “nextLine()”.

You can also create a scanner object to read input from a file or any other input stream. In this case, you would pass the file or stream to the scanner constructor instead of “System.in” or a string.

Java Scanner Class Constructors 

The scanner class provides several constructors. They allow you to create a scanner object to read input from different sources. 

Here are the primary constructors the scanner class provides:

  • Scanner(File source): Creates a scanner object to read input from a file. 

  • Scanner(InputStream source): Creates a scanner object to read input from a byte stream, such as “System.in”.

  • Scanner(String source): Creates a scanner object to read input from a string.

  • Scanner(Readable source): Creates a scanner object to read input from a character stream.

  • Scanner(Path source): Creates a scanner object to read input from a file specified by a Path object.

  • Scanner(File source, String charsetName): Creates a scanner object to read input from a file using the specified character set.

  • Scanner(InputStream source, String charsetName): Creates a scanner object to read input from a byte stream using the specified character set.

  • Scanner(ReadableByteChannel source): Creates a scanner object to read input from a byte channel.

  • Scanner(ReadableByteChannel source, String charsetName): Creates a scanner object to read input from a byte channel using the specified character set.

  • Scanner(Path source, String charsetName): Creates a scanner object to read input from a file specified by a Path object, using the specified character set.

Java Scanner Class Methods

Here is a list of scanner class methods in Java

1. close() - Closes the scanner object and frees any associated system resources.

Scanner scanner = new Scanner(System.in);
scanner.close();

2. hasNext() - Returns true if there is another token in the input.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
    String input = scanner.next();
    System.out.println("Input: " + input);
}

3. hasNextLine() - Returns true if there is another line in the input.

Scanner scanner = new Scanner("Hello,\nworld!");
if (scanner.hasNextLine()) {
    System.out.println("Found next line: " + scanner.nextLine()); // Output: Found next line: Hello,
}

4. next() - Returns the next token in the input as a string.

Scanner scanner = new Scanner("Hello, world!");
String word = scanner.next();
System.out.println(word); // Output: Hello,

5. useLocale(Locale locale): Sets the scanner's locale to the specified locale.

Scanner scanner = new Scanner("1.234,56");
scanner.useLocale(Locale.GERMAN);
double num = scanner.nextDouble(); // num = 1234.56

6. useRadix(int radix): Sets the scanner's radix to the specified radix.

Scanner scanner = new Scanner("FF");
scanner.useRadix(16);
int num = scanner.nextInt(); // num = 255

7. findAll(Pattern pattern): Returns a stream of match results that match the specified regular expression pattern.

Scanner scanner = new Scanner("Hello, World!");
Pattern pattern = Pattern.compile("\\w+");
scanner.findAll(pattern).forEach(matchResult -> System.out.println(matchResult.group()));
// Output: Hello World

8. nextLine()  in Java - Returns the next line of input as a string.

Scanner scanner = new Scanner("Hello,\nworld!");
String line = scanner.nextLine();
System.out.println(line); // Output: Hello,

9. nextDouble() - Returns the next token in the input as a double.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a double value: ");
double input = scanner.nextDouble();
System.out.println("Input value: " + input);

10. nextBoolean() - Returns the next token in the input as a boolean.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a boolean value (true/false): ");
boolean input = scanner.nextBoolean();
System.out.println("Input value: " + input);

11. nextByte() - Returns the next token in the input as a byte.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a byte value: ");
byte input = scanner.nextByte();
System.out.println("Input value: " + input);

12. nextShort() - Returns the next token in the input as a short.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a short value: ");
short num = scanner.nextShort();
System.out.println("The entered short value is " + num);

13. nextLong() - Returns the next token in the input as a long.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a long value: ");
long num = scanner.nextLong();
System.out.println("The entered long value is " + num);

14. nextFloat() - Returns the next token in the input as a float.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a float value: ");
float input = scanner.nextFloat();
System.out.println("Input value: " + input);

15. useDelimiter() - Sets the delimiter for parsing input.

Scanner scanner = new Scanner("Hello,world!");
scanner.useDelimiter(",");
System.out.println(scanner.next()); // Output: Hello
System.out.println(scanner.next()); // Output: world!

16. skip() - Skips input that matches the specified pattern.

Scanner scanner = new Scanner("1,2,3,4,5");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        int num = scanner.nextInt();
        System.out.println(num);
    } else {
        scanner.skip(",");
    }
}

17. findInLine() - Searches for the next occurrence of the specified pattern in the current input line.

Scanner scanner = new Scanner("Hello, 123, world!");
String match = scanner.findInLine("\\d+");
System.out.println(match); // Output: 123
Scanner scanner = new Scanner("The quick brown fox jumps over the lazy dog.");
String result = scanner.findInLine("fox");
System.out.println(result); // Output: fox

18. findWithinHorizon(String pattern, int horizon) - Searches for the next occurrence of the specified pattern in the input up to the specified horizon.

Scanner scanner = new Scanner("abc123def456");
System.out.println(scanner.findWithinHorizon("\\d+", 3));
// Output: null (pattern not found within horizon of 3 characters)

19. hasNextByte(): Returns true if the scanner has another token that is a byte.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextByte()) {
    byte b = scanner.nextByte();
    System.out.println("Byte: " + b);
}

20. match() - Returns the MatchResult for the last match operation.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.next();
scanner.useDelimiter("[aeiou]");
scanner.next();
MatchResult result = scanner.match();
System.out.println("Last match: " + result.group());

21. ioException() - Returns the IOException last thrown by the scanner's underlying Readable.

Scanner scanner = new Scanner(new java.io.FileReader("nonexistent.txt"));
try {
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (java.util.NoSuchElementException e) {
    if (scanner.ioException() == null) {
        System.out.println("Scanner is still valid, but there is no more input");
    } else {
        System.out.println("Scanner is invalid due to an IOException: " + scanner.ioException().getMessage());
    }
}
// Output: Scanner is invalid due to an IOException: null (file not found)

22. delimiter() - Returns the current delimiter pattern as a string.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
    System.out.println("Word: " + scanner.next());
}

23. locale() - Returns the locale associated with the scanner.

Scanner scanner = new Scanner("one deux trois");
scanner.useLocale(Locale.FRENCH);
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}
// Output: one
//         deux
//         trois
System.out.println(scanner.locale());
// Output: fr_FR

24. radix() - Returns the default radix for parsing integers.

Scanner scanner = new Scanner(System.in);
scanner.useRadix(16);
System.out.println("Enter a hexadecimal number: ");
int num = scanner.nextInt();
System.out.println("The entered hexadecimal number is " + num);

25. reset() - Resets the scanner to its initial state.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
    System.out.println("Word: " + scanner.next());
}
scanner.reset();
System.out.println("Original delimiter: " + scanner.delimiter());

26. toString() - Returns a string representation of the scanner object.

Scanner scanner = new Scanner("hello world");
System.out.println(scanner.toString());

27. tokens() - Returns an Iterator over the tokens in the input.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
Iterator<String> tokens = scanner.tokens();
while (tokens.hasNext()) {
    System.out.println("Token: " + tokens.next());
}

28. remove() - Removes the current token from the input.

Scanner scanner = new Scanner("apple orange banana");
while (scanner.hasNext()) {
    String fruit = scanner.next();
    System.out.println(fruit);
    if (fruit.equals("orange")) {
        scanner.remove();
        System.out.println("Removed " + fruit);
    }
}

29. hasNextBigDecimal() - Returns true if there is another token in the input, and it can be interpreted as a BigDecimal.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigDecimal()) {
    BigDecimal decimal = scanner.nextBigDecimal();
    System.out.println("Decimal: " + decimal);
}

30. nextBigDecimal() - Returns the next token in the input as a BigDecimal.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigDecimal value: ");
BigDecimal input = scanner.nextBigDecimal();
System.out.println("Input value: " + input);

31. hasNextBigInteger() - Returns true if there is another token in the input, and it can be interpreted as a BigInteger.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigInteger()) {
    BigInteger integer = scanner.nextBigInteger();
    System.out.println("Integer: " + integer);
}

32. nextBigInteger() - Returns the next token in the input as a BigInteger.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigInteger value: ");
BigInteger input = scanner.nextBigInteger();
System.out.println("Input value: " + input);

33. hasNextBoolean() - Returns true if the scanner has another boolean token.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBoolean()) {
    boolean bool = scanner.nextBoolean();
    System.out.println("Boolean: " + bool);
}

34. hasNextPattern() - Returns true if the next token in the input matches the specified pattern.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.next();
if (scanner.hasNextPattern("\\d+")) {
    int num = scanner.nextInt();
    System.out.println("The entered string is: " + str + " and the number is: " + num);
} else {
    System.out.println("The entered string is: " + str);
}

35. nextInt() in Java- Returns the next token in the input as an int.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("The entered integer is " + num);

36. hasNextDouble() - Returns true if there is another token in the input, and it can be interpreted as a double.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextDouble()) {
    double d = scanner.nextDouble();
    System.out.println("Double: " + d);
}

37. hasNextFloat() - Returns true if another token is in the input and can be interpreted as a float.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextFloat()) {
    float f = scanner.nextFloat();
    System.out.println("Float: " + f);
}

38. hasNextInt() - Returns true if there is another token in the input, and it can be interpreted as an int.

Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
    int i = scanner.nextInt();
    System.out.println("Int: " + i);
}

40. hasNextLong() - Returns true if another token is in the input and can be interpreted as a long.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a long value: ");
if (scanner.hasNextLong()) {
    long value = scanner.nextLong();
    System.out.println("You entered: " + value);
} else {
    System.out.println("Invalid input");
}

Conclusion

Scanner class in Java is as important as the other concepts in Java. You can take up courses curated by online learning platforms like upGrad if you want a firmer grasp of the subject. Hopefully, this tutorial will be helpful to students who want to learn Java. 

FAQs

1. What types of inputs can the scanner read?

The scanner class reads inputs of several types. These are as follows:

  • int 

  • Long

  • Float

  • Double

  • Boolean

  • string.

2. What is the difference between the Scanner class's next() and nextLine() methods in Java?

The next() method reads the next token from the input stream. But the nextLine() method reads the next line. This is their fundamental difference.

3. Can the Scanner class read input from a file?

Yes, you can use the scanner class to read input from a file in Java. You can do this by supplying the file path as a parameter to the scanner class's constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *