java. do not accept 0 as first input in a text field - java
I'm using Java and this part of my code is for entering age in a text field that only accepts numbers, back spaces and delete. How can I also tell the code to avoid accepting 0 if its the first character ?
Thank you.
Here is the code:
private void tfAgeKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar();
if(!(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
}
Well you just need to check if your entered character isn't equal to 0 in your condition using c == '0' when the current input is empty:
if((this.currentInput.isEmpty() && (!Character.isDigit(c) || c == '0')) || !(Character.isDigit(c)) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)){
evt.consume();
}
private void tfAgeKeyTyped(final java.awt.event.KeyEvent evt) {
final char c = evt.getKeyChar();
// You need access to the current input to known if you are on the
// first character or not.
// Here I assume it exists as a private member variable.
final boolean isFirstChar = this.currentInput.isEmpty();
final boolean isValidEvent = (Character.isDigit(c) && !(isFirstChar && c == '0')) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE);
if (isValidEvent) {
evt.consume();
}
}
Related
Of the two constructers one works and the other doesn't when the argument is correct
i'm new to programming. i don't understand why one of the constructers I'm using to check for the validity of the characters of a string argument in the constructer does not work. the constructer should check if the entered string contains only characters G,C,A,T, else it throws an IllegalArgumentException. I tried using an array of characters to check for the validity of the string by using the toCharArray() method on the entered string. the constructer works for invalid strings, but not for valid strings. but another constructer i used works. please let me know why the first one doesn't. //this is the first constructer that doesn't work for me public class Fragment { private String nucleotideSequence; public Fragment(String nucleotides) throws IllegalArgumentException { char[] validityCheck = nucleotides.toCharArray(); int validityCounter = 0; for (char c : validityCheck) { if(c != 'G' || c != 'C' || c != 'A' || c != 'T') { validityCounter++; } } if (validityCounter != 0) { throw new IllegalArgumentException("Invalid characters present"); } nucleotideSequence = nucleotides; } } // this is the second constructer that works public class Fragment { private String nucleotideSequence; public Fragment(String nucleotides) throws IllegalArgumentException { boolean k = false; for(int i = 0; i < nucleotides.length(); i++){ char lol = nucleotides.charAt(i); if(lol=='A'||lol=='G'||lol=='C'||lol=='T'){ k = true; } else{ k = false; } if(k == false){ throw new IllegalArgumentException("Dosent work"); } nucleotideSequence = nucleotides; } } }
Your problem in the constructor that is not working is with the following 'if' statement: if(c != 'G' || c != 'C' || c != 'A' || c != 'T') This statement is always true. So the following: for (char c : validityCheck) { if(c != 'G' || c != 'C' || c != 'A' || c != 'T') { validityCounter++; } } equals: for (char c : validityCheck) { validityCounter++; } the correct statement would be if(c != 'G' && c != 'C' && c != 'A' && c != 'T') {
Java Character Array Errors
I'm making a method for translating characters into their corresponding numbers e.g. a=1, b=2 ... I've been recieving flak from the IDE about my declaration of the dictionary array. I've read the documentation and still have no idea how I would improve this. Thanks for all your responses in advance! :D EDIT: Formatting public static int charNumTrans(char toBeTranslated){ //Variable init int translated = 0; char guessedVariable; //Checking if between a and i if(toBeTranslated == 'a' || toBeTranslated == 'b' || toBeTranslated == 'c' || toBeTranslated == 'd' || toBeTranslated == 'e' || toBeTranslated == 'f' || toBeTranslated == 'g' || toBeTranslated == 'h' || toBeTranslated == 'i'){ //Checking to see which array to use char[] dictionary; dictionary = new char {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; //chekcing between j and s }else if(toBeTranslated == 'j' ||toBeTranslated == 'k' ||toBeTranslated == 'l' ||toBeTranslated == 'm' ||toBeTranslated == 'n' || toBeTranslated == 'o' ||toBeTranslated == 'p' ||toBeTranslated == 'q' ||toBeTranslated == 'r' || toBeTranslated == 's'){//Checking to see if in between dictionary[10] = {'0','j','1','k','2','l','3','m','4','n','5','o','6','p','7','q','8','r','9','s'}; }else{//Everything else will be in this data set. char[] dictionary = {'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; } guessedVariable = dictionary[1]; while(dictionary[guessedVariable] != toBeTranslated){ guessedVariable +=2; } // Assigns letter minus one of array. e.g. b = dictionary[5]. This will then assign dictionary[4] to translated. translated = Character.getNumericValue(dictionary[guessedVariable-1]); return translated; }
First of all, you are not initializing your arrays outside of the if statements, meaning your code at the end won't be able to call the "dictionary" array. Second of all, the problem with using arrays in your scenario that you have different sized arrays. Third of all, in terms of how you are initializing the arrays, as people have pointed out, you need to create a new object that is correct for your data set e.g. new char[] {...}. To fully solve your problem, you might want to consider something like this (I have initialized all of the arrays in the simplest way possible using the same method to avoid confusion): public static int charNumTrans(char toBeTranslated){ //Variable init int translated = 0; char guessedVariable; //Checking if between a and i if(toBeTranslated == 'a' || toBeTranslated == 'b' || toBeTranslated == 'c' || toBeTranslated == 'd' || toBeTranslated == 'e' || toBeTranslated == 'f' || toBeTranslated == 'g' || toBeTranslated == 'h' || toBeTranslated == 'i'){ //Checking to see which array to use char[] dictionary = {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; return findValue(dictionary); //checking between j and s }else if(toBeTranslated == 'j' ||toBeTranslated == 'k' ||toBeTranslated == 'l' ||toBeTranslated == 'm' ||toBeTranslated == 'n' || toBeTranslated == 'o' ||toBeTranslated == 'p' ||toBeTranslated == 'q' ||toBeTranslated == 'r' || toBeTranslated == 's'){//Checking to see if in between char[] dictionary = {'0','j','1','k','2','l','3','m','4','n','5','o','6','p','7','q','8','r','9','s'}; return findValue(dictionary); }else{//Everything else will be in this data set. char[] dictionary = {'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; return findValue(dictionary); } } public static int findValue(char[] dictionary){ guessedVariable = dictionary[1]; while(dictionary[guessedVariable] != toBeTranslated){ guessedVariable +=2; } // Assigns letter minus one of array. e.g. b = dictionary[5]. This will then assign dictionary[4] to translated. translated = Character.getNumericValue(dictionary[guessedVariable-1]); return translated; }
Change dictionary = new char {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'}; to dictionary = new char[] {'0','.','1','a','2','b','3','c','4','d','5','e','6','f','7','g','8','h','9','i'};
For your array declaration, you are missing the [] when you assign the values to the array object you're creating - so, for example, change your declarations to this: char[] dictionary = new char[]{'0','t','1','u','2','v','3','w','4','x','5','y','6','z'}; Also, if you are trying to convert letters to numerical equivalents, may I suggest that you cast the char that you've passed to the function into an int, and then subtract 61 from this value? Reason being is that 61 corresponds to the position of the character 'a' on the Unicode character table, and would greatly simplify assigning a number to the letter that you pass in.
How to stop this java.lang.ArrayIndexOutOfBoundsException?
I'm trying validate my jtextfeild to enter only money value. which include only numeric and a full-stop. ex-17652.50 So I tried this method. But while it is executing I got this java.lang.ArrayIndexOutOfBoundsException: 1 Here is the method. private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { try { char c = evt.getKeyChar(); String mny[] = jTextField1.getText().split("\\."); if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_ENTER) || (c == KeyEvent.VK_TAB) || (c == KeyEvent.VK_NUM_LOCK) || (c == '.'))) { getToolkit().beep(); evt.consume(); } if (mny[1].length() == 2) { getToolkit().beep(); evt.consume(); } } catch (Exception e) { e.printStackTrace(); } } I am getting Array Index Out of Bounds Exception after I typed the first number in textfeild. As I understand this is happening because mny[o] should occur after I enter fullstop. But I can't find a solution. Please help me. Thank you.
Iy there is no dot in you input String mny[] = jTextField1.getText().split("\\."); will return an array with only one item. Arrays in java are zero based. So mny[1].length() will throw an ArrayIndexOutOfBoundsException. You should check here if your array have a size of 2 if (mny.length > 1 && mny[1].length() == 2) {
You could change your condition to : if (mny.length > 1 && mny[1].length() == 2) { getToolkit().beep(); evt.consume(); } (or something similar, depending on the required logic)
Cannot find symbol, Java and Strings
I've tried tinkering around with this for awhile and have yet to figure out what its giving me this error. The code is far from complete but I'm just trying to figure out why it says it can't find variable ch1. Any help is greatly appreciated! public class PhoneNumber { String phoneNumber; public PhoneNumber(String num) { phoneNumber = num; } public String decodePhoneNumber() { // Takes string form phone number and decodes based on number pad // Find code that makes if statement not care about caps // so if a || b || c number[cnt] = 1 etc.. for (int cnt = 0; cnt < phoneNumber.length(); cnt++) { char ch1 = phoneNumber.charAt(cnt); if (Character.ch1.equalsIgnoreCase("a") || ("b") || ("c")) { } else if (ch1.equalsIgnoreCase("d" || "e" || "f")) { } else if (ch1.equalsIgnoreCase("j" || "k" || "l")) { } else if (ch1.equalsIgnoreCase("m" || "n" || "o")) { } else if (ch1.equalsIgnoreCase("p" || "q" || "r" || "s")) { } else if (ch1.equalsIgnoreCase("t" || "u" || "v")) { } else { } } } }
You have syntax errors and that is why you cannot find ch1. Try modifying your code as per this syntax. These changes need to be done in all the conditionals. if ((ch1 == 'a') || (ch1 == 'b') || (ch1 =='c')) {
If you want to make it work regardless of capital letters then you would need to normalize the input to lower case and then do the character comparison: char ch1 = phoneNumber.toLowerCase().charAt(cnt); if (ch1 == 'a' || ch1 == 'b' || ch1 == 'c') { // Do something } ...
Java Input Numbers
I made a method to input numbers. But I want that input is numeric but a dot (.) Can still be entered. please my friend help me. Thanks private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) { // TODO add your handling code here: FilterHanyaAngka(evt); } public void FilterHanyaAngka(java.awt.event.KeyEvent evt) { char c = evt.getKeyChar(); if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) { evt.consume(); } }
Don't use KeyListener to filter content to the a text component, you have no idea of knowing in what order the KeyListeners will be notified and the key stroke may already have being sent to the field before you. Instead you should use a DocumentFilter Take a look at Text Component Features, in particular Implementing a Document Filter and here for examples In fact, I believe there is actually a numeric filter example listed there...
You can use ASCII instead of the Character or KeyEvent class. Look at this: public class ASCIITest { public static void main(String[] args) { char c = '3'; if ((c >= '0' && c <= '9') || c == '.') { //some code.. } } } For more information read about the ASCII chart
yes I've found the solution in my opinion public void filterDesimal(java.awt.event.KeyEvent evt) { char ch = evt.getKeyChar(); if (!((ch == '.') || (ch == '0') || (ch == '1') || (ch == '2') || (ch == '3') || (ch == '4') || (ch == '5')|| (ch == '6') || (ch == '7') || (ch == '8') || (ch == '9') || (ch == ',') || (ch == KeyEvent.VK_BACK_SPACE) || (ch == KeyEvent.VK_DELETE) )){ evt.consume(); } }