Java Scanner - nextByte() Method
The java.util.Scanner.nextByte() method is used to scan the next token of the input as a byte. An invocation of this method of the form nextByte() behaves in exactly the same way as the invocation nextByte(radix), where radix is the default radix of this scanner.
Syntax
public byte nextByte()
Parameters
No parameter is required.
Return Value
Returns the byte scanned from the input.
Exception
- Throws InputMismatchException, if the next token does not match the Byte regular expression, or is out of range.
- Throws NoSuchElementException, if input is exhausted.
- Throws IllegalStateException, if this scanner is closed.
Example:
In the example below, the java.util.Scanner.nextByte() method is used to scan the next token of the input as a byte.
import java.util.*; public class MyClass { public static void main(String[] args) { //String to scan String MyString = "Hello World 10 + 20 = 30.0"; //creating a Scanner Scanner MyScan = new Scanner(MyString); while(MyScan.hasNext()) { //if the next is a byte if(MyScan.hasNextByte()) System.out.println("Byte value is: "+ MyScan.nextByte()); //if the next is not a byte else System.out.println("No Byte Value found: "+ MyScan.next()); } //close the scanner MyScan.close(); } }
The output of the above code will be:
No Byte Value found: Hello No Byte Value found: World Byte value is: 10 No Byte Value found: + Byte value is: 20 No Byte Value found: = No Byte Value found: 30.0
❮ Java.util - Scanner