Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please need help to correct this below Java code to compile correct, so the user can input number of sticks at the console. Thanks! import

Please need help to correct this below Java code to compile correct, so the user can input number of sticks at the console. Thanks! import java.util.Scanner;
public abstract class Main {
protected String name;
public Main(String name){
this.name = name;
}
public abstract int makeMove(int currentSticks);
}
class Computer extends Main {
public Computer(){
super("Computer");
}
@Override
public int makeMove(int currentSticks){
// Simple strategy: take a random valid amount (1 to half of the current sticks)
int max = currentSticks /2;
int move =(int)(Math.random()*(max -1+1))+1; // Random number between 1 and max
System.out.println(name +" takes "+ move +" stick(s).");
return move;
}
}
import java.util.Scanner;
class Human extends Main {
private Scanner scanner;
public Human(){
super("Human");
scanner = new Scanner(System.in);
}
@Override
public int makeMove(int currentSticks){
int move =0;
do {
System.out.println("Enter the number of sticks to take (1-"+(currentSticks /2)+"): ");
while (!scanner.hasNextInt()){
System.out.println("That's not a valid number!");
scanner.next(); // move on to the next input
}
move = scanner.nextInt();
} while (move <1|| move > currentSticks /2);
return move;
}
}
class Game {
private Main[] players = new Main[2];
private int sticks;
public Game(int sticks){
this.sticks = sticks;
players[0]= new Computer();
players[1]= new Human();
}
public void start(){
int currentPlayer =0;
while (sticks >1){
System.out.println("Current sticks: "+ sticks);
int move = players[currentPlayer].makeMove(sticks);
sticks -= move;
if (sticks <=1){
System.out.println(players[currentPlayer].name +" wins!");
break;
}
currentPlayer =(currentPlayer +1)%2; // Switch players
}
}
public static void main(String[] args){
if (args.length <1){
System.out.println("Please specify the initial number of sticks as a command-line argument.");
return;
}
int sticks = Integer.parseInt(args[0]);
Game game = new Game(sticks);
game.start();
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design Application Development And Administration

Authors: Mannino Michael

5th Edition

0983332401, 978-0983332404

Students also viewed these Databases questions

Question

How can you defend against SQL injection attacks?

Answered: 1 week ago