Unknown
Unknown

Reputation: 13

How do I get java to only accept the user input of numbers 1-5?

I'm creating a small game and I want the user to only be able to input numbers 1-5 in the cells where both row (r) and column (c) are odd. I'm extremely new to this so I'm not bothered about the code being perfect, just trying to understand it.

if((r%2==1)&&(c%2==1)){
    setBackground(Color.WHITE);
    addKeyListener(new KeyAdapter(){
    @Override
    public void keyTyped(KeyEvent e){
        int c =(e.getKeyChar());
        trace("c: "+c);
        if ((c!='1')||(c!='2')||(c!='3')||(c!='4')||(c!='5'))
            panel.setStatus("Invalid input");
            return;
        }});
    };

I also tried using the unicode

    setBackground(Color.WHITE);
    addKeyListener(new KeyAdapter(){
    @Override
    public void keyTyped(KeyEvent e){
        int c =(e.getKeyCode());
        trace("c: "+c);
        if ((c!=49||(c!=50)||(c!=51)||(c!=52)||(c!=53))
            panel.setStatus("Invalid input");
            return;
        }});
    }; 

but neither seem to work?

Upvotes: 0

Views: 674

Answers (1)

knittl
knittl

Reputation: 265201

I see one definitive error and one potential error.

if ((c!='1')||(c!='2')||(c!='3')||(c!='4')||(c!='5'))
        panel.setStatus("Invalid input");
        return;

Is equivalent to:

if ((c!='1')||(c!='2')||(c!='3')||(c!='4')||(c!='5')) {
        panel.setStatus("Invalid input");
}
return;

Not sure if that's what you wanted. Your indentation suggests otherwise. Maybe it is just a mistake in the question. With the code given in the question, there is no difference, because return is the last statement of the block anyway. But something to keep in mind for future code if the early exit should happen conditionally and the other code skipped.

The definitive error is your boolean logic. They way you have written, the expression can never be false:

(c!='1') || (c!='2') || (c!='3') || (c!='4') || (c!='5')

If c is '1', then it is not equal to '2'. If c is '2' then it is not equal to '3'. Therefore the expression is always true for any input (a so-called tautology). The way you want to write it is either of the two:

(c!='1')&&(c!='2')&&(c!='3')&&(c!='4')&&(c!='5')
!((c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')

Or simpler:

if (!(c >= '1' && c <= '5'))

Upvotes: 1

Related Questions