Dustin Crawford
Initializing Integer Variable issue?
0 Answer(s)      3 years and 10 months ago
Posted in : Java Beginners

My program is supposed to take a phrase like you'd see on a TV commercial, for example: "Call 1-800-GETLOAN now to..." then take that phrase and convert it to its actual phone number. My problem is my integer variables (number0 - number6). It is forcing me to initialize them, yet they stay at 0 throughout the entire program. Also, any pointers on how to shorten/optimize the code are welcome. Code below.

public class Chapter5Problem5 {
public static void main(String[] args) {

    String inputPhrase;
    int number, number0 = 0, number1 = 0, number2 = 0, number3 = 0, number4 = 0,  number5 = 0, number6 = 0;
    int letterCount = 0;
    char letter;


            inputPhrase = JOptionPane.showInputDialog("Enter your phrase: ");


                for (letterCount = 0; letterCount >= 7; letterCount++) {
                    letter = inputPhrase.charAt(letterCount);
                    if (letter >= 'A' && letter <= 'C')
                        number = 2;
                    else if (letter >= 'D' && letter <= 'F')
                        number = 3;
                    else if (letter >= 'G' && letter <= 'I')
                        number = 4;
                    else if (letter >= 'J' && letter <= 'L')
                        number = 5;
                    else if (letter >= 'M' && letter <= 'O')
                        number = 6;
                    else if (letter >= 'P' && letter <= 'S')
                        number = 7;
                    else if (letter >= 'T' && letter <= 'V')
                        number = 8;
                    else if (letter >= 'W' && letter <= 'Z')
                        number = 9;


                if (letterCount == 0)
                    number = number0;
                else if (letterCount == 1)
                    number = number1;
                else if (letterCount == 2)
                    number = number2;
                else if (letterCount == 3)
                    number = number3;
                else if (letterCount == 4)
                    number = number4;
                else if (letterCount == 5)
                    number = number5;
                else if (letterCount == 6)
                    number = number6;


                    }

System.out.println("The phone number is "+number0+number1+number2+"-"+number3+number4+number5+number6);

    }

}

Advertisement
View Answers