Home > other >  Is there a better way to write this simple rock, paper, scissors game in Java? [closed]
Is there a better way to write this simple rock, paper, scissors game in Java? [closed]

Time:10-06

I was just bored and am wondering if there is a more efficient way to write this. I feel like I can get rid of a lot of the content and make it simpler. I am in college as a freshman and am a Computer Science student and was practicing a little. Thanks!

import java.util.ArrayList;
import java.util.Random;

public class Choices{
    String result;
    public String makeList(String pick){
        ArrayList<String> a = new ArrayList<String>();
        Random rand = new Random();
        if (pick.equals("Rock")){
           a.add("Paper");
           a.add("Scissors");
        }
        if (pick.equals("Paper")){
           a.add("Rock");
           a.add("Scissors");
        }
        if (pick.equals("Scissors")){
           a.add("Paper");
           a.add("Rock");
        }
        result = a.get(rand.nextInt(a.size()));
        return result;
    }
    private String decision;
    private boolean check;
    public void checkWin(String user, String cpu){
        if(user.equals("Rock") && cpu.equals("Scissors")){
            check = true;
        }
        if(user.equals("Rock") && cpu.equals("Paper")){
            check = false;
        }
        if(user.equals("Paper") && cpu.equals("Scissors")){
            check = false;
        }
        if(user.equals("Paper") && cpu.equals("Rock")){
            check = true;
        }
        if(user.equals("Scissors") && cpu.equals("Rock")){
            check = false;
        }
        if(user.equals("Scissors") && cpu.equals("Paper")){
            check = true;
        }
        if(check){
            System.out.println("You have won!");
        }
        else{
            System.out.println("You have lost!");
        }
        
    }
    }

CodePudding user response:

You could create a HashMap<String, String>() and map each value to the key that it loses against. Then check :

Map<String, String> map = new HashMap<String, String>();

map.put("rock" ,"scissors");
map.put("scissors", "paper");
map.put("paper" , "rock");

if(user.equals(cpu)) //tie
if(map.get(user).equals(cpu)) // user wins

// the only other case is that the cpu wins

CodePudding user response:

Well...

You could use or statements. Like:

if (user.equals("Paper") && cpu.equals("Rock") || user.equals("Rock") && cpu.equals("Scissors") || user.equals("Scissors") && cpu.equals("Paper") {
   check = true;
   System.out.println("You have won!");
} else {
   check = false;
   System.out.println("You have lost!");
}

Oh yeah. In the makeList() method, I would just remove the string from the list. Like this:

ArrayList<String> a = new ArrayList<String>();
a.add("Rock");
a.add("Paper")
a.add("Scissors");
a.remove(pick);
return a.get(new Random().nextInt(a.size) - 1);

Overall though, good question!

  •  Tags:  
  • java
  • Related