I am supposed to be writing the game of nim. I am having trouble finding out how to fix the compile error
cannot find symbol - method getPlayer()
Also, is this the only problem you see? Or are there other issues that would cause this program to fail to compile or work properly.
import java.util.Scanner;
import java.util.Random;
public class Nim {
private int n;
private int compMode;
private int numberLeft;
private int numberTaken;
private boolean whoseTurn;
private String inputName;
private String name;
private String play;
private boolean yes;
Scanner in = new Scanner(System.in);
Random num = new Random();
public void setState() {
numberLeft = 100;
numberTaken = numberLeft;
}
public String getPlayer() {
inputName = in.next("");
inputName = name;
return name;
}
public void getCompPlay() {
compMode = num.nextInt(2);
if (compMode == 0) System.out.println("The computer is in smart mode");
if (compMode == 1) System.out.println("The computer is in random mode");
}
public void playGame() {
if (whoseTurn == true) {
System.out.println(name + "It is your turn...");
System.out.printf("Please enter the number you wish to take from the pile (Must be less than " + (numberLeft / 2) + "): ");
numberTaken = in.nextInt();
numberLeft -= numberTaken;
System.out.println("The number left is " + numberLeft);
whoseTurn = false;
}
if (whoseTurn == false) {
System.out.println("It is the computer's turn...");
if (compMode == 0) {
numberLeft = smartComputer(numberLeft);
System.out.println("The number left is " + numberLeft);
}
if (compMode == 1) {
numberLeft -= num.nextInt(numberLeft / 2);
System.out.println("The number left is " + numberLeft);
}
whoseTurn = true;
return;
}
if (yes == true) {
}
if (numberLeft <= 1) {
if (whoseTurn = false) {
System.out.println("You Win!");
} else {
System.out.println("You're horrible...you lost to a computer.");
}
}
if (numberLeft <= 1) {
if (whoseTurn = false) {
System.out.println("You Win!");
} else {
System.out.println("you lost to a computer.");
}
}
}
public static int smartComputer(int num) {
int power = 2;
while (power < num) {
power *= 2;
}
power /= 2;
num = power - 1;
return num;
}
public boolean playAnother() {
System.out.println("/nPlay Again? (y/n)");
play = in.next("");
if (play.equalsIgnoreCase("y")) return true;
else return false;
}
public void displayTotals() {}
}
And here is my Tester
public class NimTester {
public static void header() {
System.out.println("Eric Magnusson");
System.out.println("AP Comp Sci");
System.out.println("Game of Nim (P6.16)");
}
public static void main() {
Nim nim = new Nim(getPlayer(), getCompPlay());
do {
nim.setState();
nim.playGame();
nim.printWinner();
} while (playAnother());
nim.displayTotals();
}
}
Your class either has no specific Constructor, or it is not shwon in your code. To learn more about Construcotrs, please read the documentation here. To put it simple, a Constructor is a method that allows the JVM to organize the memory and initialize the object.
The default object constructor is a non-argument constructor that sets each child variable the default value.
Example:
Class Car{
public Car(){
System.out.print("car is built.");
}
}
Car aCar = new Car();
What you have is Nim nim = new Nim(getPlayer(), getCompPlay()); therefore your Nimclass has to have a public Nim(String x, String y) method.
Another problem with the code shown is, you are using an object method to create the object...
Either the method has to be static (read about it here), or it has to not depend on the object you are creating. To simplify your program, just save that value before using it in a variable, then use that variable in the object construction. Or even create a staic method like: public static String getJohn(){return "John"}, and then your code will work past that point.
Other issues with the code are related to readability, please read on Java Naming conventions, on how to name your variables, they will help maintenance, as well as allow other programmers to assist you.
Related
In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
if (sideup == 1) {
return Coin.Head;
} else {
return Coin.Tail;
}
}
}
You can for example add two fields in your CoinToss class. Like int heads and int tails. Initialize them with 0 in the startGame() method. Then, in the tosscoin() method:
if (sideup == 1) {
heads++;
return Coin.Head;
} else {
tails++;
return Coin.Tail;
}
You can access these fields in the startGame() method and do whatever you want with them.
You could as well define these two variables directly in the startGame() method and increment them based on the type of Coin which you get from the tosscoin() method.
Below code should work. everytime it tosses, it stores the current value in a variable and compares it next time with the toss value.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private static int headCounter;
private static int tailCounter;
private static int previousToss;
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
headCounter = 0;
tailCounter = 0;
previousToss = 0;
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
Coin currentGuess;
if (sideup == 1) {
headCounter++;
currentGuess = Coin.Head;
} else {
tailCounter++;
currentGuess = Coin.Tail;
}
checkIfFlipped(sideup);
return currentGuess;
}
static void checkIfFlipped(int currentToss) {
if (currentToss != previousToss) {
if (currentToss == 0) {
System.out.println("Coin fliped from head to tail");
} else {
System.out.println("Coin fliped from tail to head");
}
}
previousToss = currentToss;
}
}
Im writing a program similar to a game called shut the box. The game asks the player to roll 2 die, and then the player chooses to cover both numbers individually (in the boolean array), or the total of the two.
I'm having difficulty returning two values of the int method roll() which is supposed to roll two die.
Heres my code for the main class:
public class clacker {
private int play;
private int die1;
private int die2;
private boolean[] table;
private final int high = 6;
private final int low = 1;
private int range;
public clacker()
{
range = high-low+1;
table = new boolean[13];
play = 0;
}
public void roll()
{
die1 = (int)(Math.random()*range+low);
die2 = (int)(Math.random()*range+low);
}
public void value(char ch)
{
if(ch == 'i' || ch == 'I')
{
table[die1] = true;
table[die2] = true;
displayBoard();
}
else if(ch == 'T' || ch == 't')
{
table[die1+die2] = true;
displayBoard();
}
else
{
roll();
}
}
public void displayBoard()
{
for(int i = 1; i<table.length; i++)
{
if(table[i] == false)
{
System.out.print(" " + i + " ");
}
else
{
System.out.print(" / ");
}
}
}
}
and for the test class:
public class clackerTest {
public static void main(String[] args) {
clacker oo = new clacker();
EasyReader kboard = new EasyReader();
System.out.println("Press anything to roll the dice. ");
char roll= kboard.readChar();
int dice1 = oo.roll();
int dice2 = oo.roll();
System.out.println("You rolled " + dice1 + " and a " + dice2 + "!");
System.out.println("Cover Individual or Total: (enter i or t)");
char roll2 = kboard.readChar();
}
}
Why don't you just roll() twice? Modify roll() to return one int.
public int roll() {
return (int)(Math.random()*range+low);
}
And now, from within clackerTest (java conventions dictates you name this ClackerTest):
int dice1 = oo.roll();
int dice2 = oo.roll();
Very simple problem that I can't seem to wrap my head around.
I'm writing a bicycle program that calculates MPH based on the cadence and gears set on the bike.
The gears that can be set are between 1-3 and the cadence is between 1-100.
TL;DR If a user enters a number outside of that range, I'm having trouble figuring out how to have the program prompt them again until they enter the correct range. I'm also having trouble figuring out how to get the entire BicycleTest program to loop over once the calculations are finished.
I looked up other questions and noticed a bunch of people talking about while loops, which I tried, but I must have done it incorrectly because it did not loop to the beginning. I'm leaving it at my original if-else loop but I would appreciate help on how to properly use a while loop for this situation.
Code below:
public class Bicycle
{
// instance variables declared private
private int gear;
private int cadence;
private int speed;
//accessor (get) method for gear
public int getGear()
{
return gear;
}
//set method for gear
public void setGear(int gear)
{
if (gear >=1 && gear <= 3)
{
this.gear = gear;
}
else
{
System.out.println ("Sorry, please enter a number between 1-3");
}
}
//accessor (get) method for cadence
public int getCadence()
{
return cadence;
}
//set method for cadence
public void setCadence(int cadence)
{
if (cadence >=1 && cadence <=100)
{
this.cadence = cadence;
}
else
{
System.out.println ("Sorry, please enter a number between 1-100");
}
}
//accessor (get) method for speed
public int getSpeed()
{
if (gear == 1)
{
return cadence / 12;
}
else if (gear == 2)
{
return cadence / 6;
}
else if (gear == 3)
{
return cadence / 4;
}
else
{
return 0;
}
}
} // end of main
and then here is the BicycleTest code:
import java.util.Scanner;
public class BicycleTest
{
public static void main(String[] args)
{
Bicycle bike = new Bicycle();
Scanner input = new Scanner(System.in);
System.out.println("Enter the gear :");
bike.setGear(input.nextInt());
System.out.println("Enter the cadence :");
bike.setCadence(input.nextInt());
int speed = bike.getSpeed();
System.out.println ("Your speed in MPH is: ");
System.out.println(speed);
}
}
Here's how to get what you want with a while loop. The secret sauce is the boolean flag that the loop depends on to know when to exit. That flag is only adjusted when the user input falls within the acceptable range.
Take note that the user input is assigned to a variable, just for the sake of clarity.
boolean badAnswer = true;
int gear = 0;
while(badAnswer)
{
System.out.println("Enter the gear :");
gear = input.nextInt();
if(gear > 0 && gear <= 3)
{
bike.setGear(gear);
badAnswer = false;
}
else
{
System.out.println("Please enter a value for gear between 1 and 3.");
}
}
If you want validation in your Bicycle class rather than in the driver program, you could put the range test inside setGear() and return a boolean value that would serve to set the exit condition of the while loop in your driver class.
public class Bicycle
{
// instance variables declared private
private int gear;
private int cadence;
private int speed;
//accessor (get) method for gear
public int getGear()
{
return gear;
}
//set method for gear
public boolean setGear(int gear)
{
if (gear >=1 && gear <= 3)
{
this.gear = gear;
return false;
}
else
{
System.out.println ("Sorry, please enter a number between 1-3");
return true;
}
}
//accessor (get) method for cadence
public int getCadence()
{
return cadence;
}
//set method for cadence
public boolean setCadence(int cadence)
{
if (cadence >=1 && cadence <=100)
{
this.cadence = cadence;
return false;
}
else
{
System.out.println ("Sorry, please enter a number between 1-100");
return true;
}
}
//accessor (get) method for speed
public int getSpeed()
{
if (gear == 1)
{
return cadence / 12;
}
else if (gear == 2)
{
return cadence / 6;
}
else if (gear == 3)
{
return cadence / 4;
}
else
{
return 0;
}
}
} // end of main
public class BicycleTest {
public static void main(String[] args) {
Bicycle bike = new Bicycle();
Scanner input = new Scanner(System.in);
int intGear = 0;
int intCadence=0;
do {
System.out.println("Enter the gear :");
intGear = input.nextInt();
} while(bike.setGear(intGear));
do {
System.out.println("Enter the cadence :");
intCadence = input.nextInt();
} while(bike.setCadence(intCadence));
int speed = bike.getSpeed();
System.out.println("Your speed in MPH is: ");
System.out.println(speed);
}
}
Use a while loop with a condition false loop through the fragment, to update the value store it in a variable, and return the variable once the condition for while loop is met!
import java.util.Random;
import java.lang.Math;
import java.lang.String;
public class GameOfNim
{
private int min,max;
private int turn;
private int firstturn;
private int stupid;
private int smart;
private int computer;
private int user;
private int first;
private int pile;
public GameOfNim(int min, int max ){
pile=(int)(Math.random()*max+min);
smart=(int)(Math.random()*100);
stupid=(int)(Math.random()*100);
System.out.println("Pile size is "+pile);
firstturn=(int)(Math.random()*100 + 1);
computer=0;
user=1;
if(firstturn>50)
{
firstturn=user;
}
else
{
firstturn=computer;
}
firstturn=turn;
}
public void play()
{
if(smart>50)
{
System.out.println("Computer is playing smart");
}
else
{
System.out.println("Computer is playing stupid");
}
if(firstturn==user)
{
System.out.println("You go first");
}
else
{
System.out.println("Computer goes first");
}
turn = firstturn;
while(pile-1>0)
{
if(turn==user)
{
String take = "How many marbles do you want to take away?";
System.out.println(take);
int take2 = Integer.parseInt(take);
while(take2>(int)(pile/2))
{
System.out.println("Only take away half or less from the pile");
take = "How many marbles do you want to take away?";
take2= Integer.parseInt(take);
}
pile= pile-take2;
System.out.println("There are "+pile+" marbles left");
turn=computer;
}
else
{
if(smart>50)
{
pile -= smartTake();
}
else
{
pile -= stupidTake();
}
turn = user;
}
}
}
private int smartTake()
{
int x = (int)(Math.random())*2-1;
int sMarbles= (int)Math.pow(2,x);
while (sMarbles > (.5 * pile) || sMarbles==0)
{
x = (int)(Math.random())*2-1;
sMarbles = (int)Math.pow(2,x);
}
System.out.println("The computer took away " + sMarbles +" marbles");
return sMarbles;
}
private int stupidTake(){
int stMarbles = pile/2;
while (stMarbles > (.5*pile) || pile==0)
{
stMarbles = pile/2;
}
System.out.println("The Computer took away " + stMarbles +" marbles");
return stMarbles;
}
}
this is my game of nim class
public class Project5
{
public static void main(String args[])
{
String k = "yes";
String str;
Scanner console = new Scanner(System.in);
System.out.print("Enter the minimum number of marbles in your pile: ");
int min = console.nextInt();
System.out.print("Enter the maximum number of marbles in your pile: ");
int max= console.nextInt();
GameOfNim game = new GameOfNim(min, max);
game.play();
System.out.println( " Thank you and good bye!");
}
}
and this is my driver class
for some reason everytime i run it it goes all the way to the point where it says "Computer goes first" then nothing else happens. im assuming its stuck in a loop but i cant seem to find out why. any help will be appreciated
I am trying to construct a rock paper scissors game that incorporates multiple classes together. I am struggling a lot with object oriented programming, and I cannot figure out how to correct my compiler error. Below is my code:
Main method:
import java.util.*;
public class RPSMain extends RPSPlayer{
RPSPlayer player = new RPSPlayer();
RPSGame gameObject = new RPSGame ();
public void main ()
{
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
System.out.print ("Number of Rounds: ");
int rounds = sc.nextInt();
//Call and process all of the methods found in RPSPlayer and RPSGame
for (int i = 0; i < rounds; i++){
int playerThrow = player.makeThrow();
int compThrow = gameObject.makeCompThrow();
int winner = gameObject.announceWinner (compThrow, playerThrow );
System.out.print (gameObject.bigWinner(winner, rounds));
}
//Final Output
System.out.print (gameObject.bigWinner(winner, rounds));
}
//accessor to return round to RPSGame
public int getRound (int round){
this.round = round;
return round;
}
}
Game method:
import java.util.*;
public class RPSGame extends RPSPlayer{
RPSPlayer player = new RPSPlayer();
RPSGame game = new RPSGame ();
RPSMain mainRPS = new mainRPS();
public void main (String args[]) {
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
int rounds = mainRPS.getRound(rounds);
}
//Random Throw Generator
public int makeCompThrow (){
int Max = 3;
int Min = 1;
int compThrow = Min + (int)(Math.random() * ((Max - Min) + 1));
return compThrow;
}
// Get the throw from the player in RPSPlayer
public int getPlayerThrow (){
RPSPlayer player = new RPSPlayer();
int getPThrow = player.makeThrow();
return getPThrow;
}
//Does all of the calculatoins and ouputs who threw what.
public int announceWinner (int compThrow, int getPThrow) {
int winner = 0;
if (getPThrow == 1){
System.out.println ("Player throws ROCK.");
}
else if (getPThrow == 2){
System.out.println ("Player throws PAPER.");
}
else if (getPThrow == 3){
System.out.println ("Player throws SCISSORS.");
}
if (compThrow == 1){
System.out.println ("Computer throws ROCK.");
}
else if (compThrow == 2){
System.out.println ("Computer throws PAPER.");
}
else if (compThrow == 3){
System.out.println ("Computer throws SCISSORS.");
}
if (getPThrow == compThrow){
winner = 3;
}
else if (getPThrow == 1 && compThrow == 3){
winner = 1;
}
else if (getPThrow == 1 && compThrow == 2){
winner = 2;
}
else if (getPThrow == 2 && compThrow == 1){
winner = 1;
}
else if (getPThrow == 2 && compThrow == 3){
winner = 2;
}
else if (getPThrow == 3 && compThrow == 1){
winner = 2;
}
else if (getPThrow == 3 && compThrow == 2){
winner = 1;
}
return winner;
}
//Final Output with imported values of 'rounds' and 'winner'
public int bigWinner (int winner, int rounds){
int tie = 0;
int playerWins = 0;
int compWins = 0;
if (winner == 1){
playerWins = playerWins + 1;
}
else if (winner == 0){
tie = tie + 1;
}
else if (winner == 3){
compWins = compWins + 1;
}
System.out.println ("You win " +playerWins+ ". Computer wins " +(compWins)+ ".");
if (playerWins > compWins){
System.out.print ("You win!");
}
if (playerWins < compWins){
System.out.print ("Computer wins!");
}
if (playerWins == compWins){
System.out.print ("It's a tie!");
}
return tie;
}
}
Player method:
import java.util.*;
public class RPSPlayer {
public void main (String args[]) {
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
}
//This method gets the throw, and loops if throw is not within 1 and 3
public int makeThrow (){
Scanner sc = new Scanner (System.in);
int playerThrow;
do{
System.out.print ("Enter your throw (1=Rock, 2=Paper, 3=Scissors)");
playerThrow = sc.nextInt();
} while (playerThrow > 3 && playerThrow < 1);
return playerThrow;
}
//Accessor method
public int getThrow (int playerThrow){
this.playerThrow = playerThrow;
return playerThrow;
}
}
When I attempt to compile any of the classes, the error refers to code found in the RPSPlayer class:
cannot find symbol - variable playerThrow
As I said before, my knowledge of object-oriented program is very weak. I'm not really sure why I'm getting this error, as int playerThrow is defined right above it. I am also unsure if there are additional flaws or errors within my code. One thing I particularly struggle with is the concept of static vs. non-static code, and when to use which and what can be used within them.
Suggestions are greatly appreciated. Thank you in advance.
You'll need to define the member variable, before you can assign a value to it. That's mandatory (obviously) for every class and every member variable.
Please add this to your class:
private int playerThrow;
Also, the function getThrow makes no sense. Getters return an already set value; setters are the one who actually give a value to your member variables. Do this instead:
public int getThrow()
{
return playerThrow;
}
public void setThrow(int playerThrow)
{
this.playerThrow = playerThrow;
}
Please note that this.playerThrow and playerThrow are not related in any way. this.playerThrow is a member variable of your class (defined as shown above) and playerThrow is a variable given as an argument to your method.
EDIT:
I'm addressing some more of your errors.
The problem you are referring to in your comment is because you are calling a constructor mainRPS while your class is called RPSmain. That's located here RPSMain mainRPS = new mainRPS(); in the RPSGame class, in the start. Please fix this to RPSMain mainRPS = new RPSMain();.
Please define private int round in your RPSMain class. That's the same error as your first one addressed.
Also, define int winner outside the for loop because you're using it outside your loop, as well. When you define a value inside a loop, it will be local to that loop and will get destroyed when the program exits the loop.