Java修改硬币翻转

时间:2018-03-29 17:04:17

标签: java

嗨,我需要一些帮助,我一直收到2个小错误

C:\Users\ez\Documents\HoustonJacoriemodifiedCoin.java:16: error: illegal start of expression
                    public Coin();
                    ^
C:\Users\ez\Documents\HoustonJacoriemodifiedCoin.java:38: error: invalid method declaration; return type required
                    public Coin(String s)
                           ^
2 errors

Tool completed with exit code 1

我的实际代码是:

public class ModifiedCoin {
  private String sideUp;
  {
    Random rc = new Random();
    public Coin();
    {
      int rg = rc.nextInt(2);
      if(rg == 0)
        sideUp = "Heads";
      else sideUp = "Tails";
    }
  }
  public void toss() {
    int rg = rc.nextInt(2);
    if(rg == 0)
      sideUp = "Heads";
    else
      sideUp = "Tails";
  }
  public String getSideUp() {
    return sideUp;
  }
  public Coin(String s) {
    sideUp = s;
  }
}

2 个答案:

答案 0 :(得分:1)

所以问题是你在一个名为Coin.java的文件中使用构造函数。您可能希望将HoustonJacoriemodifiedCoin.java重命名为Coin.java,并可能将该类从公共类HoustonJacoriemodifiedCoin重命名为公共类Coin。

在大多数情况下,您的文件名,公共类*和构造函数都是相同的名称。

另外,我同意另一个回答说删除第一个分号。以下是这些更改的示例(在名为HoustonJacoriemodifiedCoin .java的文件中):

import java.util.Random;

public class HoustonJacoriemodifiedCoin {
  private String sideUp;
  private Random rc = new Random();

  public HoustonJacoriemodifiedCoin()
  {
    int rg = rc.nextInt(2);
    if(rg == 0)
      sideUp = "Heads";
    else
    sideUp = "Tails";
  }
  public HoustonJacoriemodifiedCoin(String s) {
    sideUp = s;
  }

  public void toss() {
    int rg = rc.nextInt(2);
    if(rg == 0)
      sideUp = "Heads";
    else
      sideUp = "Tails";
  }
  public String getSideUp() {
    return sideUp;
  }

  public static void main(String ... args) {
    HoustonJacoriemodifiedCoin c = new HoustonJacoriemodifiedCoin();
    c.toss();
    System.out.println(c.getSideUp());
    c.toss();
    System.out.println(c.getSideUp());
    c.toss();
    System.out.println(c.getSideUp());
    c.toss();
    System.out.println(c.getSideUp());
  }
}

答案 1 :(得分:0)

这是更正后的代码:

public class ModifiedCoin { private String sideUp; Random rc = new Random(); public ModifiedCoin () { int rg = rc.nextInt(2); if(rg == 0) sideUp = "Heads"; else sideUp = "Tails"; } public void toss() { int rg = rc.nextInt(2); if(rg == 0) sideUp = "Heads"; else sideUp = "Tails"; } public String getSideUp() { return sideUp; } public ModifiedCoin (String s) { sideUp = s; } }