gpt4 book ai didi

JAVA 美式-加拿大式 翻译

转载 作者:行者123 更新时间:2023-11-30 03:37:13 24 4
gpt4 key购买 nike

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

已解决;它不起作用,因为单个字符不喜欢此代码 ->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);

由于字长 = 0

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com