0

I want to print out "ENTER" When I typing enter +if I press Control C to exit.

package project;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
            
            
        while(true) {
        String t = sc.nextLine();
        System.out.println(t);
            
        if(t.equals('enter')) { 
            System.out.println("\"ENTER\"");
            }
            
            
            
        if(t.equals('ctrl+C')) {
            break;}
        }
        
            sc.close();
            
    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • `nextLine()` only returns if enter was pressed, so you don't need to check for that. Ctrl+c is worse since it's not something that ends up in `System.in` and thus cannot be detected in your Scanner. – f1sh Mar 14 '23 at 09:53
  • 1
    Does this answer your question? [Catching Ctrl+C in Java](https://stackoverflow.com/questions/1611931/catching-ctrlc-in-java) – f1sh Mar 14 '23 at 09:55
  • @f1sh That question focuses only on one control character and thus cannot answer this question. – Queeg Mar 14 '23 at 09:56

1 Answers1

0

System.in is a stream you can read bytes from. The enter key usually delivers a linefeed character (0x0A) on Un*x-ish systems and and carriage return/linefeed characters on Windows (0x0D 0x0A).

Using the scanner.nextLine() reads all characters up to the linefeed/cariage return. These characters may not be delivered in the result as they get already stripped off.

So after having read the next line you can be sure there was some ENTER involved.

Queeg
  • 7,748
  • 1
  • 16
  • 42