To clear the buffer in Java and allow the user to input a new string, you can use the nextLine
method of the Scanner
class.
Here's an example of how to clear the buffer and input a new string using the Scanner
class:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // input and print the first string System.out.print("Enter a string: "); String str1 = scanner.nextLine(); System.out.println("You entered: " + str1); // clear the buffer and input the second string scanner.nextLine(); // clear the buffer System.out.print("Enter another string: "); String str2 = scanner.nextLine(); System.out.println("You entered: " + str2); scanner.close(); } }
In this example, the nextLine
method is used to input the first string and store it in the str1
variable. After the first string has been input, the buffer still contains the newline character that was entered after the string. To clear the buffer and allow the user to input a new string, we call the nextLine
method again, but do not store the result. This consumes the newline character in the buffer and allows the user to input a new string.
The nextLine
method reads the entire line of input, including any whitespace characters, until it encounters a newline character. This makes it a convenient way to input and clear the buffer in a single step.
Keep in mind that you should close the Scanner
object when you are done with it, to free up system resources. You can do this by calling the close
method.