Untitled
unknown
plain_text
7 days ago
3.0 kB
7
Indexable
Never
package rockpaperscissors2; import static java.lang.Math.random; import java.util.Scanner; public class RockPaperScissors2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] choices = new String[3]; choices[0] = "paper"; choices[1] = "scissors"; choices[2] = "rock"; int totalCoins = 0; int round = 0;// Round counter boolean again = false; do { round++; //Increment the round counter // random index (for the computer) int rand = (int) (random() * 3); System.out.print("Enter your choice (paper/scissors/rock): "); String input = in.nextLine(); System.out.printf("The computer choice is: %s\n", choices[rand]); //determine the result int idx = rand; for (int i = 0; i < 3; i++) { if(i == rand) continue; if(compareStrings(input,choices[i])) idx = i; } // //generate 2 random number as the coin rewards if(rand-idx==-1||rand-idx==2){ int earnedCoins1= (int) (Math.random() * 10 + 1); int earnedCoins2= (int) (Math.random() * 10 + 1); int earnedCoins= Math.addExact(earnedCoins1,earnedCoins2); totalCoins += earnedCoins; System.out.println("The player wins"); System.out.println (" Congratulation, you have won " +earnedCoins + " coins! "); } else if (rand == idx) { System.out.println("Tie"); again = true; } else { System.out.println("The Computer wins"); System.out.println (" Oh no ! Try again."); //Ask if the player wants to play again whenever after losing System.out.println (" continue playing? (yes/no)"); String choose = in.nextLine(); if ("yes".equals(choose)){ System.out.println ("Let's play again"); }else { System.out.println("Thanks for playing!"); System.out.println("Total coins collected is" + totalCoins + "coins"); System.out.println("Total rounds played: " + round); in.close(); return; } } //Display total coins and rounds after each round System.out.println("Total coins collected:" + totalCoins); System.out.println("Total rounds played: " + round); } while (again); System.out.println("Total rounds played: " + round); } public static boolean compareStrings (String a, String b) { int sz1 = a.length(), sz2 = b.length(); if(sz2!=sz1) return false; for (int i = 0; i < sz1; i++) { if(a.charAt(i)!=b.charAt(i)) return false; } return true; } }
Leave a Comment