Method that appends to a Stringbuilder based on user entered value - java

I have a homework problem that wants me to take a phone number and if the phone number has characters to determine what number that is. When I run my current method it returns the numbers but any characters input the method ignores them.
I have tried different versions of my current method.
class Telephone {
String telephoneNumber;
StringBuilder telephone = new StringBuilder();
public String translator(String telephoneNumber){
for(int i=0; i<telephoneNumber.length(); i++){
if(Character.isDigit(telephoneNumber.charAt(i))){
telephone.append(telephoneNumber.charAt(i));
} else if(telephoneNumber.charAt(i) == 'A' || telephoneNumber.charAt(i) == 'B' || telephoneNumber.charAt(i) == 'C') {
telephone.append(2);
} else if(telephoneNumber.charAt(i) == 'D' || telephoneNumber.charAt(i) == 'E' || telephoneNumber.charAt(i) == 'F'){
telephone.append(3);
} else if(telephoneNumber.charAt(i) == 'G' || telephoneNumber.charAt(i) == 'H' || telephoneNumber.charAt(i) == 'I'){
telephone.append(4);
} else if(telephoneNumber.charAt(i) == 'J' || telephoneNumber.charAt(i) == 'K' || telephoneNumber.charAt(i) == 'L'){
telephone.append(5);
} else if(telephoneNumber.charAt(i) == 'M' || telephoneNumber.charAt(i) == 'N' || telephoneNumber.charAt(i) == 'O'){
telephone.append(6);
} else if(telephoneNumber.charAt(i) == 'P' || telephoneNumber.charAt(i) == 'Q' || telephoneNumber.charAt(i) == 'R'){
telephone.append(7);
} else if(telephoneNumber.charAt(i) == 'T' || telephoneNumber.charAt(i) == 'U' || telephoneNumber.charAt(i) == 'V'){
telephone.append(8);
} else if(telephoneNumber.charAt(i) == 'W' || telephoneNumber.charAt(i) == 'X' || telephoneNumber.charAt(i) == 'Y' || telephoneNumber.charAt(i) == 'Z' ){
telephone.append(9);
}
}
return telephone.toString();
}
}
Current results: telephone entered 555555food returns 555555. I would need it to return 555 555 3662

Write a function that takes in two chars, converts them to Strings using String.valueOf() then compare them using equalsIgnoreCase(). And then use that function in all of your else-if conditions. That should make it cleaner.
EDIT
You can also convert the telephoneNumber to upper case (or lower case, your wish) and then proceed as you were as suggested by #Stultuske in the comments

Related

How do I get scanner input to register a blank space as a value

I am writing a code that represents an old-fashioned phone keypad. Everything is working fine except for when I try to take a blank space from the user which is supposed to print out the number 0. I've tried Unicode as well with '\u0020' but that didn't work either. In the output If I type a space and hit enter, I get another line so the scanner is not recognizing the blank space as a char that would be my guess. Someone, please help thanks!
import java.util.Scanner;
public class phoneKeypad{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a letter: ");
char userInput = input.next().charAt(0);
if (userInput == 'a' || userInput == 'b' || userInput == 'c' ||
userInput == 'A' || userInput == 'B' || userInput == 'C')
{
System.out.println(userInput + " is the number 2!");
}
else if (userInput == 'd' || userInput == 'e' || userInput == 'f' ||
userInput == 'D' || userInput == 'E' || userInput == 'F')
{
System.out.println(userInput + " is the number 3!");
}
else if (userInput == 'g' || userInput == 'h' || userInput == 'i' ||
userInput == 'G' || userInput == 'H' || userInput == 'I')
{
System.out.println(userInput + " is the number 4!");
}
else if (userInput == 'j' || userInput == 'k' || userInput == 'l' ||
userInput == 'J' || userInput == 'K' || userInput == 'L')
{
System.out.println(userInput + " is the number 5!");
}
else if (userInput == 'm' || userInput == 'n' || userInput == 'o' ||
userInput == 'M' || userInput == 'N' || userInput == 'O')
{
System.out.println(userInput + " is the number 6!");
}
else if (userInput == 'p' || userInput == 'q' || userInput == 'r' || userInput == 's' ||
userInput == 'P' || userInput == 'Q' || userInput == 'R' || userInput == 'S')
{
System.out.println(userInput + " is the number 7!");
}
else if (userInput == 't' || userInput == 'u' || userInput == 'v' ||
userInput == 'T' || userInput == 'U' || userInput == 'V')
{
System.out.println(userInput + " is the number 8!");
}
else if (userInput == 'w' || userInput == 'x' || userInput == 'y' || userInput == 'z' ||
userInput == 'W' || userInput == 'X' || userInput == 'Y' || userInput == 'Z')
{
System.out.println(userInput + " is the number 9!");
}
else if (userInput == '\u0020')
{
System.out.println("Blank space is the number 0!");
}
else
{
System.out.println(userInput + " could be either a 1 or the character does not exist");
}
input.close();
}
}
Use:
char userInput = input.nextLine().charAt(0);
instead of:
char userInput = input.next().charAt(0);
Use Scanner.nextLine() instead of next() :
char userInput = input.nextLine().charAt(0);
scanner.nextLine() will capture everything in the line, including whitespace.
scanner.next() will not capture whitespace as the delimiter is whitespace by default.
So, try using scanner.nextLine();

