我正在编写一个简单的程序来输入美国拼写并输出加拿大拼写。例如,荣誉->荣誉,或颜色->颜色。有效,但并非始终如此。我不知道为什么。

解决了;它不起作用,因为单个字符不喜欢此代码-> secondLastLetter = word.charAt(wordLength - 2);

这是完成的代码,可以使用完整的句子,要翻译的单词不能有后缀。

import java.io.*;
import java.util.*;

public class XXXXCanadian
{
  public static void main (String[] args) throws IOException
  {
    BufferedReader objReader = new BufferedReader (new InputStreamReader (System.in));

    String lowerInput = ""; // declaring variable to work outside the loop

    while (!lowerInput.equals("quit"))
    {
      System.out.print ("Please enter a sentence to translate (Enter 'quit' to leave)");
      String input = objReader.readLine ();

      lowerInput = input.toLowerCase(); // any form of "quit" will make the loop exit

      Translate newSentence = new Translate(input);
      String output = newSentence.getOutput();

      System.out.println (output); // printing output
    }
  }
}


class Translate
{
  // declaring variables
  private String word = "";
  private String newWord = "";
  private String line = "";
  private String output = "";
  private char lastLetter;
  private char secondLastLetter;
  private int wordLength;

  Translate(String l)
  {
    line = l;
    Translation();
    getOutput(); // accessor method
  }


  private void Translation()
  {
    Scanner freader = new Scanner(line);
    StringBuffer newPhrase = new StringBuffer ("");

    while (freader.hasNext())
    {
      String word = freader.next();
      wordLength = word.length(); // gets the length of each word

      if (wordLength >= 5)
      {
        lastLetter = word.charAt(wordLength - 1);
        secondLastLetter = word.charAt(wordLength - 2);

        if (secondLastLetter == 'o' && lastLetter == 'r') // last two letters must be "OR"
        {
          String word2 = word.substring(0, wordLength - 2); // extracts all letters but the "OR"
          newWord = word2.concat("our"); // adds "OUR" to the end of the word
        }
        else
        {
          newWord = word; // keeps the same word
        }
      }
      else
      {
        newWord = word;
      }

      newPhrase.append(newWord);
      newPhrase.append(' '); // add a space
      output = newPhrase.toString(); // convert back to a string
    }
  }

  String getOutput()
  {
    return output; // returns the whole output
  }
}

最佳答案

当您只有一个字符串(例如“ a”)并且执行此操作时,会发生什么?

String str = "a";
int wordLength = str.length();
str.charAt(wordLength - 2);


由于wordLength = 1,因此wordLength-2 = -1,这不是字符串的有效索引。

如果您这样做,将会出现相同的问题:

String str = "";
int wordLength = str.length();
str.charAt(wordLength - 2);


要么

str.charAt(wordLength - 1);


由于wordLength = 0

您需要做的是在继续之前检查wordLength:

int wordLength = input.length();
if(wordLength >= 5)
{
    // find last letters
    // do your check/replacement
}

关于java - JAVA美洲到加拿大的翻译,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27553455/

10-12 21:32