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.
Related
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();
}
}
I am creatings a simple Java program that in the main class asks for a string (input) and then prints out how many vowels (int count) and consonants are in the string. The number of vowels works perfectly however the number of consonants double, so the string "James" has 2 vowels and 6 consonants according to my program.
public class counter {
vowels p1 = new vowels();
public int con = 0;
public int count() {
String input = p1.getInput();
int i = 0;
int count = 0;
while (i < input.length()){
if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'i' || input.charAt(i) == 'o' || input.charAt(i) == 'u') {
count++;
} else if (input.charAt(i) != ' ') {
con++;
}
i++;
}
return count;
}
public int con() {
return con;
}
}
You are using an instance member con for counting the consonants, and you don't initialize it at the beginning of the count method, so multiple calls to that method will result in invalid counts.
seems like you are using
int con=0;
is used for consonant count
so instead of using
else if (input.charAt(i) != ' ') {
con++;
}
simply use
else {
con++;
}
Alternate :
subtract the vowel count from string length
'com = P1.length()-count;'
Try to set the variable con to zero at the begining of the method "count".
con = 0;
I hope it works.
char ch;
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
count ++;
else
con;
}
you had nod consider the case when vowels are in caps I solved this in my code
hope my code helps you in this regard thanks.Happy coding
I have a char[] that must be comprised of the letters : 'R', 'B', 'O', 'V', 'J', 'F', 'I', 'N'. I must check if the array contains only these letters and if not, I need to reintroduce the letters till it contains the correct letters.
I did this by a method (which is not working):
boolean validation=false;
if (choixJoueur.length != 4) {
validation=false;
} else {
for (int i = 0; i < 4; i++) {
if (choixJoueur[i] != 'R' || choixJoueur[i] != 'B'
|| choixJoueur[i] != 'O' || choixJoueur[i] != 'V'
|| choixJoueur[i] != 'J' || choixJoueur[i] != 'F'
|| choixJoueur[i] != 'I' || choixJoueur[i] != 'N')) {
validation=false;
} else
validation=true;
}
}
If I test it with RBVD the validation is (correctly) calculated as false, but if I try RBVO the validation is (incorrectly) false too.
Frakcool is right about the first part. You want to check that a character {is not R, AND it is not B, AND it is not O, AND ...}. Currently, you are checking if an individual character {is not R, OR is not B, OR is not O, OR ...}. This doesn't work because every character in existence will be either not R or not B.
You also have another problem which is that you are only effectively checking if the last character is one of those characters because for every character you reset the value of 'validation' without taking into consideration a past failure. In other words, if the first letter failed but the last letter passed, you just set validation to true even though it should be false. Instead, it's best to just start with true and set it to false whenever a failure condition is encountered, without ever setting it to true again.
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException
{
char[] choixJoueur = { 'R', 'B', 'V', 'O' };
boolean validation = true;
if (choixJoueur.length != 4)
validation = false;
else
{
for (int i = 0; i < 4; i++)
{
if (choixJoueur[i] != 'R' && choixJoueur[i] != 'B'
&& choixJoueur[i] != 'O' && choixJoueur[i] != 'V'
&& choixJoueur[i] != 'J' && choixJoueur[i] != 'F'
&& choixJoueur[i] != 'I' && choixJoueur[i] != 'N')
{
validation = false;
}
}
}
System.out.println(validation);
}
}
if (choixJoueur[i] != 'R' || choixJoueur[i] != 'B'
|| choixJoueur[i] != 'O' || choixJoueur[i] != 'V'
|| choixJoueur[i] != 'J' || choixJoueur[i] != 'F'
|| choixJoueur[i] != 'I' || choixJoueur[i] != 'N')) {
validation=false;
}else
validation=true;
}
Let's debug your code:
Your input for example: RBVD then:
R != R is false but R != B is true so validation = false
B != R is true so validation = false
V != R is true so validation = false
D != R is true so validation = false
You remain with false the same goes with your second input.
You might want to change || for && on your if validations to validate all of the possibilities.
Also, in case the validation is false, you might want to break the for-loop :) (Or that's my guess)
If changed to && this would be the debug:
R != R is false so validation = true
B != R is true but B != B is false so validation = true
V != R is true but V != V is false so validation = true
D != R is true and D is different from all of the rest of letters, so validation = false
On the other hand with RBVO
R != R is false so validation = true
B != R is true but B != B is false so validation = true
V != R is true but V != V is false so validation = true
O != R is true but O != O is false so validation = true
After all of that your if statement should be:
if (choixJoueur[i] != 'R' && choixJoueur[i] != 'B'
&& choixJoueur[i] != 'O' && choixJoueur[i] != 'V'
&& choixJoueur[i] != 'J' && choixJoueur[i] != 'F'
&& choixJoueur[i] != 'I' && choixJoueur[i] != 'N')) {
validation=false;
break; //because I guess if it contains any of the letters the validation fails, if you don't and the next letter is a valid one it will override validation to true.
}else
validation=true;
}
Also you can change it to:
boolean validate = true;
and remove the else statement inside your for-loop. But still take into consideration the break statement since it will prevent the program from doing more operations when it knows it's an invalid input from the moment it finds it's invalid (such as on 1st letter or something like that).
The problem is the logic; you should be using && (rather than ||) between your conditions (every character is not equal to at least one of the tested chars).
But you can simplify your code considerably by using regex, which does it all in one line:
boolean validation = new String(choixJoueur).matches("[RBOVJFIN]{4}");
If you want to also assert that no character is used more than once:
boolean validation = new String(choixJoueur).matches("((?!(.).*\\1)[RBOVJFIN]){4}");
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
}
...
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();
}
}