Adele McKenney
Adele McKenney

Reputation: 27

Return type void/method alternatives?

I'm a beginner programmer and don't completely understand methods and how they function. I'm attempting to make a program that does rock paper scissors, and the program chooses one randomly and then asks the user for input. What I'm having trouble with is the method. My code is below, and the error I'm getting is that I can't return values for a void method, but I don't know what else I could do to make it work. Any suggestions would be appreciated!

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];
        }

Upvotes: 0

Views: 4562

Answers (2)

F. Knorr
F. Knorr

Reputation: 3055

You could try this:

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] );     
  }

Regarding your question: rand.nextInt() will most likely return a value larger than 3 (= size of your array). Note that for an array of length, only 0, 1, ..., n-1 are valid indices.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

return is for returning from the method in which return is.

In this case, I guess you want to store the selected value to somewhere and use it later in the same method.

Try this:

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);
  }
}

This code will eliminate the error, but this code has a big chance of printing null and is not a good code.

If you want to use return, you can put it in another method.

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
  }
}

Upvotes: 1

Related Questions