How to Read in Integers in Java and Skip the White Spaces
Java includes predefined classes to allow programs to read input in a variety of formats, for any of the primitive types -- for example, "int" and "float." Those classes can automatically eliminate white spaces, such as space characters and carriage returns, that can occur between useful input elements. If the user or another input source includes any number of white space characters, they will be ignored. You can read multiple integers while ignoring white spaces in your Java code.
Instructions
-
-
1
Include the following line at the beginning of your Java code:
import java.util.Scanner;
-
2
Declare variables of primitive type "int" to hold the integers you need to read, as in the following sample code:
int myFirstInt;
int mySecondInt;
-
-
3
Create a Scanner object that will take input from an input stream, as in the following sample code:
Scanner myScanner = new Scanner(System.in);
The example will read from "System.in," the standard input to the Java program, though you can use any stream as the source of your data.
-
4
Read the integers one by one, as in the following sample code:
myFirstInt = myScanner.nextInt();
mySecondInt = myScanner.nextInt();
Any white spaces before the first integer, between the first and second integers, or after the second integer will be skipped; it will not affect the integer values the code reads.
-
1