【问题标题】:Why am I getting an Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12 error?为什么我在线程“main”java.lang.StringIndexOutOfBoundsException 中出现异常:字符串索引超出范围:12 错误?
【发布时间】:2015-10-18 20:10:30
【问题描述】:
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)

你好,

我已经阅读过一个错误,这是一种可能性。不过,我已经尽我所能地弄乱了我的代码,结果并没有什么不同。我从 correctFormat 方法中删除了最后一个 while 循环;但是,我被提示输入我的名字,然后程序停止了。我什至在 convertPhoneNumber 方法的末尾输入了一个额外的消息框,以查看是否由于某种原因没有返回字符串,但我也没有得到任何结果。我知道这是一个常见问题,但从我所读到的内容来看,我仍然没有解决这个问题。不过,这只是我写的第五或第六个程序,所以我并没有太慌张。只是有人将我指向正确的道路,如果我来回写它们,我不会介意它们会有所帮助。格拉西亚斯,

安迪`

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

【问题讨论】:

标签: string phone-number outofrangeexception


【解决方案1】:

在您的 while 循环中,将其更改为

while (ch != ' ') 

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

【讨论】:

  • 为什么我的大脑很难理解兰迪?!我觉得我有能力编写像样的代码,但事情仍然让我着迷。 ch != ' ' 不应该捕获第一个空“值”并停止循环吗?为什么还需要 i
  • 我不确定,你可能是对的。但我觉得我已经到了这样的程度,它正在搜索电话号码中超出其索引的字符,这就是为什么你会得到一个例外。
  • 谢谢兰迪。这确实有道理。它处理了运行时错误。我仍然得到它询问我的名字,输入电话号码然后只是“停止运行”的行为。我将详细研究它,但对此的建议会有所帮助。您不必用勺子喂我,但对此的一些指导也会有所帮助。再次感谢 RandyFreak,AndyFreak
  • @FreakyRandy,我添加了你建议的代码,从 correctFormat 方法的末尾删除了 System.exit(0),并在 main 方法中放置了一个 Message 框,在对 correctFormat 的调用下显示我的用户名和输入的号码。消息框显示正确(这是我不明白的,因为我认为在调用 JOptionPane 类的每个方法的末尾都需要一个 System.exit(0) )。现在;但是,我遇到的问题是:
  • 线程“主”java.lang.OutOfMemoryError 中的异常:java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java) 处 java.util.Arrays.copyOf(Arrays.java:3332) 处的 Java 堆空间:137) 在 java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:121) 在 java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:622) 在 java.lang.StringBuilder.append(StringBuilder.java:202) 在 TelephoneNumberTranslator .convertPhoneNumber(TelephoneNumberTranslator.java:185) 在 TelephoneNumberTranslator.main(TelephoneNumberTranslator.java:29)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 2013-01-20
相关资源
最近更新 更多