public String simpleConditional(int price) {
String answer = null ;
price = 20;
if (price < 20)
System.out.println("Buying new shirt");
answer = "Buying new shirt"
ConditionalStatementsTest > simpleConditionalTest(int, String) > com.ata.ConditionalStatements
Test.simpleConditionalTest(int, String)[3] FAILED
org.opentest4j.AssertionFailedError: expected: <null> but was: <Buying new shirt>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.ata.ConditionalStatementsTest.simpleConditionalTest(ConditionalStatementsTest.j
我正试图与";回答";变量为";购买新衬衫"价值这就是我收到的断言错误代码和上面提到的代码。我该如何解决解决这个错误,在我看来是正确的。(这是一个家庭作业检查器程序(
从代码片段中可以清楚地看出,返回类型是"字符串"所以如果你想返回";买新衬衫"。
public String simpleConditional(int price) {
String answer = null;
price = 20;
if(price < 20) {
System.out.println("Buy new shirt");
answer = "buy new shirt";
return answer;
} else {
return "Something else";
}
}
它可能是这样的:
/**
* Assumes the monetary value supplied is a floating point value.
*
* @param price (double) Will return null if 0 or less is supplied.
*
* @return (String)
*/
public static String simpleConditional(double price) {
String answer = null;
if (price > 0d && price < 20d) {
System.out.println("Buy new shirt");
answer = "buy new shirt";
}
else if (price >= 20d && price < 80d) {
answer = "Hmmm...buying a decent shirt!";
}
else if (price >= 80d) {
answer = "Wow...Big Spender, buying a really good shirt!";
}
return answer;
}
要在类main()
方法中使用名为simpleConditional()
方法的方法,可以执行以下操作:
public static void main(String args[]) {
String anAnswer = simpleConditional(56.98);
System.out.println(anAnswer);
// The following will work to:
System.out.println(simpleConditional(104));
}