0

我正在尝试在 Java 中进行简单的抛硬币模拟,并且在玩过初始化等之后,我无法让字符串端初始化被抛掷模拟覆盖。

    import java.util.*;

 public class Coin {
public static void main(String [] args)
{
    int randomNum = -1;
    String side = "";
    toss();
    sideUp(randomNum);
    getSideUp(side);
}

public static int toss()
{
    Random rn = new Random();
    int range = 2;
    int randomNum =  rn.nextInt(range);
    return randomNum;
}

public static String sideUp(int randomNum)
{
    String side;
    if (randomNum == 0)
        side = "heads";
    else
        side = "tails";
    return side;
}

public static void getSideUp(String side)
{
    System.out.println("The result is " + side + ".");
}

}
4

5 回答 5

2

您正在丢弃“折腾”方法的结果

看看如果你这样做会发生什么

int randomNum = toss();
于 2013-06-16T19:59:14.287 回答
2

side从中返回sideUp,但随后您不使用该返回值。您应该将其返回值分配sidemain. 你也对tosswith做同样的事情randomNum。请记住,当您将变量传递给函数的参数时,您看不到该函数对变量所做的更改。(嗯,这是一种简化,但可变性是一个不同的问题。)

于 2013-06-16T20:00:56.957 回答
0

这是一个:使 Random 成为类成员并且不要使用静态方法。

package random;

/**
 * Coin
 * @author Michael
 * @link http://stackoverflow.com/questions/17137118/initializing-and-passing-strings-in-java
 * @since 6/16/13 4:00 PM
 */

import java.util.Random;

public class Coin {

    public static final int MAX_VALUE = 2;
    public static final int HEADS_VALUE = 0;
    private final Random random;
    private int numHeads = 0;
    private int numTosses =0;

    public static void main(String[] args) {
        int maxTosses = (args.length > 0 ? Integer.valueOf(args[0]) : 10);
        Coin coin = new Coin();
        for (int i = 0; i < maxTosses; ++i) {
            System.out.println(coin.toss());
        }
        int numHeads = coin.getNumHeads();
        int numTosses = coin.getNumTosses();
        System.out.println(String.format("# heads : %d", numHeads));
        System.out.println(String.format("# tosses: %d", numTosses));
        System.out.println(String.format("%% heads : %10.3f", ((double)numHeads/numTosses)*100.0));
    }

    public Coin() {
        this.random = new Random();
    }

    public Coin(long seed) {
        this.random = new Random(seed);
    }

    public synchronized String toss() {
        int value = this.random.nextInt(MAX_VALUE);
        if (value == HEADS_VALUE) {
            ++numHeads;
        }
        ++numTosses;
        return (value == HEADS_VALUE ? "heads" : "tails");
    }

    public synchronized int getNumHeads() {
        return numHeads;
    }

    public synchronized int getNumTosses() {
        return numTosses;
    }
}
于 2013-06-16T20:00:41.377 回答
0

你可以这样做 -

getSideUp(sideUp(toss()));
于 2013-06-16T20:01:42.960 回答
0

像这样改变你的主要

 public static void main(String[] args) {

    int randomNum=toss();
   String side= sideUp(randomNum);
    getSideUp(side);
}
于 2013-06-16T20:06:06.183 回答