Home > other >  Is there a cleaner method to this?
Is there a cleaner method to this?

Time:01-25

public class ChartData {
    //lv22 double charts
    public String[] walkInThePark = {"CanCan", "Cleaner", "Meteo5cience", "FFF22", "Wedding Crasher", "Hyponosis22", "Redline", "1950", "Monolith", "Just hold on", "Revolution", ""};
    //lv23 double charts
    private String[] timeToSuffer = {"Travel To Future", "Nililism", "Creed", "HTTP", "Cross Over", "Final Autition 2-1", "Love is a Danger Zone", "Gargoyle", "Broken Karma", "BS Explosion", "Windmill", "Prime Time", "Clematis", "Nyar", "Your Mind", "D&D", "Red Snow", "Stardream", "Crossing Delta", "Video Out C"};
    //lv24 double charts
    private String[] chooseDeath = {"la Cinq", "Gloria", "Vanish", "Harma", "Conflict", "Sarabande", "Bedlam", "Final Audition", "Achluoias", "FFF24", "Full moon", "Full moon FULL", "Annihilator", "Creed FULL", "BrainPower", "lolite", "Dement", "Destri", "Cross Soul", "TFTMN FULL", "Errorcode", "Dignity", "A Site De La Rue", "Trashy", "Paved Garden", "V3"};

    Random r = new Random();
    Scanner sc = new Scanner(System.in);

    public void select(){


        do{
            System.out.println("Please choose from the following: \n 1. WalkInThePark(lv22 double charts) \n 2. timeToSuffer(lv23 Double Charts) \n 3. chooseDeath(lv24 double charts)");
            int select = sc.nextInt();

            switch (select){
                case 1:
                    System.out.println("That's sorta weak, my dude... :");
                    chill();
                    break;
                case 2:
                    System.out.println("I see you:");
                    suffer();
                    break;
                case 3:
                    System.out.println("You decided to not B**** out. Here's your list:");
                    death();
                    break;
            }

        }while(true);



    }


    public void chill(){

        Set<String> set = new HashSet<>();
        for(int i = 0 ; i < 4 ; i  ){
            int r_int = r.nextInt(11);
            String chooseChill = (walkInThePark[r_int]);
            if(!set.contains(chooseChill)){
                set.add(chooseChill);
                System.out.println(chooseChill);
            }else{
                i--;
                continue;
            }

        }

    }

    public void suffer(){

        Set<String> set = new HashSet<>();
        for(int i = 0 ; i < 4 ; i  ){
            int r_int = r.nextInt(19);
            String chooseSuffer = (timeToSuffer[r_int]);
            if(!set.contains(chooseSuffer)){
                set.add(chooseSuffer);
                System.out.println(chooseSuffer);
            }else{
                i--;
                continue;
            }

        }

    }

    public void death(){

        Set<String> set = new HashSet<>();
        for(int i = 0 ; i < 4 ; i  ){
            int r_int = r.nextInt(26);
            String chosenDeath = (chooseDeath[r_int]);
            if(!set.contains(chosenDeath)){
                set.add(chosenDeath);
                System.out.println(chosenDeath);
            }else{
                i--;
                continue;
            }


        }



    }





}

Look at method chill, Void, and Suffering. Excuse me if I'm not explaining this correctly. Is there a cleaner way to do this without copying and pasting the same thing?!

CodePudding user response:

The first step is to realize that the parameter of r.nextInt does not need to be hardcoded. The values you are using (11, 19, 26) correspond to the arrays's lengths. Thus, you can get them from the respective array, such as walkInThePark.length.

More importantly, you can extract the identical code and then pass in the data that make them different:

