How do I only allow numbers in a JTextField using a KeyEvent? - java

My attempt at this is:
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if(c != '1' && c != '2' && c != '3' && c != '4'
&& c != '5' && c != '6' && c != '7' && c != '8'
&& c != '9' && c != '0') {
evt.consume();
}
Which is quite strange, since this is what my book has shown me.
Also, is this viable in comparison to a Formatted Text Field?

You should never use KeyListeners with text components
For one, it doesn't take into account what happens when the user pastes text into the field. It's also possible that the key event could be consumed and never reach your listener
Swing has a number of components which might fulfill your needs
JSpinner
JFormattedTextField
Both these are capable of restricting user input to numbers and I'm the case of the JSpinner, ranges of numbers
These fields are post processing, that is, they will allow the user to enter what ever they want, but will validate the value when the loses focus or the user accepts the value
If you want real time filtering you should use a DocumentFilter, for examples

Try replacing your if (Mile of tests) with:
if(c < '0' || c > '9')
evt.consume();
or, the more readable, as azurefrog pointed out:
if(!Character.isDigit(c))
evt.consume();

If you want the backspace and delete button to function then you need to put them inside your if statement
sample:
if(c != '1' && c != '2' && c != '3' && c != '4'
&& c != '5' && c != '6' && c != '7' && c != '8'
&& c != '9' && c != '0') || !(c == KeyEvent.VK_BACK_SPACE) ||
!(c == KeyEvent.VK_DELETE)){
evt.consume();
}

Related

How to prevent IntelliJ to stop continuing double-slash comments on the next line?

Short version
When pressing <enter> at the end of a // comment, Intellij sometimes decides to continue the // comment on the next line. How can I prevent that? Is there a setting somewhere to disable this automation?
Long version
There is a thing I do regularily, it is to break a long expression with a double-slash.
Let's say I have a line like
boolean isHex = c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
and I want to split it like that
boolean isHex = c >= '0' && c <= '9' //
|| c >= 'A' && c <= 'F' //
|| c >= 'a' && c <= 'f';
Note that I want the final // in order to prevent any formatter to join the lines again.
So I insert a double-slash-return after the '9', by pressing //<enter>. But Intellij will auto-continue the comment on the next line.
boolean isHex = c >= '0' && c <= '9' //
// || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
It forces me to uncomment and reindent the line manually.
I want Intellij to not continue the comment on the next line and optionally indent my code:
boolean isHex = c >= '0' && c <= '9' //
|| c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
So I want to disable this "continue // comment after <enter>" feature. Is it possible? I haven't found any setting related to that.
The closest you are going to get is to define a macro to insert a new line and remove the comment and then bind that macro to a suitable key.
Go to Settings → Code Style → Java → Wrapping and Braces and check "Line breaks" under "Keep when reformatting". This will make IntelliJ's formatter respect any manual line breaks, even if they contradict other formatting rules.

