【问题标题】:Return type void/method alternatives?返回类型无效/方法替代?
【发布时间】:2016-08-09 07:14:14
【问题描述】:

我是一名初级程序员,并不完全了解方法及其功能。我正在尝试制作一个做石头剪刀布的程序,程序随机选择一个,然后要求用户输入。我遇到的问题是方法。我的代码在下面,我得到的错误是我无法为 void 方法返回值,但我不知道我还能做些什么来让它工作。任何建议将不胜感激!

public class RPS {

  public static void main (String[] args) {

    String[] list = {"rock", "paper", "scissors"}; 

    Random rand = new Random();
        int x = rand.nextInt();

        switch (x) {
            case 0: return list[0];
            case 1: return list[1];
            case 2: return list[2];
        }

【问题讨论】:

  • 为什么您认为退货会解决您的问题?问问自己:你想做什么?您想随机选择数组中的一个元素。所以搜索那个。

标签: java methods void return-type


【解决方案1】:

你可以试试这个:

public class RPS {

  public static void main (String[] args) {

    String[] list = {"rock", "paper", "scissors"}; 

    Random rand = new Random();
    int x = rand.nextInt();

    System.out.println( list[x%list.length] );     
  }

关于您的问题:rand.nextInt() 很可能会返回大于 3 的值(= 数组的大小)。请注意,对于长度数组,只有 0、1、...、n-1 是有效索引。

【讨论】:

  • 请注意3(List的大小)也是无效索引。
  • @MikeCAT:谢谢你的评论。我已经调整了答案。
【解决方案2】:

return 用于从return 所在的方法返回。

在这种情况下,我猜你想将选定的值存储到某个地方,然后以相同的方法使用它。

试试这个:

import java.util.Random;
public class RPS {

  public static void main (String[] args) {

    String[] list = {"rock", "paper", "scissors"}; 

    Random rand = new Random();
    int x = rand.nextInt();

    String hand = null;
    if (0 <= x && x <= 2) hand = list[x];
    // do something using hand
    System.out.println(hand);
  }
}

此代码将消除错误,但此代码很有可能打印null,并不是一个好的代码。

如果你想使用return,你可以换成别的方法。

import java.util.Random;
public class RPS {

  public static void main (String[] args) {

    String hand = selectHand();
    // do something using hand
    System.out.println(hand);
  }

  private static String selectHand() {
    String[] list = {"rock", "paper", "scissors"};

    Random rand = new Random();
    int x = rand.nextInt();

    switch (x) {
      case 0: return list[0];
      case 1: return list[1];
      case 2: return list[2];
    }
    return null; // you must return something everytime from non-void method
  }
}

【讨论】:

  • 这几乎总是返回 null。最好使用return list[random.nextInt(3)];
  • @AndyTurner 保持x的值应该不错,应该对游戏的判断有用。我同意你在selectHand() 中使用,它只返回字符串。
  • 很好,但您需要解决这样一个事实,即您应该期望在每 40 亿次调用中大约 3 次选择一个有效的数组索引。
猜你喜欢
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2022-12-30
  • 1970-01-01
  • 2012-02-07
  • 2013-02-24
  • 2019-02-21
相关资源
最近更新 更多