Scanner hasNextByte() method in Java with Examples
Last Updated :
17 Nov, 2022
The hasNextByte() method of java.util.Scanner class returns true if the next token in this scanner’s input can be assumed as a Byte value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interprets the radix to be default radix and functions accordingly. Syntax:
public boolean hasNextByte(int radix)
or
public boolean hasNextByte()
Parameters: The function accepts a single parameter radix which is not a mandatory one. It specifies the radix used to interpret the token as a Byte value. Return Value: This function returns true if and only if this scanner’s next token is a valid Byte value in the default radix. Exceptions: The function throws IllegalStateException if this scanner is closed. Below programs illustrate the above function: Program 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "gfg 2 geeks!";
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.US);
while (scanner.hasNext()) {
System.out.print("" + scanner.hasNextByte( 3 ));
System.out.print(" -> " + scanner.next() + "\n");
}
scanner.close();
}
}
|
Output:
false -> gfg
true -> 2
false -> geeks!
Program 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
String s = "gfg 2 geeks!";
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.US);
while (scanner.hasNext()) {
System.out.print("" + scanner.hasNextByte());
System.out.print(" -> " + scanner.next() + "\n");
}
scanner.close();
}
}
|
Output:
false -> gfg
true -> 2
false -> geeks!
Program 3: Program to demonstrate exception
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "gfg 2 geeks!";
Scanner scanner = new Scanner(s);
scanner.useLocale(Locale.US);
scanner.close();
while (scanner.hasNext()) {
System.out.print("" + scanner.hasNextByte());
System.out.print(" -> " + scanner.next() + "\n");
}
scanner.close();
}
catch (IllegalStateException e) {
System.out.println("Exception: " + e);
}
}
}
|
Output:
Exception: java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextByte()
Share your thoughts in the comments
Please Login to comment...