我正在为一个班级工作,我们将创建一个“多个Greeter”计划。以下是规格:
我遇到了getGreetings()
方法的问题,我必须返回一个字符串数组,其中包含可能已添加到greeter的任何问候语。我目前得到这个输出:
最后一行是有问题的输出。我需要它是添加的问候语的字符串值数组。我无法使用Arrays.toString()
,因为它需要返回String[]
,所以我才被正式难倒。
这是我的MultiGreeter类:
package edu.metrostate.ics240.p1.gaw886;
import java.util.Random;
public class MultiGreeter {
private static final int MAX_NUM_GREETINGS = 25;
private String defaultGreeting = "Hello";
private String defaultName = "World";
private String[] greetingList;
private int greetingCount;
private int maxGreets;
public MultiGreeter(){
greetingList = new String[MAX_NUM_GREETINGS];
greetingList[0] = defaultGreeting;
greetingCount = 1;
}
public MultiGreeter(int maxGreetings){
maxGreets = maxGreetings;
if (maxGreetings >= 0){
greetingList = new String[maxGreetings];
greetingList[0] = defaultGreeting;
greetingCount = 1;
}else{
throw new IllegalArgumentException(String.format("Negative value detected MultiGreeter(%s)", maxGreetings));
}
}
public int getMaxGreetings(){
return greetingList.length;
}
public int getNumGreetings(){
return greetingCount;
}
public Boolean addGreeting(String greeting){
if (greetingCount == maxGreets ) {
return false;
}else{
greetingList[greetingCount] = greeting;
greetingCount++;
return true;
}
}
public String[] getGreetings(){
String[] greetings = greetingList;
return greetings;
}
public String greet(String name){
int randomIdx = new Random().nextInt(greetingCount);
String randomGreeting = greetingList[randomIdx];
if (greetingCount == 1) {
return String.format("\"%s, %s!\"", defaultGreeting, name);
}else{
return String.format("\"%s, %s!\"", randomGreeting, name);
}
}
public String greet(){
int randomIdx = new Random().nextInt(greetingCount);
String randomGreeting = greetingList[randomIdx];
if (greetingCount == 1) {
return String.format("\"%s, %s\"", defaultGreeting, defaultName);
}else{
return String.format("\"%s, %s\"", randomGreeting, defaultName);
}
}
}
这是我的MultiGreeter测试类:
package edu.metrostate.ics240.ex1.tests.gaw886;
import edu.metrostate.ics240.p1.gaw886.MultiGreeter;
public class MultiGreeterTester {
public static void main(String[] args) {
MultiGreeter mg = new MultiGreeter();
MultiGreeter mg1 = new MultiGreeter(10);
mg.addGreeting("Bonjour");
mg.addGreeting("Vilkommen");
mg1.addGreeting("Namaste");
mg1.addGreeting("Hello");
mg1.addGreeting("Hello1");
mg1.addGreeting("Hello2");
mg1.addGreeting("Hello3");
System.out.println(mg.getMaxGreetings());
System.out.println(mg.getNumGreetings());
System.out.println(mg.greet());
System.out.println("\n");
System.out.println(mg1.getMaxGreetings());
System.out.println(mg1.getNumGreetings());
System.out.println(mg1.greet());
System.out.println(mg1.greet("Gabriel"));
System.out.println(mg1.getGreetings());
}
}
提前感谢您的帮助!