What do you mean by "reduce the size"? Code or byte-code?If it's code you can easily remove a few lines by merging your System.out.print*()
:
System.out.printf("Wins: %d %.2f%%\nLosses: %d %.2f%%\nDraws %d %.2f%%", wins, winP, losses, loseP, draws, drawP);
Also, what is the use of transforming Integer
into a String
for the switch()
? switch()
on String
was introduced in Java 7. A better-optimized version would be to use int
directly:
int choice = random.nextInt(3); // (n-1) 0 = rock, 1 = paper, 2 = scissorsswitch (choice) { case 0: ...}
You can also have a String[]
to store what you want to display:
String[] rps = { "rock", "paper", "scissors" };if (choice >= 0 && choice < rps.length) System.out.println("Computer chose "+rps[choice]);else System.out.println("Wrong choice!");// Or use ternary operator://System.out.println(choice >= 0 && choice < rps.length ? "Computer chose "+rps[choice] : "Wrong choice!");
For byte-code size you can use primitive int
instead of class Integer
. And also int
for your wins
, losses
, draws
and games
variables: ++
incrementation is a lot faster on int
than on double
. You can convert them to double
only when computing the percentage (and correct a potential percentage calculation bug when using integer arithmetics):
loseP = 100.0 * losses / games; // 100.0 is a double, so 100.0 * losses is a double and (100.0 * losses) / games is also a double// loseP = losses/games*100 will always be an int: losses and games are int, losses/games is an int, 100 is an int and losses/games*100 is an int
I'll let you figure out the rest :)