【问题标题】:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 for Pig Latin线程“main”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:Pig Latin 为 -1
【发布时间】:2020-09-28 01:03:29
【问题描述】:

我正在尝试制作一个程序,该程序将文本文件翻译成猪拉丁语。当我运行它时,它说线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1。你能帮我修一下吗。我会告诉你代码中不正确的部分。

public static void piglatenizeFile(String fileNameIn, String fileNameOut) 
   {
      Scanner infile = null;
      String g = "";
      String output = "";
      String eachLetter = "";
      int index= -1;
      String vowels = "aeiouAEIOU";
      try
      {
         infile = new Scanner(new File(fileNameIn));  
      }
      catch(IOException e)
      {
         System.out.println("oops");
         System.exit(0);   
      }
   
      PrintWriter outfile = null;
      try
      {
         outfile = new PrintWriter(new FileWriter(fileNameOut));
      }
      catch(IOException e)
      {
         System.out.println("File not created");
         System.exit(0);
      }
      while(infile.hasNext()){// while txt has next line
         String sentence = infile.nextLine();// looks at next line
         String[] word = sentence.split(" ");//splits sentence to array of words
         for(int i=0;i<word.length;i++){//goes through every word in the sentence
            g =word[i].replaceAll("[\\p{Punct}]+", "");// replaces all punctuation
            for(int t=0;t<g.length();t++){// goes through every letter in each word
               eachLetter = g.substring(t,t+1);// eachLetter= each letter in noPunct
               if(eachLetter == vowels){
                  index = t;
                  t = g.length();
               }
            }
            output = g.substring(index)+ g.substring(0,index)+"ay";//ERROR
            outfile.print(output+" ");
         }
         outfile.print("\n");
      }

      outfile.close();
      infile.close();
   }
}

【问题讨论】:

  • 不要使用==比较字符串。使用equals()。尽管在您的情况下,您应该像这样使用contains()if (vowels.contains(eachLetter))
  • 我建议使用 Scanner 和 Tokenizer 来处理“单词”,而不是使用 for 循环。

标签: java


【解决方案1】:

在 java 中,当您在查看字符串池的字符串上使用 == 时 (https://www.journaldev.com/797/what-is-java-string-pool) 所以 if(eachLetter == vowels){ 它始终为假,因此索引将始终保持在 -1,正如 JustAnotherDeveloper 所说,使用 equals 并且您的 if 条件将为真有时

【讨论】:

  • 在这种情况下,如果使用equals() 则不会为真,因为提供的代码会将单字符字符串与字符串“aeiouAEIOU”进行比较。正如我的评论所述,解决方案是使用contains()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2011-06-21
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2014-06-19
  • 2015-05-24
相关资源
最近更新 更多