To take space-separated input in Java, you can use the Scanner
class and the next
method to read a string from the standard input. The next
method reads a string from the input up to the first whitespace character, and returns the string.
Here's an example of how you can use the Scanner
class and the next
method to read space-separated input in Java:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read the first string from the input String str1 = scanner.next(); // Read the second string from the input String str2 = scanner.next(); // Read the third string from the input String str3 = scanner.next(); System.out.println("Input: " + str1 + " " + str2 + " " + str3); } }
This code will read three strings from the standard input and print them to the console.
You can also use the hasNext
method to check if there is another token in the input before reading it. This can be useful if you want to handle invalid input or if you want to read multiple tokens from the input.
Here's an example of how you can use the hasNext
method to read multiple tokens from the input:
Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { // Read a string from the input String str = scanner.next(); System.out.println("Input: " + str); }
This code will read multiple strings from the standard input and print them to the console until there are no more tokens in the input.
Note that the next
method reads a string from the input up to the first whitespace character, and will not read any leading or trailing whitespace characters. If you want to read a string from the input that may contain whitespace characters, you can use the nextLine
method to read the entire line of input as a string.
Here's an example of how you can use the nextLine
method to read a string from the input:
Scanner scanner = new Scanner(System.in); // Read the entire line of input as a string String input = scanner.nextLine(); System.out.println("Input: " + input);
This code will read an entire line of input as a string and print it to the console.