0

Im looking for a form to make Scanner to stop reading when you push the first time (so, if I press the key K automatically the program considerer that I press the Intro key, so it stop to recognise inputs, save the K and keep going with the program).

Im using char key= sc.next().charAt(0); in a beginning, but dont know how to make it stop without pushing Intro

Thanks in advance!

2 Answers2

1

If you want to stop accepting after a single particular character you should read the user's input character by character. Try scanning based on a Pattern of one single character or using the Console class.

Scanner scanner = new Scanner(System.in);
Pattern oneChar = new Pattern(".{1}");
// make sure DOTALL is true so you capture the Enter key
String input = scanner.next(oneChar);
StringBuilder allChars = new StringBuilder();

// while input is not the Enter key {
    if (input.equals("K")) {
        // break out of here
    } else {
        // add the char to allChars and wait for the next char
    }
    input = scanner.next(oneChar);
}
// the Enter key or "K" was pressed - process 'allChars'
Paul MacGuiheen
  • 628
  • 5
  • 17
0

Unfortunately, Java doesn't support non blocking console and hence, you can't read user's input character by character (read this SO answer for more details).

However, what you can do is, you can ask the user to enter the whole line and process each character of it until Intro is encountered, below is an example:

System.out.println("Enter the input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringBuilder processedChars = new StringBuilder();
for(int i=0 ; i<input.length() ; i++){
    char c = input.charAt(i);
    if(c == 'K' || c == 'k'){
        break;
    }else{
        processedChars.append(c);
    }
}
System.out.println(processedChars.toString());
Community
  • 1
  • 1
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Is sad to hear that; what I wanted is the same you do there, but automatically to avoid the "extra key push". Perhaps someday we can have that option – Frikilangelo Mar 29 '16 at 06:52