2015-10-18 35 views
0
at java.lang.String.charAt(String.java:658) 
at TelephoneNumberTranslator.correctFormat(TelephoneNumberTranslator.java:97) 
at TelephoneNumberTranslator.getPhoneNumber(TelephoneNumberTranslator.java:61) 
at TelephoneNumberTranslator.main(TelephoneNumberTranslator.java:22) 

你好,爲什麼我在線程「main」java.lang.StringIndexOutOfBoundsException:String index超出範圍:12錯誤?

我讀到過差一錯誤,這是一種可能性。儘管如此,我儘可能地用自己的代碼欺騙了我的代碼,結果並沒有什麼不同。我從correctFormat方法中刪除了最後一個while循環;然而,我被提示輸入我的名字,然後程序停止。我甚至在convertPhoneNumber方法的最後輸入了一個額外的消息框,以查看該字符串是否因爲某種原因沒有被返回,但是我沒有得到任何結果。我知道這是一個普遍的問題,但從我所讀到的內容來看,我仍然沒有把頭轉過來。但這只是我寫的第五或第六個程序,所以我不會太慌亂。只是有人指着我走在正確的道路上,如果我來回寫一下就不會介意,這會有所幫助。格拉西亞斯,

Andy`

import javax.swing.JOptionPane;        //Needed for user dialogue boxes 
import java.io.*;           //Needed for File I/O classes 
/* 
    PROGRAM: TelephoneNumberTranslator.java 
    Written by Andrew Sechrist 
    On 10/13/15 
    For CPS 121 - JAVA Programming 
    This program requests user input for their name and a telephone number that may be a combination of alphanumeric characters. 
    It checks the string for correctness and converts lower case alphabetic characters to upper case. It then outputs the data. 
*/ 

public class TelephoneNumberTranslator      //This line creates the class TelephoneNumberTranslator 
{ 
//This line creates the Main Method for the above class 
    public static void main(String[] args) throws IOException      
    {              //This line opens the body of the Main Method to begin creating the class 
     String userName;          //For the user's name; initialized with a call to method getName 
     String phoneNumber;         //To hold the value of the string phoneNumber 
     char eachSymbol;          //For a specific symbol from the phone number String 

     userName = getName();         //Calling the getName method to obtain the user's name 
     phoneNumber = getPhoneNumber();      //Calling the getPhoneNumber method to obtain the user's phone number input 

     /*Making sure the phone number is in the correct 
     format with a call to the correctFormat method*/ 
     String formattedPhoneNumber = correctFormat(phoneNumber); 

     //Converting the phone number correctly with a call to the convertPhoneNumber method 
     String convertedPhoneNumber = convertPhoneNumber(formattedPhoneNumber); 

     //Call method displayResults to display the results 
     displayResults(userName, formattedPhoneNumber, convertedPhoneNumber);    
    } 
/** 
     The getName method prompts the user to enter their name 
     It then returns their name to the main method 
     @return The name the user entered is returned 
    */ 

    public static String getName() 
    {              
     String name =           //For the user's name locally in the getName method 
     JOptionPane.showInputDialog("Please enter your name: "); 
     return name;            //Return the user's name    
    } 

    /** 
     The getPhoneNumber method prompts the user to enter a phone number 
     It then checks the phone number for correctness with a call to the correctFormat method 
     It finally returns the phone number to the main method 
     @param getPhoneNumber 
     @return The phone number the user entered is returned 
    */ 

    public static String getPhoneNumber() 
    {              
     String thisNumber =          //Get a phone number 
     JOptionPane.showInputDialog("You will be entering a telephone number.\n Make sure that it is in the format XXX-XXX-XXXX\n Any X can be any" + 
     " numer 0 to 9 inclusive\n or any alphabetical English letter A through Z inclusive.\n Please enter the telephone number: \n"); 
     String phoneNumber = correctFormat(thisNumber); 
     return phoneNumber;          //Return the phone number    
    } 
/** 
     The correctFormat method receives an argument of telephoneNumber from the getPhoneNumber method 
     It detects any format errors and prompts the user to correct them by inputting the phone number again 
     It finally returns the phone number input with any formatting errors corrected to the getPhoneNumber method 
     @param telephoneNumber 
     @return the user's inputted telephone number in the correct format 
    */ 

    public static String correctFormat(String telephoneNumber) 
    { 
     int firstHyphen = telephoneNumber.indexOf('-');   //Holds position of first hyphen 
     int secondHyphen = telephoneNumber.lastIndexOf('-');  //Holds position of second hyphen 
     int stringSize = telephoneNumber.length();    //Holds the length of the telephone number string 
     char symbol;            //To hold the referenced value in the present position of the telephoneNumber string 
     while (firstHyphen != 3 || secondHyphen != 7)   //A while loop to make sure that hyphens are placed correctly 
     { 
     telephoneNumber = 
      JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n It seems that you have misplaced or forgotten " + 
      "the hypens (-).\n They are necessary, so please re-enter a telephone number with them placed correctly: \n"); 
     } 
     while (stringSize > 12)         //A while loop to correct situations where there are not 12 characters in the string 
     { 
     telephoneNumber = 
      JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n Any X can be any numer 0 to 9 inclusive\n" + 
      "or any alphabetical English letter A through Z inclusive.\n Please re-enter a telephone number: \n"); 
     } 
     int i = 0;            //An accumulator variable 
     char ch = telephoneNumber.charAt(i);      //Holds the first char value in the phone number string 

     //A while loop to determine that values are either hyphens or letters or digits 
     while (ch != ' ') 
     { 
     ch = telephoneNumber.charAt(i);      //Holds the char value in the next position of the telephoneNumber string 
     if (ch != '-') 
     { 
      if (!Character.isLetterOrDigit(ch))    //Prints an error message if the char is not an English letter or digit 
      { 
       telephoneNumber = 
        JOptionPane.showInputDialog("The number you enter must be in the format XXX-XXX-XXXX\n Any X can be any numer 0 to 9 inclusive\n" + 
        "or any alphabetical English letter A through Z inclusive.\n Please re-enter a telephone number: \n"); 
      } 
     } 
     i++; 
     } 
     System.exit(0);           //Terminate JOptionPane's running thread 
     return telephoneNumber;         //Return a correctly formatted phone number       
    } 
/** 
     The correctFormat method receives an argument of telephoneNumber from the getPhoneNumber method 
     It detects any format errors and prompts the user to correct them by inputting the phone number again 
     It finally returns the phone number input with any formatting errors corrected to the getPhoneNumber method 
     @param telephoneNumber 
     @return the user's inputted telephone number in the correct format 
    */ 

    public static String convertPhoneNumber(String telephoneNumber) 
    { 
     StringBuilder sb = new StringBuilder();     /**Initializing a StringBuilder class object to hold all generated values 
                   in one accessable String*/ 
     int i = 0;            //An accumulator variable 
     char ch = telephoneNumber.charAt(i);      //Holds the first char value in the phone number string 
     while (ch != ' ')          //A while loop to determine whether there is another character to check    
     { 
     char symbol = telephoneNumber.charAt(i);    //To hold the referenced value in the present position of the telephoneNumber string 
     if (Character.isLetter(symbol))      //To convert lower case alphabetic values to upper case 
     { 
      char value = Character.toUpperCase(symbol); 
     }          
     if (symbol == '-') 
     { 
      sb.append(symbol);         //Hold the values of the characters in the String 
     } 
     else if (symbol == 'A' || symbol == 'B' || symbol == 'C' || symbol == '2') 
     { 
      symbol = 2; 
      sb.append(symbol); 
     } 
     else if (symbol == 'D' || symbol == 'E' || symbol == 'F' || symbol == '3') 
     { 
      symbol = 3; 
      sb.append(symbol); 
     } 
     else if (symbol == 'G' || symbol == 'H' || symbol == 'I' || symbol == '4') 
     { 
      symbol = 4; 
      sb.append(symbol); 
     } 
     else if (symbol == 'J' || symbol == 'K' || symbol == 'L' || symbol == '5') 
     { 
      symbol = 5; 
      sb.append(symbol); 
     } 
     else if (symbol == 'M' || symbol == 'N' || symbol == 'O' || symbol == '6') 
     { 
      symbol = 6; 
      sb.append(symbol); 
     } 
     else if (symbol == 'P' || symbol == 'Q' || symbol == 'R' || symbol == 'S' || symbol == '7') 
     { 
      symbol = 7; 
      sb.append(symbol); 
     } 
     else if (symbol == 'T' || symbol == 'U' || symbol == 'V' || symbol == '8') 
     { 
      symbol = 8; 
      sb.append(symbol); 
     } 
     else if (symbol == 'W' || symbol == 'X' || symbol == 'Y' || symbol == 'Z' || symbol == '9') 
     { 
      symbol = 9; 
      sb.append(symbol); 
     } 
     else if (symbol == '1') 
     { 
      symbol = 1; 
      sb.append(symbol); 
     } 
     else 
     { 
      symbol = 0; 
      sb.append(symbol); 
     } 
     } 
     JOptionPane.showMessageDialog(null, sb); 
     return sb.toString(); 
    } 


public static void displayResults(String userName, String formattedTelephoneNumber, String convertedTelephoneNumber) 
    { 
     JOptionPane.showMessageDialog(null, "Thank you for entering a phone number " + userName + ".\n The telephone number that you entered " + 
     "was: " + formattedTelephoneNumber + ".\n After replacing any letters that you entered to the correct keypad numbers\n your telephone " + 
     "is " + convertedTelephoneNumber + ".\n"); 

     System.exit(0);           //Terminate JOptionPane's running thread 
    } 
} 
+1

http://stackoverflow.com/help/mcve – Marged

回答

0

在你的while循環,從

while (ch != ' ') 

將其更改爲

while (ch != ' ' && i < telephoneNumber.length()-1) 
+0

爲什麼這對我的大腦來說很難理解蘭迪?我覺得我有能力寫出體面的代碼,但事情仍然讓我感到滿意。不應該ch!=''趕上第一個空的「值」並停止循環?爲什麼我還需要 andrews

+0

我不確定,你可能是對的。但我覺得我已經到了一個地步,它正在尋找一個超出其索引的電話號碼中的角色,這就是爲什麼你會得到一個例外。 –

+0

感謝蘭迪。這確實有道理。它處理運行時錯誤。我仍然得到它的行爲,要求我輸入姓名,輸入電話號碼,然後「停止跑步」。我會詳細介紹一下,但對此的建議將有所幫助。你不需要用勺子給我餵食,但是關於這點的一些指導也會有幫助。再次感謝RandyFreak,AndyFreak – andrews

相關問題