How to check if the input key has been pressed into a scanner?

advertisements

First, I tried:

while (!(in.nextLine().equals("")))
    arrayList.add(in.nextInt());

This doesn't work out too well at all for me. Instead, I tried:

while (in.hasNextint())
    arrayList.add(in.nextInt());

Basically I type numbers separated by whitespace and then enter some letter and press enter. This works perfectly in IDEs. However, if I try to compile and run it using the command prompt it throws an error in my face: InputMismatchException. Finally, I tried:

while (in.nextLine() != null)
    arrayList.add(in.nextInt());

And that did not work(!) Any ideas?


For keyboard, you would need a

keyListener

You can do this in the class void (I mean the void the same name as your class) For example:

public Classname(){
    //stuff
    window.addKeyListener(new KeyAdapter(){
//For every time the specific key is being pressed
        public void keyPressed(KeyEvent e){
            KeyCode = e.getKeyCode();
                switch (KeyCode) {
                case KeyEvent.VK_SPACE:
                    //stuff
                    break;
                case KeyEvent.VK_H:
                    //stuff
                    break;

                }
            }
        }
//For every time the specific key is being released
public void keyReleased(KeyEvent e){
            switch (e.getKeyCode()) {
            case KeyEvent.VK_LEFT: //stuff
 break;
            case KeyEvent.VK_RIGHT: //stuff
   break;

        }
    });

}

Also, I think there's a public

keyTyped(KeyEvent e)

void that you can use.

Hope this solves ur problem if it doesn't let me know by commenting. :)