有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java返回类型void/方法替代方案?

我是一名初级程序员,不完全理解方法及其功能。我正在尝试制作一个制作石头剪刀的程序,程序会随机选择一个,然后要求用户输入。我遇到的问题是方法。下面是我的代码,我得到的错误是,我不能为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];
        }

共 (2) 个答案

  1. # 1 楼答案

    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
      }
    }
    
  2. # 2 楼答案

    你可以试试这个:

    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是有效的索引