Or operand not working in while loop [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 4 years ago.
I have this loop statement, which I'll express using C-like syntax (C, C++, Java, JavaScript, PHP, etc. all use similar syntax):
while (c != 'o' || c != 'x') {
c = getANewValue();
}
I want it to run until I get a 'o' or 'x', but it never exits, even when c is 'o' or 'x'. Why not?
I've also tried using if:
if (c != 'o' || c != 'x') {
// Show an error saying it must be either 'o' or 'x'
}
but that also always shows the error message, even when c is 'o' or 'x'. Why?
The condition (c != 'o' || c != 'x') can never be false. If c is 'o', then c != 'x' will be true and the OR condition is satisfied. If c is 'x', then c != 'o' will be true and the OR condition is satisfied.
You want && (AND), not || (OR):
while (c != 'o' && c != 'x') {
// ...
}
"While c is NOT 'o' AND c is NOT `'x'..." (e.g., it's neither of them).
Or use De Morgan's law, covered here:
while (!(c == 'o' || c == 'x')) {
// ...
}
"While it's NOT true that (c is 'o' or c is 'x')..."
It must be if(c!='o' && c!='x') instead of if(c!='o' || c!='x'). If you use the or operator the boolean expression will be always true.
Why is my c != 'o' || c != 'x' condition always true?
The expression combines two sub-expressions using the logical OR operator (||). The expression is true if at least one of the sub-expressions is true. In order to be false, both sub-expressions it connects must be false.
The sub-expressions are c != 'o' and c != 'x'.
The first sub-expression c != 'o' is false when c == 'o'. The same for the second one; it is false when c == 'x'.
Please note that they cannot be false on the same time because c cannot be 'o' and 'x' on the same time.
The condition should be if(!(c=='o' || c=='x')) or if(c!='o' && c!='x')
even when you enter x or you enter o in that case if condition evaluates to true and hence game_start remains false.
it should be if(c!='o' && c!='x')
or use a more straight forward way
if(c == 'o' || c == 'x')
game_start=true;
else
System.out.println("you can only enter o or x!");

Boolean Logic in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have come across a problem in Boolean logic in which you must assign Boolean values to each of the three variables, therefore making each equation unequal to each other.
The problem specifies:
!b && (c || !d) != !(b || !c && d)
I've tried solving the problem with a guess and check method, but I haven't had any luck quite yet. Is there a way to solve the problem algebraically? I'm working in Java.
This is a bit of a trick question. Consider applying De Morgan's law to the expression on the left, after applying a double negation:
!!(!b && (c || !d))
!(b || !(c || !d))
!(b || !c && d)
In other words, there is no such combination because the two are logically equivalent.
A very simple solution to this kind of problem can often be checking the formular for what seems to be the most "powerful" value. Here I'd say that is b.
So let's go through the examples with b == true and b == false.
First though, let's add some more parenthesis so it's clear what is what:
!b && (c || !d) != !(b || !c && d)
= (!b && (c || !d)) != !(b || (!c && d))
If b == true then:
(!true && (c || !d)) != !(true || (!c && d))
=> (false && (c || !d)) != !(true || (!c && d))
=> false != !true
=> false != false
=> false
And if b == false then:
(!false && (c || !d)) != !(false || (!c && d))
=> (true && (c || !d)) != !(!c && d)
=> (c || !d) != (c || !d)
=> false
So this can never be fulfilled.
You can use some rules of boolean logic:
!(a || b) = !a && !b
!(a && b) = !a || !b
Apply them to the right hand side:
!(b || !c && d) = !b && !(!c && d) = !b && (c || !d)

operator precedence && and ||

please ignore the question - its wrong
I am not sure if my question is issue is related to operator precedence- Just to rule out that I added additional bracket. My understanding is in that case that code in each bracket will be executed. So basically all the OR operation will happen and its output would be AND'ed to condition a.
I have below set of parameters a = true and c = 254 , b is not availble ( b is initialized to 0 -At any given time either b or c only is availble) . So for the above condition I am expecting if condition to result in true but it's resulting in false condition. Any reason why ? Also what is best way to debug such things as in where exactly condition is going wrong - any pointers
if ((a == true) && ((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825)))
First a is evaluated, if (a == true) evaluated to true, then only it will execute next && statement
((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825))
Inside this, it will check for any one condition which is true, and once it encounter any one statement true, it return from there.
For your condition to be true, a must be true, and in addition, at least one of the conditions on b or c must be true.
Therefore, if a==true and c==254, you will get false, since c is not within any of the ranges you allow, and, as you said, b is not available (which I'm assuming means it doesn't have one of the 3 values you allow).
It would be much simpler if the code is written in a more readable manner;
bool isEqualToAny(int valueToCheck, int[] listToCheckIn){
boolean isMatch = false;
(for item in listToCheckIn){
if (item == valueToCheck){
isMatch = true;
break;
}
}
}
bool isWithinRange(int valueToCheck, int min, int max){
return (valueToCheck > min && valueToCheck < max);
}
if ((a == true)
&& (isEqualToAny(b, int[]{460,454,455})
|| isWithinRange(c,3568,14335)
|| isWithinRange(c,10640,10655)
|| isWithinRange(c,11296,11311)
|| isWithinRange(c,25600,26111)
|| isWithinRange(c,10640,10655)
|| (c== 7825)))
In java8 you can use an array of Tuples to make #isWithinRange more like #isEqualToAny

Backspace Ascii value vs integer?

So far I have a text field that accepts only numbers, backspace, delete, decimal and hyphens. The block of code with is:
if ( ((keyChar > '0') && (keyChar < '9')) ||
(keyChar == '.') || (keyChar == '-') ||
(keyChar == 8 ) || (keyChar == 127) )
This works however when I leave out the "(keyChar == 8 ) ||" and use
if ( ((keyChar > '0') && (keyChar < '9')) ||
(keyChar == '.') || (keyChar == '-') ||
(keyChar == 127) )
The backspace key does not work even though it is between 0 and 9?
The backspace key does not work even though it is between 0 and 9?
The backspace key does not generate a character, its value is undefined. A character is something that can actually be displayed in a text component.
Assuming this is Swing then don't attempt to solve this by using a KeyListener. Swing has newer and better API's:
See Using a Formatted Text Field for a component will built in support for this
See Implementing a DocumentFilter for implementing you own custom editing of valid characters.

Categories

Resources