-1

I was Trying to find a way to check the user input while typing so if they typed a special character ("#") the execution will terminate immediately without pressing Enter (using Java Scanner) , I tried this code but it needs to press enter each time .I couldn't find a way to do that I'd appreciate any help.

import java.util.Scanner;
public class test{

    public static void main(String[] args) {

            Scanner scan =new Scanner(System.in);

            while (true) {
                String input =scan.next();
                if (input.equals("#")) {
                    break;
                }

                System.out.println("yes");


            }
    }
}
Rd_x
  • 13
  • 5

3 Answers3

0

you may read byte by byte and stop read when entering the special character.

For example:

char key;
do{
   key = scanner.nextByte() // be careful with encoding. utf-8 may use 2 bytes per symbol
   //do stuff
}while(key != '#')
andermirik
  • 46
  • 4
0

Try reading the input char by char. Something like this:

Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
if(c == '#')
{
    // terminate execution
}
0

you can try this. System.in.read() will read the entered character. If the entered character is # you can terminate the execution. If the user has entered the enter key you can use the whitespace() method to break out of the loop.

char arr[] = new char[100];
for(int i=0;i<100;i++) {
    arr[i] = (char)System.in.read();
    if (arr[i].equals("#")) {
        System.exit(1);
}
if(arr[i].isWhitespace()){
break;
}

}
  • It gives compiletion errors (can't invoke equlas(Sting) on the primitive type char)& (can't invoke isWhitespace() on the primitive type char). – Rd_x Apr 19 '20 at 15:32
  • I tried to change .equlas to == and isWhitespace to ==' ' . It worked but it needs to press enter :( – Rd_x Apr 19 '20 at 15:33
  • Yes System.in.read() method reads the character even if enter is not pressed. Once the user presses enter key it can be detected with whitespace – Athish Murugan Apr 19 '20 at 15:43