如何做到每次按回车键,都会在 Java 中弹出一个新文本?
How to make it so each time you press the enter key, a new text pops up in Java?
这是我目前的代码,第一次点击回车键时,"Read enter key" 出现。第二次单击回车键时,"Read enter key" 和 "the second hit" 都出现了。我该怎么做才能在我第二次按回车键后只出现 "second hit" ?
import java.util.Scanner;
public class love {
static public void main (String[] args) {
// creation the scanner to look for when the enter key is pressed
try (Scanner scanner = new Scanner(System.in)) {
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
// enter the first text
System.out.println("Read Enter Key");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
// enter the second text
System.out.println("second hit");
} else {
readString = null;
}
}
}
}
}
**Make the following changes in your code.Hope so it works as you wanted.**
import java.util.Scanner;
class Love
{
public static void main (String[] args)
{
// creation the scanner to look for when the enter key is pressed
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
System.out.println(readString);
if (readString.isEmpty())
{
System.out.println("Read Enter Key");
}
if (scanner.hasNextLine())
{
readString = scanner.nextLine();
System.out.println("second hit");
readString=null;
}
}
}
}
这是我目前的代码,第一次点击回车键时,"Read enter key" 出现。第二次单击回车键时,"Read enter key" 和 "the second hit" 都出现了。我该怎么做才能在我第二次按回车键后只出现 "second hit" ?
import java.util.Scanner;
public class love {
static public void main (String[] args) {
// creation the scanner to look for when the enter key is pressed
try (Scanner scanner = new Scanner(System.in)) {
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
if (readString.isEmpty()) {
// enter the first text
System.out.println("Read Enter Key");
}
if (scanner.hasNextLine()) {
readString = scanner.nextLine();
// enter the second text
System.out.println("second hit");
} else {
readString = null;
}
}
}
}
}
**Make the following changes in your code.Hope so it works as you wanted.**
import java.util.Scanner;
class Love
{
public static void main (String[] args)
{
// creation the scanner to look for when the enter key is pressed
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
System.out.println(readString);
if (readString.isEmpty())
{
System.out.println("Read Enter Key");
}
if (scanner.hasNextLine())
{
readString = scanner.nextLine();
System.out.println("second hit");
readString=null;
}
}
}
}