Search code examples
javakeyboardkeyjava.util.scanner

How to make it so each time you press the enter key, a new text pops up in Java?


Here is the code I have so far, the first time I click the enter key, "Read enter key" appears. The second time I click the enter key, both "Read enter key" and "the second hit" appear. How do I go about making it so only "second hit" appears after the second time I press the enter key?

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;
            }
        }

    }

}

}

Solution

  • **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;
                     } 
    
    
              }
    
         }
    
     }