Friency Fernandez
Friency Fernandez

Reputation: 445

Replace a string with a new string on a condition

I'm making a program where a user inputs name, P, S or T, and number of rounds. It will then check if they are equal, or not (one wins depending on condition of choices? This is a rock, paper, scissors game). And then, if they are equal, I want it to print a replaced version of iChoice and iComputerChoice in the JOPtionPane. (Since in this case, it will only print P, S or T). These are the replacements:

"P" = "Paper" // "S" = "Scissors" // "T" = "Stone"

Below is the code block:

if(iComputerchoice.equals(iChoice))
        {
            JOptionPane.showMessageDialog (null, "Computer: " +iComputerchoice + "\n" + "" +iName + ": " + "" +iChoice + "\nIt's a tie!", "Result", JOptionPane.PLAIN_MESSAGE);
        }

Example: iComputerchoice = P iChoice = P

Computer = Paper // Your Name = Paper // It's a tie!

I know a way to do this but it's kinda long. I'm wondering if there's a shorter way to do this. Thanks!

Upvotes: 2

Views: 1788

Answers (2)

joey rohan
joey rohan

Reputation: 3566

Well I don't know it's a good/bad way, but was just curious so tried this out , you can use a HashMap to write your "keys" and display its value when needed.

Map<String,String> map=new HashMap();
  map.put("p","paper");
  map.put("t","Stone");
  map.put("s","Scissor");

A demo short example:

 Scanner scan=new Scanner(System.in);
   System.out.println("T-Stone..P-paper..S-Scissors..enter");
   String choice=scan.nextLine().toLowerCase().trim();

   Map<String,String> map=new HashMap();
   map.put("p","paper");
   map.put("t","Stone");
   map.put("s","Scissor");


   //s b p-> scissor beats paper   
     final   String test="s b p , t b s , p b t";
     String vals[]={"p","s","t"};

     String ichoice=vals[new Random().nextInt(3)+0];//((max - min) + 1) + min

     if(ichoice.equalsIgnoreCase(choice)){

         JOptionPane.showMessageDialog(null,"  Tie !!--"+map.get(ichoice));
         System.exit(1);
    }

      String match=ichoice+" b "+choice;

     if(test.contains(match))  
           JOptionPane.showMessageDialog(null,"  CPU Won!!--!"+map.get(ichoice));
     else
           JOptionPane.showMessageDialog(null,"  YOU Won!!--"+map.get(ichoice));

Upvotes: 0

Palo
Palo

Reputation: 1020

in many ways. For instance, write a method that will do the conversion for you:

private String convertChoice(String abbr)
{
   if (abbr.equals("T")) return "Stone";
   else if (abbr.equals("S")) return "Scissors";
   else return "Paper";
}

then use convertChoice(iChoice) instead of iChoice when updating the value in your JOptionPane.

Upvotes: 1

Related Questions