To scan a string in Java, you can use the Scanner
class. The Scanner
class is a utility class that allows you to read input from various sources, such as the keyboard, a file, or a network connection.
To use the Scanner
class to scan a string, you can create a Scanner
object and pass the string as an argument to the constructor. Here is an example:
String str = "Hello, World!"; Scanner scanner = new Scanner(str);
Once you have created the Scanner
object, you can use various methods to read the input. For example, you can use the nextLine
method to read the entire line as a string:
String line = scanner.nextLine();
Or, you can use the next
method to read a single word:
String word = scanner.next();
You can also use the hasNext
method to check if there is more input available, and the close
method to close the scanner when you are finished with it.
Here is an example of a complete program that uses the Scanner
class to scan a string and print each word on a separate line:
import java.util.Scanner; public class Main { public static void main(String[] args) { String str = "Hello, World!"; Scanner scanner = new Scanner(str); while (scanner.hasNext()) { String word = scanner.next(); System.out.println(word); } scanner.close(); } }