我获得了一个测试驱动开发任务的测试套件。该程序播放Rock,Paper,Scissors游戏,我还获得了实际程序的骨架代码。我不应该更改测试套件,而是我必须更改,或者在实际程序中生成代码以便测试通过。我在通过getInput方法时遇到了问题。 这是实际程序的代码:
public static char getInput(String prompt, char[] options, Scanner sc) {
// getInput method
// prompts user for an input that matches one of the given characters
// if its not one of those, repeat. (use contains (above))
char c;
boolean flag = false;
do {
c = sc.next().charAt(0);
if (contains(c, options)) {
System.out.println(prompt + " ( y, n, q ):");
flag = true;
}
}
while (!flag);
return c;
}
这是测试套件中测试getInput方法的方法:`
private static void testGetInput() {
OutputStream out;
out = resetSystemOut();
assert 'y' == RPS.getInput("Choose", new char[] {'y','n','q'}, new Scanner("y\n"));
assertOutput("Choose ( y, n, q ):\n", out);
out = resetSystemOut();
assert 'n' == RPS.getInput("Alice", new char[] {'y','n','q'}, new Scanner("n\n"));
assertOutput("Alice ( y, n, q ):\n", out);
out = resetSystemOut();
assert 'q' == RPS.getInput("Bob", new char[] {'y','n','q'}, new Scanner("q\n"));
assertOutput("Bob ( y, n, q ):\n", out);
out = resetSystemOut();
assert 'q' == RPS.getInput("Cloe", new char[] {'y','n','q'}, new Scanner("x\nw\nq\n")); //line 81
assertOutput("Cloe ( y, n, q ):\n" +
"Cloe ( y, n, q ):\n" +
"Cloe ( y, n, q ):\n", out);
out = resetSystemOut();
assert 'v' == RPS.getInput("Doug", new char[] {'v'}, new Scanner("vvvv\nv\n"));
assertOutput("Doug ( v ):\n" +
"Doug ( v ):\n", out);
}
这是我得到的错误:
Exception in thread "main" java.lang.AssertionError: 54 18
Cloe ( y, n, q ):
Cloe ( y, n, q ):
Cloe ( y, n, q ):
Cloe ( y, n, q ):
at RPSTester.assertOutput(RPSTester.java:226)
at RPSTester.testGetInput(RPSTester.java:81)
at RPSTester.main(RPSTester.java:25) //line 25 has a call to the testGetInput method
我在办公时间拜访了导师,但在揭示问题的全部答案之前,他只能告诉我。我会感谢任何帮助,暗示,指出我的错误;任何事情都表示赞赏。
答案 0 :(得分:0)
你应该做这样的事情
while(scanner.hasNext()) {
String input = scanner.next();
//check if input equals to y or n or q . If yes then break
// otherwise System.out.println(prompt + " ( y, n, q ):")
}
答案 1 :(得分:0)
您需要通过连接提示和选项中的字符来构建print语句,然后将该语句打印的次数与Scanner输入中的字符一样多。您可能必须调整新行字符\ n的追加以匹配您的测试断言。
这应该有所帮助:
public static char getInput(String prompt, char[] options, Scanner sc) {
// getInput method
// prompts user for an input that matches one of the given characters
// if its not one of those, repeat. (use contains (above))
char c;
boolean flag = false;
String printStr = prompt + " (";
for (int i = 0; i < options.length; i++) {
printStr += " " + options[i] + ",";
}
printStr = printStr.substring(0, printStr.length() - 1) + " ):\\n";
do {
c = sc.next().charAt(0);
System.out.println(printStr);
if (contains(c, options)) {
flag = true;
}
}
while (!flag);
return c;
}