next up previous
Next: Exercise: the class BankAccount Up: Unit 04 Previous: Writing of numbers of

Reading of numbers using the Scanner class

Starting with Java version 5.0, we have an alternative way to read numbers from an input channel, namely by making use of the Scanner class. We first create a Scanner object that reads from the input channel. Then we can directly read a value of a primitive numeric data type by invoking on the Scanner object one of the methods nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), and nextDouble().

Example:

Scanner scanner = new Scanner(System.in);
...
System.out.println("Insert a byte");
byte b = scanner.nextByte();
System.out.println("Insert a short");
short s = scanner.nextShort();
System.out.println("Insert an int");
int i = scanner.nextInt();
System.out.println("Insert a long");
long l = scanner.nextLong();
System.out.println("Insert a float");
float f = scanner.nextFloat();
System.out.println("Insert a double");
double d = scanner.nextDouble();


next up previous
Next: Exercise: the class BankAccount Up: Unit 04 Previous: Writing of numbers of