【发布时间】:2018-03-16 12:55:00
【问题描述】:
我正在挑战在https://www.codewars.com/kata/reversed-words/train/java 反转给定句子,我已经设法将句子反转为预期但在他们的 JUnit 测试中遇到了一个小错误。 这是我将任何句子反转为预期结果的代码,例如
“最大的胜利是不需要战斗的胜利”
// 应该返回 "battle no requires which is the 胜利最大"
我的代码
public class ReverseWords{
public static String reverseWords(String sentence){
String reversedsentence ="";
for(int x=sentence.length()-1;x>=0;--x){ //Reversing the whole sentence
reversedsentence += sentence.charAt(x);
} //now you are assured the whole sentence is reversed
String[]words = reversedsentence.split(" "); //getting each word in the reversed sentence and storing it in a string array
String ExpectedSentence= "";
for(int y=0;y<words.length;y++){
String word =words[y]; //getting word by word in the string array
String reverseWord = "";
for(int j=word.length()-1;j>=0;j--){ /*Reversing each word */
reverseWord += word.charAt(j);
}
ExpectedSentence +=reverseWord + " "; //adding up the words to get the expected sentence
}
return ExpectedSentence;
}
}
还有JUnit测试代码
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void testSomething() {
assertEquals(ReverseWords.reverseWords("I like eating"), "eating like I");
assertEquals(ReverseWords.reverseWords("I like flying"), "flying like I");
assertEquals(ReverseWords.reverseWords("The world is nice"), "nice is world The");
}
}
错误出现了
> expected:<eating like I[ ]> but was:<eating like I[]>
有关错误的更多详细信息是
> org.junit.ComparisonFailure: expected:<eating like I[ ]> but was:<eating like I[]> at org.junit.Assert.assertEquals(Assert.java:115) at org.junit.Assert.assertEquals(Assert.java:144) at SolutionTest.testSomething(SolutionTest.java:10)
您只需点击此链接并粘贴我的代码,您将看到一个代码游乐场Train: Reversed Words |CodeWars
【问题讨论】:
-
循环结束后删除结尾空格字符。命名以大写字符开头的变量不遵守 Java 命名约定
-
@sarkasronie 对不起,我的错。
-
具体在哪里,我应该在哪里删除结束空格字符
标签: java