I can't seem to find the problem with this code. I am trying to convert a phone number which is comprised of numbers and letters to numbers only. For example, 1800SMILEING should translate to 1800-764-5464. But my code repeats the last digit in each group. 180048-766-5466 instead of the correct format. It also generates the additional 48 after 800.
Please help, I've been working on this for many hours for my Java course homework but I can't figure out the problem.
import java.util.Scanner;
public class PhoneNumberConverter {
public static void main(String[] args) {
System.out.println("Enter a phone number to convert:");
Scanner input = new Scanner(System.in);
String phoneNumber = input.next();
input.close();
int firstGroup = translatePhoneNumber (phoneNumber, 0, 4);
System.out.print(firstGroup);
System.out.print("-");
int secondGroup = translatePhoneNumber (phoneNumber, 4, 6);
System.out.print(secondGroup);
System.out.print("-");
int thirdGroup = translatePhoneNumber (phoneNumber, 7, 10);
System.out.print(thirdGroup);
}
public static int translatePhoneNumber (String phoneNumber, int firstIndex, int lastIndex) {
int chartoNumber = 'A';
int currentIndex;
if (firstIndex != 0) {
for (currentIndex = firstIndex; currentIndex < lastIndex; currentIndex++) {
if (phoneNumber.charAt(currentIndex) == 'A' || phoneNumber.charAt(currentIndex) == 'B' || phoneNumber.charAt(currentIndex) == 'C' )
chartoNumber = 2;
else if (phoneNumber.charAt(currentIndex) == 'D' || phoneNumber.charAt(currentIndex) == 'E' || phoneNumber.charAt(currentIndex) == 'F' )
chartoNumber = 3;
else if (phoneNumber.charAt(currentIndex) == 'G' || phoneNumber.charAt(currentIndex) == 'H' || phoneNumber.charAt(currentIndex) == 'I' )
chartoNumber = 4;
else if (phoneNumber.charAt(currentIndex) == 'J' || phoneNumber.charAt(currentIndex) == 'K' || phoneNumber.charAt(currentIndex) == 'L' )
chartoNumber = 5;
else if (phoneNumber.charAt(currentIndex) == 'M' || phoneNumber.charAt(currentIndex) == 'N' || phoneNumber.charAt(currentIndex) == 'O' )
chartoNumber = 6;
else if (phoneNumber.charAt(currentIndex) == 'P' || phoneNumber.charAt(currentIndex) == 'Q' || phoneNumber.charAt(currentIndex) == 'R' || phoneNumber.charAt(currentIndex) == 'S' )
chartoNumber = 7;
else if (phoneNumber.charAt(currentIndex) == 'T' || phoneNumber.charAt(currentIndex) == 'U' || phoneNumber.charAt(currentIndex) == 'V' )
chartoNumber = 8;
else if (phoneNumber.charAt(currentIndex) == 'W' || phoneNumber.charAt(currentIndex) == 'X' || phoneNumber.charAt(currentIndex) == 'Y' || phoneNumber.charAt(currentIndex) == 'Z' )
chartoNumber = 9;
else
chartoNumber = phoneNumber.charAt(currentIndex);
System.out.print(chartoNumber);
}
} else {
for (currentIndex = firstIndex; currentIndex < lastIndex; currentIndex++) {
chartoNumber = phoneNumber.charAt(currentIndex);
char numbeeer = (char) chartoNumber;
System.out.print(numbeeer);
}
}
return chartoNumber;
}
}
Firstly note that you are printing out your result in the translatePhoneNumber method itself, you there is not need to print out the result again.
Get rid of System.out.print(firstGroup); etc.
Second, if (firstIndex != 0) { - why? Note that you are doing translatePhoneNumber (phoneNumber, 0, 4); so firstIndex will be 0
Personally I would just pass the substring to the method and loop for each char.
translatePhoneNumber (phoneNumber.substring (0, 4));
....
for (char c : localPhoneNumber) {
// your mapping
}
Related
I have to write a program that takes a String as user input and then prints a substring that starts with the first vowel of the String and ends with the last. So for instance if my String is : "Hi I have a dog named Patch", the printed substring would be : "i I have a dog named Pa"
This is the code I have now:
import java.util.Scanner;
import java.util.*;
public class SousChaineVoyelle {
private static Scanner sc;
public static void main (String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = sc.nextLine();
int pos1 = 0;
int pos2 = 0;
int i;
int j;
boolean isVowel1 = false;
boolean isVowel2 = false;
for (i = 0; i < str.length(); i++){
if (str.charAt(i) == 'A' || str.charAt(i) == 'a' ||
chaine.charAt(i) == 'E' || str.charAt(i) == 'e' ||
str.charAt(i) == 'I' || str.charAt(i) == 'i' ||
str.charAt(i) == 'O' || str.charAt(i) == 'o' ||
str.charAt(i) == 'U' || str.charAt(i) == 'u' ||
str.charAt(i) == 'Y' || str.charAt(i) == 'y'){
isVowel1 = true;
break;
}
}
if (isVowel1){
pos1 = str.charAt(i);
}
for (j = str.length() - 1; j > i; j--){
if (str.charAt(j) == 'A' || str.charAt(j) == 'a' ||
str.charAt(j) == 'E' || str.charAt(j) == 'e' ||
str.charAt(j) == 'I' || str.charAt(j) == 'i' ||
str.charAt(j) == 'O' || str.charAt(j) == 'o' ||
str.charAt(j) == 'U' || str.charAt(j) == 'u' ||
str.charAt(j) == 'Y' || str.charAt(j) == 'y'){
isVowel2 = true;
break;
}
}
if (isVowel2){
pos2 = str.charAt(j);
}
String sub = chaine.substring(pos1, pos2);
System.out.print(The substring from the first vowel to the last is "\"" + sub +"\"");
}
}
this got me this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.lang.String.checkIndex(String.java:4557)
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
at java.base/java.lang.String.charAt(String.java:1515)
at SousChaineVoyelle.main(SousChaineVoyelle.java:33)
One way of looking at it is you have a lot of code to do a simple thing, which means more chances for bugs and errors.
Here's a "less code" solution:
str = str.replaceAll("(?i)^[^aeiou]*|[^aeiou]*$", "");
See live demo.
This works by matching all leading and trailing non-vowels (if any) and replacing them with nothing, effectively deleting them.
(?i) makes the match case insensitive.
After the first for loop, i will be str.length() no matter what. You may want to create another variable to hold I when it's found to remedy this.
I'm working on a priority queue for my homework and I need to call on methods from another class to identify if a word starts with a vowel, letter , or other character. I have tested them inside and outside the class but it only seems to not work when I input a temp variable that uses toString() to convert and object into a string. For some reason the startsWithVowel always returns false and startsWithLetter always returns true.
public static boolean startsWithVowel(String input) {
char W = input.charAt(0);
if ((W == 'a') || (W == 'e') || (W == 'i') || (W == 'o') || (W == 'u') || (W == 'A') || (W == 'E') || (W == 'I') || (W == 'O') || (W == 'U')) {
return true;
}
else {
return false;
}
}
public static boolean startsWithLetter(String input) {
char W = input.charAt(0);
if ((W == 'a')|| (W == 'b') || (W == 'c') || (W == 'd') || (W == 'e') || (W == 'f') || (W == 'g') || (W == 'h') || (W == 'i') || (W == 'j') || (W == 'k') || (W == 'l') || (W == 'm') || (W == 'n') || (W == 'o') || (W == 'p') || (W == 'q') || (W == 'r') || (W == 's') || (W == 't') || (W == 'u') || (W == 'v') || (W == 'w') || (W == 'x') || (W == 'y') || (W == 'z') || (W == 'A')|| (W == 'B') || (W == 'C') || (W == 'D') || (W == 'E') || (W == 'F') || (W == 'G') || (W == 'H') || (W == 'I') || (W == 'J') || (W == 'K') || (W == 'L') || (W == 'M') || (W == 'N') || (W == 'O') || (W == 'P') || (W == 'Q') || (W == 'R') || (W == 'S') || (W == 'T') || (W == 'U') || (W == 'V') || (W == 'W') || (W == 'X') || (W == 'Y') || (W == 'Z')) {
return true;
}
else {
return false;
}
}
public void enqueue(Word newEntry,int prio) {
Node<Word> newNode = new Node<Word>(newEntry,prio);
String temp = newNode.toString();
if (Words.startsWithLetter(temp)) {
if (Words.startsWithVowel(temp)) {
newNode.setPriority(1);
}
else {
newNode.setPriority(2);
}
}
else {
newNode.setPriority(3);
}
if(isEmpty()) {
firstNode = newNode;
lastNode= newNode;
numberOfElements++;
}
else {
// if (newNode.getPriority()) {}
lastNode.setNext(newNode);
lastNode = newNode;
numberOfElements++;
}
}
As I said before I can call the both the methods in other classes but only in the line of code above does it not return the right values. When I test it in my main class every input comes out with priority 2 even though I can test the same words in the actual class and it returns the right values.
EDIT:
So the problem is toString() converting the object to a string that says "hw4.WordPriorityQueue$Node#16f65612". What do I need to do to override toString() to say what I am putting into the object?
I suppose you would like to get back, what's in newEntry. The toString() probably returns with something else, if Node is a built in class. (Although i haven't checked in this specific case.) You might try to print out the return value of newNode.toString(). (Or check the documentation/implementation.)
You need to override the toString() method in your Node class. Otherwise It will always return something like Node#4c203ea1 which is just the name of the class and its hashcode.
Also you can make your methods a little bit more elegant like this:
public static List<Character> vowels = Arrays.asList('a','e','i','o','u','A','E','I','O','U');
public static boolean startsWithVowel(String input) {
return vowels.contains(input.charAt(0));
}
Look, I have pasted the whole code for you will understand the problem only when you see the whole code. Coming to my problem I want this program to take he strings until I want It to stop
Look i tried many loops thought upon it for hours and i would be glad if you help me in this issue
import java.util.*;
class secretopencoding
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String a = sc.nextLine();
int l = a.length();
int i;
char b;
for (i=0;i<l;i++)
{
b = a.charAt(i);
if (b=='a'||b=='A')
System.out.print("01");
if (b=='b'||b=='B')
System.out.print("02");
if (b=='c'||b=='C')
System.out.print("03");
if (b=='d'||b=='D')
System.out.print("04");
if (b=='e'||b=='E')
System.out.print("05");
if (b=='f'||b=='F')
System.out.print("06");
if (b=='g'||b=='G')
System.out.print("07");
if (b=='h'||b=='H')
System.out.print("08");
if (b=='i'||b=='I')
System.out.print("09");
if (b=='j'||b=='J')
System.out.print("10");
if (b=='k'||b=='K')
System.out.print("11");
if (b=='l'||b=='L')
System.out.print("12");
if (b=='m'||b=='M')
System.out.print("13");
if (b=='n'||b=='N')
System.out.print("14");
if (b=='o'||b=='O')
System.out.print("15");
if (b=='p'||b=='P')
System.out.print("16");
if (b=='q'||b=='Q')
System.out.print("17");
if (b=='r'||b=='R')
System.out.print("18");
if (b=='s'||b=='S')
System.out.print("19");
if (b=='t'||b=='T')
System.out.print("20");
if (b=='u'||b=='U')
System.out.print("21");
if (b=='v'||b=='V')
System.out.print("22");
if (b=='w'||b=='W')
System.out.print("23");
if (b=='x'||b=='X')
System.out.print("24");
if (b=='y'||b=='Y')
System.out.print("25");
if (b=='z'||b=='Z')
System.out.print("26");
if (b==' ')
System.out.print("27");
}
}
}
every time It will ask me If i Want to enter the program and continue the lop of running till enter no continue till i enter no
You have to iterate what you already have until user stop it. To do that you can use a while to iterate, and to stop it you can set a key that if it is introduced as input it will stop the program. Then the condition to stop the while loop will be that input.equals(stopKey).
I have commented the new lines
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a;
// key that indicates the program to stop
String stopKey = "stop";
System.out.println("Enter a string");
while (!(a = sc.nextLine()).equals(stopKey)) { // when input is equal to key, it stops
// nothing changed here ...
int l = a.length();
int i;
char b;
for (i = 0; i < l; i++) {
b = a.charAt(i);
if (b == 'a' || b == 'A')
System.out.print("01");
if (b == 'b' || b == 'B')
System.out.print("02");
if (b == 'c' || b == 'C')
System.out.print("03");
if (b == 'd' || b == 'D')
System.out.print("04");
if (b == 'e' || b == 'E')
System.out.print("05");
if (b == 'f' || b == 'F')
System.out.print("06");
if (b == 'g' || b == 'G')
System.out.print("07");
if (b == 'h' || b == 'H')
System.out.print("08");
if (b == 'i' || b == 'I')
System.out.print("09");
if (b == 'j' || b == 'J')
System.out.print("10");
if (b == 'k' || b == 'K')
System.out.print("11");
if (b == 'l' || b == 'L')
System.out.print("12");
if (b == 'm' || b == 'M')
System.out.print("13");
if (b == 'n' || b == 'N')
System.out.print("14");
if (b == 'o' || b == 'O')
System.out.print("15");
if (b == 'p' || b == 'P')
System.out.print("16");
if (b == 'q' || b == 'Q')
System.out.print("17");
if (b == 'r' || b == 'R')
System.out.print("18");
if (b == 's' || b == 'S')
System.out.print("19");
if (b == 't' || b == 'T')
System.out.print("20");
if (b == 'u' || b == 'U')
System.out.print("21");
if (b == 'v' || b == 'V')
System.out.print("22");
if (b == 'w' || b == 'W')
System.out.print("23");
if (b == 'x' || b == 'X')
System.out.print("24");
if (b == 'y' || b == 'Y')
System.out.print("25");
if (b == 'z' || b == 'Z')
System.out.print("26");
if (b == ' ')
System.out.print("27");
}
// ask for a new input
System.out.println("\nEnter a string");
}
// at this point user have enter the stop key
System.out.println("Stoped. Bye!");
// close the Scanner
sc.close();
}
I have been stuck for quite some time. I would need to ignore digits entered, blank spaces and special characters like $^%##&! and just read the other letters a-z, using Character.isDigit & Character.isLetter.. I have tried using the both methods, it didn't work out for me.. Please advice..
The error:
The normal output (without spaces and digits) :
The expected output should be 438-5626 even when I entered 123$#GetLoan.. They should ignore the first few characters '123$#' and read only GetLoan..
Full Question: Write a program that prompts the user to enter a telephone number expressed in letters and outputs the corresponding telephone number in digits. If the user enters more than seven letters, then process only the first seven letters. Also output the – (hyphen) after the third digit. Allow the user to use both uppercase and lowercase letters as well as spaces between words.
public class Question3 {
public static void main(String[] args) {
String letters;
char phoneDigit;
Scanner kb = new Scanner(System.in);
System.out.println("Enter letters : ");
letters = kb.next();
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
if (Character.isLetter(phoneDigit) == true) {
if (i == 3) {
System.out.println("-");
} //If
if (phoneDigit >= 'A' && phoneDigit <= 'C'
|| phoneDigit >= 'a' && phoneDigit <= 'c') {
System.out.println("2");
} else if (phoneDigit >= 'D' && phoneDigit <= 'F'
|| phoneDigit >= 'd' && phoneDigit <= 'f') {
System.out.println("3");
} else if (phoneDigit >= 'G' && phoneDigit <= 'I'
|| phoneDigit >= 'g' && phoneDigit <= 'i') {
System.out.println("4");
} else if (phoneDigit >= 'J' && phoneDigit <= 'L'
|| phoneDigit >= 'j' && phoneDigit <= 'l') {
System.out.println("5");
} else if (phoneDigit >= 'M' && phoneDigit <= 'O'
|| phoneDigit >= 'm' && phoneDigit <= 'o') {
System.out.println("6");
} else if (phoneDigit >= 'P' && phoneDigit <= 'S'
|| phoneDigit >= 'p' && phoneDigit <= 's') {
System.out.println("7");
} else if (phoneDigit >= 'T' && phoneDigit <= 'V'
|| phoneDigit >= 't' && phoneDigit <= 'v') {
System.out.println("8");
} else if (phoneDigit >= 'W' && phoneDigit <= 'Z'
|| phoneDigit >= 'W' && phoneDigit <= 'z') {
System.out.println("9");
} // If
} // If
} // For loop
} //PSVM
Below fragment is probably the problem:
for (int i = 0; i < 7; i++) {
phoneDigit = letters.charAt(i);
if (Character.isLetter(phoneDigit) == true) {
You are taking first 7 characters, and printing only the ones that are letters. So for input string 123getloan you will iterate over 123getl, and then isLetter will reject 123, so your program later will deal only with getl.
To iterate over only 7 letters you would need to change it to increment i only if given character is a letter e.g. by doing the below:
int i = 0;
for (char phoneDigit : letters.toCharArray()) {
if (Character.isLetter(phoneDigit)) {
i++;
// other ifs here
if (i == 3) {
System.out.println("-");
}
}
if (i >= 7) {
break;
}
}
EDIT: Fixed problem mentioned by #Andreas
This lab for my intro class requires us to return any user input in pig latin.
The error I seem to keep getting when I run it and type any string into the console is this:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
The error is found here:
thisWord = x.substring(indexOfCurrentNonLetter +1, indexOfNextNonLetter);
I understand from another post this is the problem:
IndexOutOfBoundsException -- if the beginIndex is negative, or endIndex is >larger than the length of this String object, or beginIndex is larger than >endIndex.
Actually, your right edge of your substring function may be lower than the left >one. For example, when i=(size-1) and j=size, you are going to compute >substring(size-1, 1). This is the cause of you error. (Answer By Bes0ul)
My question is, what is the solution to this problem?
Here are the methods I am using:
public String pigLatin(String x)
{
String thisWord = "";
x += " ";
int indexOfNextNonLetter = 0, indexOfCurrentNonLetter = 0;
for(int i = 0; i < x.length(); i++)
{
System.out.println("At least the loop works"); //Let's play a game called find the issue
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122) //if it isn't a letter
{
phrase += x.charAt(i); // add our non character to the new string
for(int j = 0; j < x.substring(i).length(); j++) // find the next character that isn't a letter
{
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122)
{
indexOfNextNonLetter = j + i;
if(j+i > x.length())
System.out.print("Problem Here");
indexOfCurrentNonLetter = i;
System.out.println("noncharacter detected"); //I hope you found the issue
j = x.length();
thisWord = x.substring(indexOfCurrentNonLetter +1, indexOfNextNonLetter);//between every pair of nonletters exists a word
}
}
phrase += latinWord(thisWord); // translate the word
i = indexOfNextNonLetter - 1;
}
}
return phrase;
}
/*
* This converts the passed word to pig latin
*/
public String latinWord(String word)
{
String lWord = "";
String beforeVowel = "";
String afterVowel = "";
boolean caps = false;
char first = word.charAt(0);
if(first > 'A' && first < 'Z')
{
first = Character.toLowerCase(first); //If the first char is capital, we need to account for this
caps = true;
}
if(containsNoVowels(word))
lWord = Character.toUpperCase(first) + word.substring(1) + "ay"; //If we have no vowels
if(word.charAt(0) == 'A' || word.charAt(0) == 'a' || word.charAt(0) == 'E' || word.charAt(0) == 'e' || word.charAt(0) == 'I' || word.charAt(0) == '0'
|| word.charAt(0) == 'O' || word.charAt(0) == 'O' || word.charAt(0) == 'o' || word.charAt(0) == 'U' || word.charAt(0) == 'u')
{
lWord = Character.toUpperCase(first) + word.substring(1) + "yay"; //If the first char is a vowel
}
if(word.charAt(0) != 'A' || word.charAt(0) != 'a' || word.charAt(0) != 'E' || word.charAt(0) != 'e' || word.charAt(0) != 'I' || word.charAt(0) != '0'
|| word.charAt(0) != 'O' || word.charAt(0) != 'O' || word.charAt(0) != 'o' || word.charAt(0) != 'U' || word.charAt(0) != 'u')
{ //If the first letter isnt a vowel but we do have a vowel in the word
for(int m = 0; m < word.length(); m++)//if we have a vowel in the word but it doesn't start with a vowel
{
if(word.charAt(m) == 'A' || word.charAt(m) == 'a' || word.charAt(m) == 'E' || word.charAt(m) == 'e' || word.charAt(m) == 'I' || word.charAt(m) == 'm'
|| word.charAt(m) == 'O' || word.charAt(m) == 'O' || word.charAt(m) == 'o' || word.charAt(m) == 'U' || word.charAt(m) == 'u')
{
for(int l = 0; l < word.substring(m).length(); l++)
{
afterVowel += word.substring(m).charAt(l); //Build the part after the first vowel
}
m += word.length();
}
else
beforeVowel += word.charAt(m);
}
if(caps == false)
lWord = afterVowel + beforeVowel + "ay";
else
{
first = Character.toUpperCase(afterVowel.charAt(0));
}
}
return lWord;
}
/*
* This function checks the string letter by letter to see if any of the letters are vowels.If there are none it returns true
*/
public boolean containsNoVowels(String wrd)
{
for(int h = 0; h < wrd.length(); h++)
{
if(wrd.charAt(h) == 'A' || wrd.charAt(h) == 'a' || wrd.charAt(h) == 'E' || wrd.charAt(h) == 'e' || wrd.charAt(h) == 'I' || wrd.charAt(h) == 'h'
|| wrd.charAt(h) == 'O' || wrd.charAt(h) == 'O' || wrd.charAt(h) == 'o' || wrd.charAt(h) == 'U' || wrd.charAt(h) == 'u')
return false;
else
return true;
}
return false;
}
I think the error lies inside your second for loop within pigLatin():
for (int j = 0; j < x.substring(i).length(); j++) // find the next character that isn't a letter
{
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122)
The last line shown above starts checking at char i. This is the same char you just checked in the outer loop. So the test will succeed. And I think the logic breaks down either in this iteration or a subsequent one.
I think what you want is:
for(int j = 1; j < x.substring(i).length(); j++)
{
if (x.charAt(j) < 65 || x.charAt(j) > 90 && x.charAt(j) < 97 || x.charAt(j) > 122)
Note, there are two changes:
Initialise j at 1 to test the next character in the for statement
Test the jth character, not the ith in the if statement