JAVA美国加拿大翻译

时间:2014-12-18 18:38:46

标签: java

我制作一个简单的程序来输入美式拼写并输出加拿大拼写。例如,荣誉 - >荣誉或颜色 - >颜色。工作,但不是所有的时间。我不知道为什么。

解决;它没有用,因为单个字符不喜欢这段代码 - > 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
  }
}

1 个答案:

答案 0 :(得分:2)

如果你有一个字符串(" a"例如)你会这样做会发生什么?

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

由于wordLength = 1,wordLength-2 = -1,它不是String的有效索引。

如果你这样做会出现同样的问题:

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

OR

str.charAt(wordLength - 1);

因为wordLength = 0

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

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