Cannot find symbol, Java and Strings - java

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
}
...

Related

Creating an Ubbi Dubbi translator in Java

I'm in an entry java class, and for one of my programs I am expected to create a ubbi dubbi translator, which ads a ub before every vowel and vowel cluster. I cannot figure out how to get my program to run correctly, and also am unsure how to make it exclude the extra vowel included with the cluster. I am not allowed to use Stringbuilder..
public void buttonPressed()
{
String lowerCase = "";
String userInput = input.getText();
Scanner words = new Scanner( userInput );
String ubbiDubbi = "";
//Splits up user input by line
while (words.hasNext()) {
//Converting to lower case.
lowerCase = words.next().toLowerCase();
System.out.println(lowerCase);
}
for (int i = 0; i < lowerCase.length(); i++) {
if (lowerCase.charAt(i+1) == 'a'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'e') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'i'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'o'){
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else if (lowerCase.charAt(i+1) == 'u') {
ubbiDubbi = ubbiDubbi + lowerCase.charAt(i+1);
}
else {
ubbiDubbi += lowerCase.charAt(i);
}
To get this translator to work you basically just need to step through each character in the input and write it to the output. In addition if the input is a vowel you need to write "ub" out first, except where the previous character was also a vowel.
One thing which is going to be handy is to be able to identify vowels. Starting by writing a function for this is a good idea. It could look like:
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
Now that's in place if you look at the translation, we want to step over every character in the input and write it to the output. This could look like this:
private String translate(String raw) {
String translated = "";
for(char c:raw.toCharArray()) {
// some extra stuff needed here
translated += c;
}
return translated;
}
For the extra stuff you need to know if the current character is a vowel and whether the previous character was a vowel so we can add a little to do this:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false; //
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
And finally to ad "ub" where required you can check if the character is a vowel and whether the last character was a vowel:
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
With that in place you just need to hook up the button press action etc. So it might look a little like this:
public class UbbiDubbi {
private boolean isVowel(char c) {
return
c == 'a' || c == 'A' ||
c == 'e' || c == 'E' ||
c == 'i' || c == 'I' ||
c == 'o' || c == 'O' ||
c == 'u' || c == 'U';
}
private String translate(String raw) {
String translated = "";
boolean wasLastCharacterVowel = false;
for(char c:raw.toCharArray()) {
if(isVowel(c)) {
if(!wasLastCharacterVowel) {
translated += "ub";
}
wasLastCharacterVowel = true;
} else {
wasLastCharacterVowel = false;
}
translated += c;
}
return translated;
}
public void buttonPressed() {
String userInput = "";// = input.getText();
Scanner words = new Scanner( userInput );
while (words.hasNext()) {
String lowerCase = words.next().toLowerCase();
String translated = translate(lowerCase);
System.out.println(translated);
}
words.close();
}
public static void main(String...none) {
System.out.println(new UbbiDubbi().translate("The quick brown fox jumps over the lazy aadvark"));
}
}
adding the main method gives an easy way to test out the translation. Hope this helps.

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') {

Can't figure out why int is duplicating in Java

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

Phone numbers in java

I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSáµ 's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).

Checking string for large amount of different, incremental values

Currently I am checking a string for the following:
if(parseCommand.contains("vlan1")
|| parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o")
|| parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
|| parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0"))
{
//do things here
}
However it may contain vlan1 up to vlan4094 and i have to check for these. What is the simplest way to do this, do I have to stick it all in a for loop incrementing to 4094 I guess?
for (int i = 1; i <= 4094; i++)
{
if(parseCommand.contains("vlan"[i]))
{
//do stuff here
}
}
if(other conditions from above)
{
//do same stuff again here
}
Or else I could stick all the conditions in the for loop and do everything inside there. This all seems messy, is there a non-messy way of doing it?
I think this regex should do it:
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
"[1-9][0-9]{0,2}|" +
"40(9[0-4]|[0-8][0-9])).*"))
System.out.println("matches");
[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094
Something like this is probably simpler:
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
int v = Integer.parseInt(parseCommand.substring(4));
if (v >= 1 && v <= 4094)
/* do stuff */
}
Suggested change:
Replace:
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
with
parseCommand.matches(".*?Fa1/[0-9].*")
You can combie them into one boolean
boolean b = false;
for(int i = 1 ; i < 4094 ; i ++){
b = b || parseCommand.contains("vlan" + i);
}
Then check your boolean value
If the only problem is with "vlanXXX" you can remove the "vlan" part of the string:
parseCommand = parseCommand.replaceFirst("vlan", "");
and then cast it to int
int value = Integer.parseInt(parseCommand);
and then comparing this result with that whaat you want
if((value >= 1) && (value <= 4094)){....}
This will only work for the given case and you have to handle the case where parseCommand cannot be cast to int. And it is much more understandable than using whatever regular expresion

Categories

Resources