To read space-separated integers in Java, you can use the Scanner
class, which provides a convenient way to read input from the console, a file, or any other input source.
Here is an example of how you can use the Scanner
class to read space-separated integers in Java:
import java.util.Scanner; public class IntegerReader { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter integers: "); String input = scanner.nextLine(); String[] tokens = input.split(" "); for (String token : tokens) { int number = Integer.parseInt(token); System.out.println(number); } scanner.close(); } }
In this example, the main
method starts by creating a Scanner
object that reads from the console using the System.in
object. It then prompts the user to enter the integers and reads the input using the nextLine
method.
The main
method then splits the input string into an array of tokens using the split
method and stores the array in a variable named tokens
.
The main
method then iterates over the array of tokens using a for-each loop and converts each token to an integer using the parseInt
method of the Integer
class. It then prints the integer to the console using the System.out.println
method.
Finally, the Scanner
object is closed using the close
method.
This code will read space-separated integers from the console and print each integer to the console. You can modify the code to perform other operations with the integers, such as sorting them or searching for specific integers.
Keep in mind that this is just one way to read space-separated integers in Java. You can use different techniques and libraries to achieve the same result, such as using the BufferedReader
class or the FileReader
class. You may also need to handle exceptions and other error conditions.