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.
Related
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.
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();
}
Java beginner here - hoping someone can help me solve this problem. I am trying to write a simple program that will display a particular message depending on the character entered by the user. The problem I'm having is that it won't recognize the validity of capitalized characters in determining which message to print.
The code compiles OK but if I enter a capital letter, it prints out the message telling me it is not a valid character to start an identifier.
Here is a snippet of the source code:
choice2 = (char) System.in.read();
if(choice2 == 'q')
break;
else
if(choice2 == '_' || choice2 >= 'a' && choice2 <= 'z' && choice2 >= 'A' && choice2 <= 'Z' && choice2 > '0' && choice2 <= '9')
System.out.println("That is a valid character to start an identifier.");
else
if(choice2 == '$')
System.out.println("That is a valid character to start an identifier but should only be used by mechanically generated source code");
else
System.out.println("Sorry, that is not a valid character to start an identifier");
break;
Is there something I'm doing wrong or is it something inherent to the char data type?
Thanks
The problem is with your boolean groupings and a couple && should be ||
if (choice2 == '_' ||
((choice2 >= 'a' && choice2 <= 'z') ||
(choice2 >= 'A' && choice2 <= 'Z') ||
(choice2 > '0' && choice2 <= '9')))
This will evaluate to true if choice2 == '_' OR if choice2 is either between a and z inclusive, between A and Z inclusive, or between 0 and 9 inclusive.
The program is suppose to check if a string is consecutive including string such as zab and 901234. I wrote and exception to each so I can skip over 90 or za if they appear. Unfortunately I can't seem to get into the if block of code... I'm not sure why. If someone can help me get into this 901 it would be much appreciated.
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == 9 && s.charAt(i + 1) == 0) {
System.out.println("in");
}
}
Remember, integers get converted to characters through the ASCII table, so you want the characters '9' and '0'
Your original code was actually looking for the null (0) and backspace (9) characters. More info on the ASCII table here: ASCII Table
for (int i=0; i<s.length()-1; i++){
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {
System.out.println("in");
}
}
You need to test for charachers:
if (s.charAt(i) == '9' && s.charAt(i + 1) == '0') {
I have a bunch of characters and want to remove everything that isn't a '#' '.' 'E' and 'G'.
I tried to use this:
if (buffer.get(buffertest) == 'G'|'E'|'#'|'.')
But got an issue with an incompatible type.
This root problem is incorrect use of the bitwise OR operator, and the Java operator precedence hierarchy. Java expressions of this type are evaluated left to right, and the == operator takes precedence over |. Which when combined, your expression roughly translates to:
(buffer.get(buffertest) == 'G') | 'E' | '#' | '.'
The first part of the expression buffer.get(buffertest) == 'G' evaluates to a boolean.<br>
The second part of the expression'E' | '#' | '.'` evaluates to an int, which is narrowed to a char
Which leads to an incompatible type compile time error. You can correct your code by expanding the check this way:
char ch = buffer.get(buffertest);
if(ch == 'G' || ch == 'E' || ch == '#' || ch == '.') {
// do something
}
You need to compare for each character individually. Assuming that buffer.get(buffertest) returns a char, here's how to do it:
char c = buffer.get(buffertest);
if (c == 'G' || c == 'E' || c == '#' || c == '.') {
// do something
}
Alternatively, you could do something like this:
char c = buffer.get(buffertest);
if ("GE#.".contains(Character.toString(c))) {
// do something
}
You haven't shown the type of buffer, which makes things harder. But assuming buffer.get returns a char, you could use:
if ("GE#.".indexOf(buffer.get(buffertest) >= 0)
Or you could check each option explicitly, as per Simulant's answer... or to do the same thing but only calling get once:
char x = buffer.get(buffertest);
if (x == 'G' || x == 'E' || x == '#' || x == '.')
Your original code is failing because | is trying to perform a bitwise "OR" operation on the four characters... it's not the same thing as performing a logical "OR" on four conditions.
if (buffer.get(buffertest) == 'G'||
buffer.get(buffertest) == 'E'||
buffer.get(buffertest) == '#'||
buffer.get(buffertest) == '.')