void doTheThing(String[] target) {
    Set<String> set = new HashSet<>();
    for(int i = 0; i < 4; i  ){
        int r_int = r.nextInt(target.length-1);
        String choice = (target[r_int]);
        if(!set.contains(choice)){
            set.add(choice);
            System.out.println(choice);
        } else {
            i--;
            continue;
        }
    }

And then call that function like this:

public void chill(){
    doTheThing(walkInThePark);
}

public void suffer(){
    doTheThing(timeToSuffer);
}

CodePudding user response:

The only ways in which your chill(), suffer() and death() functions differ are in the range of the random integer as well as the array used (chooseDeath, timeToSuffer or walkInThePark), both of which you could pass to the function as an argument instead to unify them into one function.

CodePudding user response:

This is what function parameters are for.

You can pass the array you want to choose from to a function, and since Java arrays are objects than know their own length, you don't need to wright the length out manually.

Since f1sh already fixed your code with minimum changes, I will give you a slightly different solution, that does not involve changing a for loop counter inside the loop (which is usually considered a bad practice), and will allow you to easily select different number of random items:

private void chooseSomeRandoms(String [] from, int howMany) {
    List<String> strs = Arrays.asList(from);
    Collections.shuffle(strs);

    for (int i = 0; i < howMany; i  ) {
        System.out.println(strs.get(i));
    }
}

And here is how you call it:

chooseSomeRandoms(walkInThePark, 4);
chooseSomeRandoms(timeToSuffer, 4);
chooseSomeRandoms(chooseDeath, 4);

If you ever want more or less than 4 choices, replace the last parameter.

If you IDE does not do it automatically, add :

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

to the top of your file.

How it works:

The first line converts your simple array to a dynamic List that can be rearranged.

The second line shuffles this list, so you get all your options in random order (this does not effect the original array, so you can do this as many times as you like).

Then you just print the first 4 (or how many you want) items, and you are done!

You may also want to add a check to make sure howMany is between 0 and from.length like so:

if (howMany < 0 || howMany >= from.length) {
    System.out.println("Invalid number of items!");
    return;
}

CodePudding user response:

package com.company;

import java.util.*;

public class Main {

    public static void main(String[] args) {

        ChartData chartData= new ChartData();
        chartData.select();
    }
    public static class ChartData {
        //lv22 double charts
        public String[] walkInThePark = {"CanCan", "Cleaner", "Meteo5cience", "FFF22", "Wedding Crasher", "Hyponosis22", "Redline", "1950", "Monolith", "Just hold on", "Revolution", ""};
        //lv23 double charts
        private  String[] timeToSuffer = {"Travel To Future", "Nililism", "Creed", "HTTP", "Cross Over", "Final Autition 2-1", "Love is a Danger Zone", "Gargoyle", "Broken Karma", "BS Explosion", "Windmill", "Prime Time", "Clematis", "Nyar", "Your Mind", "D&D", "Red Snow", "Stardream", "Crossing Delta", "Video Out C"};
        //lv24 double charts
        private  String[] chooseDeath = {"la Cinq", "Gloria", "Vanish", "Harma", "Conflict", "Sarabande", "Bedlam", "Final Audition", "Achluoias", "FFF24", "Full moon", "Full moon FULL", "Annihilator", "Creed FULL", "BrainPower", "lolite", "Dement", "Destri", "Cross Soul", "TFTMN FULL", "Errorcode", "Dignity", "A Site De La Rue", "Trashy", "Paved Garden", "V3"};

        Random r = new Random();
        Scanner sc = new Scanner(System.in);
        public void select() {
            do {
                System.out.println("Please choose from the following: \n 1. WalkInThePark(lv22 double charts) \n 2. timeToSuffer(lv23 Double Charts) \n 3. chooseDeath(lv24 double charts)");
                int select = sc.nextInt();
                List<String> arrayToGo = null;

                switch (select) {
                    case 1:
                        System.out.println("That's sorta weak, my dude... :");
                        arrayToGo = Arrays.asList(walkInThePark);
                        break;
                    case 2:
                        System.out.println("I see you:");
                        arrayToGo = Arrays.asList(timeToSuffer);
                        break;
                    case 3:
                        System.out.println("You decided to not B**** out. Here's your list:");
                        arrayToGo = Arrays.asList(chooseDeath);
                        break;
                }
                operation(arrayToGo);
            } while (true);
        }

        public void operation(List<String> data) {
            data = new ArrayList<>(data);
            for (int i = 0; i < 4; i  ) {
                String chooseChill = data.remove(r.nextInt(data.size()));
                System.out.println(chooseChill);
            }
        }
    }
}

Or with streams:

 public void select() {
            Stream.generate(() -> {
                        System.out.println("\n Please choose from the following: \n 1. WalkInThePark(lv22 double charts) \n 2. timeToSuffer(lv23 Double Charts) \n 3. chooseDeath(lv24 double charts)");
                        return sc.nextInt();
                    })
                    .map(select -> {
                        switch (select) {
                            case 1:
                                System.out.println("That's sorta weak, my dude... :");
                                return Arrays.asList(walkInThePark);
                            case 2:
                                System.out.println("I see you:");
                                return Arrays.asList(timeToSuffer);
                            case 3:
                                System.out.println("You decided to not B**** out. Here's your list:");
                                return Arrays.asList(chooseDeath);
                        }
                        throw new RuntimeException("incorrect choice");
                    })
                    .map(ArrayList::new)
                    .flatMap(data -> IntStream.range(0, 4)
                            .boxed()
                            .map(operand -> data.remove(r.nextInt(data.size()))))
                    .forEach(System.out::println);
        }

https://www.online-java.com/axXlIVWTUk

  •  Tags:  
  • Related