December 27, 2020 [Java] How to get / output standard input deals with standard input, but I didn't know the existence of hasNext at that time, so I will summarize it briefly today.
Used for standard output and reading the contents of a file.
When creating an instance of the Scannner class, set System.in
for standard output and a file object for reading a file.
Basic writing
Scanner variable= new Scanner(value);
It is a process to determine whether iterative processing can still be performed when a file is read by the Scannner class. Gets the values in order from the front, and returns true if the value can still be obtained, false if no more values can be obtained. If you don't know how many to enter, you can't receive by specifying the number of times in the for statement, so use it in such cases.
The next function is used in combination with the hasNext function. The next function gets the values in order from the front, and the hasNext function advances the place to judge whether there is a value.
Basic writing
while(Object you want to repeat.hasNext()) {
String variable=Object you want to repeat.next();
Subsequent processing;
}
A program that reads the contents of a file
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("sample.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String str = scanner.next();
System.out.println(str);
}
scanner.close();
}
}
A program that reverses and displays characters entered from the keyboard
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
while (s.hasNext()) {
String value = s.next();
System.out.println(new StringBuilder(value).reverse());
}
} finally {
s.close();
}
}
}
How to use the HasNext method of Scanner Active engineers explain the hasNext function of Java's Scanner class [for beginners] Get from keyboard input! How to use Scanner class in Java [For beginners]
Recommended Posts