Rules not obeyed by if statement

The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}

Why does `if (guess != 'a' || guess != 'A' || ...)` not work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Here is my code, I know the if statement is really long and the code could probably be more efficient, but I just want to know the answer to this as it is driving me nuts.
while (whileloop == 1)
{
if (guess != 'a' || guess != 'A' || guess != 'b' || guess != 'B' || guess != 'c' || guess != 'C' || guess != 'd' || guess != 'D' || guess != 'e' || guess != 'E' || guess != 'f' || guess != 'F' || guess != 'g' || guess != 'G' || guess != 'h' || guess != 'H' || guess != 'i' || guess != 'I' || guess != 'j' || guess != 'J' || guess != 'k' || guess != 'K' || guess != 'l' || guess != 'L' || guess != 'm' || guess != 'M' || guess != 'n' || guess != 'N' || guess != 'o' || guess != 'O' ||guess != 'p' || guess != 'P' || guess != 'q' || guess != 'Q' || guess != 'r' || guess != 'R' || guess != 's' || guess != 'S' || guess != 't' || guess != 'T' || guess == ' ')
{
System.out.println ("\nNot a Point. Try again.");
guess = IBIO.inputChar ("If the missile is launched from Point B, which Point will the missile hit? ");
}
else
whileloop = 2;
}
Because you wanted a logical and && (not a logical or ||). When you use || if any condition is true (such as the letter A not being the letter B, the entire expression is true). You could use an || with two ands. Something like
if (!(guess >= 'a' && guess <= 'z') || !(guess >= 'A' && guess <= 'Z'))

Sorting data file by number of vowels

Sort all words by comparing the number of vowels that each word contains. The
word with the fewest number of vowels would come first. If you have more than one word with the same number of vowels, that group would be sorted alphabetically.
I believe that I have most of the project completed, I just don't know why it's not working.
public class Word implements Comparable<Word> {
private String word;
public Word(String s) {
word = s;
}
private int numVowels() {
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for (int i = 0; i < vowels.length(); i++) {
if ((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u')) {
return vowelCount;
}
}
return vowelCount;
}
public int compareTo(Word rhs) {
for (int i = 0; i < word.length(); i++) {
if ((word.charAt(i) == 'a') || (word.charAt(i) == 'A')) {
System.out.println(word);
} else if ((word.charAt(i + 1) == 'e') || (word.charAt(i + 1) == 'E')) {
System.out.println(word);
}
}
return -1;
}
public String toString() {
return word;
}
}
I think my error is in the compareTo method. I'm not sure. Would anyone be able to help me?
First - I didn't realize that Word was your custom class. That said...there's a lot of flaws with it.
Your compareTo method is really, effectively, only comparing two Strings together. What you want to do is something like this:
public int compareTo(Word other) {
return word.compareTo(other.getWord());
}
The reason for this is that String implements Comparable<String>.
Now, if this isn't what you're going for (and I'm really not sure what that exactly is), then you may look into comparing the number of vowels two Word instances have.
public int compareTo(Word other) {
return word.numVowels() - other.numVowels();
}
The above will return a positive value if the current Word has more vowels than the Word being compared to, a negative value if there are less, or zero if the vowels are equivalent.
Next, your numVowels() method is completely broken. Look at what you're iterating across: vowels. The vowels String is always a constant value. It's never going to change - there are exactly ten vowels, five lower case, and five upper case.
What you want to do is check your word field against the set of vowels.
Here's a better* solution: use a Set<Character> - you get constant look up time for them all.
Set<Character> vowelSet = new HashSet<Character>() {{
add('a');
add('A');
add('e');
add('E');
add('i');
add('I');
add('o');
add('O');
add('u');
add('U');
}};
Then, all you have to do in your loop is this:
int count = 0;
for(char c : word.toCharArray()) {
if(vowelSet.contains(c)) {
count++;
}
}
return count;
*It doesn't take into account that Y is sometimes a vowel.
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
vowelCount++;
}
You were previously returning 0 when you returned vowelCount. You need to increment vowelCount when you find vowels and then return it after you're done looping. You also need to check for upper case vowels and not just lower case vowels to get an accurate count.
Your compareTo method is not even close to correct...
First of all, try not to post your Homework on here. Your numVowels() method is wrong too.
private int numVowels() //FIXED METHOD
{
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for(int i = 0; i < vowels.length(); i++)
{
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
return vowelCount; //Will return lowercase AND capital vowels :)
}
}
return vowelCount;
}
Your original code only searched for lowercase 'a', 'e', 'i', 'o', and 'u'. I added capitals to your if statement ('A', 'E' etc)

