好的,我试图想一下如何测试从Java中的方法返回的字符串。我知道我无法测试一个字符串,但我对如何更改返回以使其能够将其作为char或其他不同的东西进行测试感到困惑。
这就是问题,我似乎无法过去。
if(flip().equals("Heads")) {
headsCount++;
}
完整代码
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many times should I flip the coin? ");
int headsCount = 0;
int flips = input.nextInt();
for(flips = flips; flips >= 1; flips--) {
flip();
}
if(flip().equals("Heads")) {
headsCount++;
}
System.out.println(headsCount);
}
public static int flip() {`enter code here`
int rand = (int) (Math.random() * 2);
if (rand == 1) {
System.out.println("Heads");
}
if (rand != 1){
System.out.println("tails");
}
return rand;
}
答案 0 :(得分:0)
将flip
方法更改为:
public static String flip() {
int rand = (int) (Math.random() * 2);
String result = null;
if (rand == 1) {
System.out.println("Heads");
result = "Heads";
}
if (rand != 1){
System.out.println("tails");
result = "tails";
}
return result;
}
然后,将for
循环更改为以下内容:
for(flips = flips; flips >= 1; flips--) {
String result = flip();
if("Heads".equals(result)) {
headsCount++;
}
}
答案 1 :(得分:0)
public static void main(String[] args) {
System.out.println("How many times should I flip the coin? ");
Scanner input = new Scanner(System.in);
int headsCount = 0;
int flips = input.nextInt();
for(int flips = flips; flips >= 1; flips--) {
flip();
}
if(flip() == true) {
headsCount++;
}
System.out.println(headsCount);
}
public static boolean flip() {
int rand = (int) (Math.random() * 2);
if (rand == 1) {
System.out.println("Heads");
return true;
}
if (rand != 1){
System.out.println("tails");
return false;
}
}
所以你甚至不需要比较字符串
答案 2 :(得分:0)
应该是这样的:
//variable ensures that we are not testing a separate flip all the time
int result = flip();
if (result == 1) {
headscount++;
} else {
tailscount++;
}
你检索随机的方法很糟糕......很有可能是它的尾巴
Random random = new Random();
//from + random.nextInt(to - from + 1)
//0 + random.nextInt(1-0+1)
int result = random.nextInt(2);
你的for循环正在运行一个进程,然后在你的for循环之外,你正在测试单个翻转是否是头部,这与头部/尾部结果的概率和翻转的其余部分完全无关。
for(int x = 0; x < flips; x++) {
//variable ensures that we are not testing a separate flip all the time
int result = flip();
if (result == 1) {
headscount++;
} else {
tailscount++;
}
}