ERROR: This method must return a result of type int

前端 未结 5 1651
耶瑟儿~
耶瑟儿~ 2021-01-25 03:51

Code:

import java.util.*;

public class shuffleDeck
{ 
    public static int shuffleDeck (int[] deck, int theNumber)
    {
        int [] array1         


        
5条回答
  •  后悔当初
    2021-01-25 04:18

    Based on your main method, I suppose, that what you want is to shuffle the deck for the given count of times, for that you should update the method as follows:

    public static void shuffleDeck (int[] deck, int theNumber)
    {
        Random random = new Random();
        for (int k=0; k < theNumber; k++) {
            for (int i = deck.length, j, tmp; i > 1; i--) {
                j = random.nextInt(i);
    
                tmp = deck[i - 1];
                deck[i - 1] = deck[j];
                deck[j] = tmp;
            }
        }
    }
    

    for returning the number of how many times you actually did the shuffle doesn't make sense ... based on your input. The inner loop, as posted in https://stackoverflow.com/a/30757452/4234940 is only the shuffle itself... so actually I would change it like this:

    public static void shuffleDeck (int[] deck, int theNumber)
    {
        Random random = new Random();
        for (int k=0; k < theNumber; k++) {
            shuffle(deck, random);
        }
    }
    
    private static void shuffle(int[] array, Random random){
        for (int i = array.length, j, tmp; i > 1; i--) {
            j = random.nextInt(i);
    
            tmp = array[i - 1];
            array[i - 1] = array[j];
            array[j] = tmp;
        }
    }
    

提交回复
热议问题