l33t why is it printing three U's

i am having a problem i am making a l33t translator and my translator from English to l33t works for my l33t to English works other then u and what is happening is it is printing three U's i have tryed taking it out of the for loop and it will only print one but it prints it at the start of the word i have tryed putting it at the bottom out of the for and it doesnt even print one. i have also tryed if(phrase.charAt(i) == '|') && phrase.charAt(i+1) == '_' && phrase.charAt(i+2) == '|'). here is what i got.
public static String translateToEnglish(String phrase) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello what pharse would you like to convert in to l33t");
phrase = scan.nextLine();
String NewString = "";
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == '4') {
NewString += "a";
}
if (phrase.charAt(i) == '8') {
NewString += "b";
} else {
if (phrase.charAt(i) == '3') {
NewString += "e";
}
}
if (phrase.charAt(i) == '1') {
NewString += "l";
} else {
if (phrase.charAt(i) == '0') {
NewString += "o";
}
}
if (phrase.charAt(i) == '5') {
NewString += "s";
} else {
if (phrase.charAt(i) == '7') {
NewString += "t";
}
}
if (phrase.contains("|_|")) {
NewString += "u";
}
if (phrase.charAt(i) == '2') {
NewString += "z";
}
if (phrase.charAt(i) == 'c' || phrase.charAt(i) == 'd' || phrase.charAt(i) == 'f' || phrase.charAt(i) == 'g'
|| phrase.charAt(i) == 'h' || phrase.charAt(i) == 'i'
|| phrase.charAt(i) == 'j' || phrase.charAt(i) == 'k' || phrase.charAt(i) == 'm' || phrase.charAt(i) == 'n'
|| phrase.charAt(i) == 'p' || phrase.charAt(i) == 'q'
|| phrase.charAt(i) == 'r' || phrase.charAt(i) == 'v' || phrase.charAt(i) == 'w' || phrase.charAt(i) == 'x'
|| phrase.charAt(i) == 'y') {
NewString += phrase.charAt(i);
}
// if (phrase.charAt(i) == 'c') {
}
System.out.println(NewString);
return phrase;
}
For every char in the word you check if it contains a "u". It will always be true because you don't check at a specific position of the word. You would have to check for a | followed by _ followed by | and then add a "u" instead of generally checking if it's somewhere in the input.
Your if statement for |_| is doing a String#contains comparison and is not elsed. So for every iteration in the loop it will print a u if the phrase contains this sequence of characters.
If you use your alternative of checking each char at i, i+1, i+2 you will firstly have to make sure that your phrase is long enough and then if it is true, in that if statement you will have to make sure you increment i by 3 i.e
if(phrase.length() < i+2
&& phrase.charAt(i) == '|')
&& phrase.charAt(i+1) == '_'
&& phrase.charAt(i+2) == '|')
{
NewString += "u";
i += 2; // Will get the third increment from loop
continue;
}
Also if you make sure the structure is always if..if else...else, the final check where is just replaces with the same character can just be reduced to an else without needing to or together every other character

Categories