Elevator Simulator help in Java - java

I'm having trouble finishing a basic elevator simulator in Java. What I have so far is an option that lets the user input whether they want to choose a floor, to pull a fire alarm, or to quit the simulation. When they choose select floor, they can pick any floor from 1 to 100, except 13. What I can't figure out how to do is to get the simulation to track their current floor so that they can go down. This is what I have so far:
public class Elevator {
public Elevator() {}
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else if (newFloor <= 100 && newFloor > 0 && newFloor != 13) {
for (int i = 1; i <= newFloor; i++)
System.out.println("..." + i);
System.out.println("Ding!");
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
}
Also, would it be helpful to post my other class for this program?

The Elevator should have a currentFloor field, like so:
private int currentFloor;
Then, in selectFloor, you need to find the direction. Also, in selectFloor, the else if is unnecessary.
public class Elevator {
private int currentFloor;
public Elevator() {
currentFloor = 0;
}
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else { // The if was not necessary
int direction = 0;
if(currentFloor < newFloor){
direction = 1; // going up;
} else if (currentFloor > newFloor) {
direction = -1; //going down;
} else {
direction = 0; //going nowhere;
}
for (; currentFloor != newFloor; currentFloor += newFloor)
System.out.println("..." + i);
System.out.println("Ding!");
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
}
Note: I haven't tested this yet, so I can't be sure it's correct.

Give your Elevator object a class variable by adding a private int floor; directly under the class opening tag. (Above the Elevator class constructor.) This variable will be tied directly to the Elevator object that contains it.
That way when you create your Elevator by using new Elevator you'll also have an int value always available to hold the floor. To access this value, build a getter and setter method. They should look like the following:
public void setFloor(int floor) {
this.floor = floor;
}
public int getFloor() {
return floor;
}
You can then call these two methods to set the floor number and get the floor number. To keep track, in your selectFloor method you'll need to use setFloor and pass it the floor number after a valid selection is made. You could then use getFloor to determine whether it would be going up or down.
To have your constructor set the floor variable at 1 when a new Elevator object is created. Simply change your constructor to look like this:
public Elevator() {
setFloor(1);
}
Hope this helps! If you have any questions on how those things are working let me know, I'll try to provide more details.

I just inserted a new method called backToBasement() and tied it into your selectFloor() method. Hope its helpful.
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter the floor you'd like to go to ==> ");
newFloor = scnr.nextInt();
if (newFloor > 100 || newFloor < 0 || newFloor == 13) {
System.out.println("Invalid selection");
}
else if (newFloor <= 100 && newFloor > 0 && newFloor != 13) {
for (int i = 1; i <= newFloor; i++)
System.out.println("..." + i);
System.out.println("Ding!");
backToBasement(newFloor);
}
}
public void fireAlarm() {
System.out.println("Danger, you must exit the building now!");
}
public void backToBasement(int newFloor){
for (int i=newFloor; i>0;i--){
System.out.println("..." + i);
}
System.out.println("Ding!... Back to Ground Level");
}

Related

Using more than one condition at the same time in if else statements [duplicate]

This question already has answers here:
How to use greater than and less than in a single if statement in Java
(2 answers)
Closed 4 years ago.
I have a question involving if else statements using Java. I'm stuck on how to put two conditions within the parenthesis or if that is even possible?
So far this is my code:
public class rollerCoaster {
int age = 11;
int weight = 81;
if ( age <= 10 && weight < 10 ) {
System.out.println("This person needs to ride the black roller coaster.");
}
else if ( age <= 10 && weight >= 80 && <= 200 ) {
}
else {
}
//The new part is this:
else if ( condition_two ) {
}
};
For the relational operator '<=' you need to provide two operands. So your else if in your if statement should read:
else if ( age <= 10 && weight >= 80 && weight <= 200 ) {
}
Firts of all the firts chart in the class name for convention need to be in uppercase, and the structure of the code I think it would be something like this
public class RollerCoaster {
static int age = 11;
static int weight = 81;
public static void main(String args[]) {
if(age <= 10) {
if(weight < 10) {
System.out.println("This person needs to ride the black roller coaster.");
}else if(weight >= 80 && weight <= 200) {
System.out.println("This person needs to ride the red roller coaster.");
}else {
System.out.println("The roller coaster is not able for this person");
}
}else{
if(weight < 10) {
System.out.println("This person needs to ride the black roller coaster.");
}else if(weight >= 80 && weight <= 200) {
System.out.println("This person needs to ride the red roller coaster.");
}else {
System.out.println("The roller coaster is not able for this person");
}
}
}
}
public class RollerCoaster {
static int age, weight;
public static void main(String args[]) {
Scanner input = new Scanner(System.in);//this help take input from user
System.out.println("Enter Your Age Below:");
age = input.nextInt();
System.out.println("Enter Your Weight Below:");
weight = input.nextInt();
System.out.println("You entered "+age+" as your age, and "+ weight+" as your weight!");
//****** First Codition
if(age < 11){
if(weight <10){
//Do somthing
}else if(weight > 79 && weight < 201){
//Do another thing
}else{
//Do something else
}
}else{
//***** Second Codition
//no need to check if age > 10 since it obviously will
if(weight >10){
//Do somthing
}else if(weight < 80 && weight < 201){
//Do another thing
}else{
//Do something else
}
}
}
}

Blackjack program score total

So in my blackjack program when each game ends the program asks you if you would to play again. My main problem right now is that when the new game is started the score counter just keeps adding the new score to the old score instead of resetting to 0. Im not really sure how to fix it. Here are the two classes where the problem is.
Player class:
public class Player{
private String name;
private Card[] hand; // from 2 - 5 cards allowed
private int cardCount,
chips;
public Player()
{
hand = new Card[5];
chips = 5;
cardCount = 0;
}
public Player(String n){
hand = new Card[5];
name = n;
chips = 5;
cardCount = 0;
}
public void acceptACard(Card c){
hand[cardCount] = new Card();
hand[cardCount] = c;
cardCount++;
}
public void showHand(int startCard)
{
for (int i = startCard; i < cardCount; i++){
System.out.print(hand[i] + "\t"); // displays one card from hand
}
}
public int calcScore(){
int cardScore =0;
int total = 0;
boolean hasAce = false;
for(int i=0; i < cardCount; i++){
cardScore = hand[i].getValue();
if (cardScore >=11 && cardScore <=13)
cardScore = 10;
else if (cardScore == 14){
cardScore = 11;
hasAce = true;
}
total += cardScore;}
if (total > 21 && hasAce == true)
total -= 10;
return total;
}
public void incrementChips(){
chips ++;
}
public void decrementChips(){
chips --;
}
public int getChips(){
return chips;
}
}
BlackJack class:
public class BlackJack {
private Player human,
computer;
private Deck deck = new Deck();
Scanner scan = new Scanner(System.in);
public BlackJack(){
human = new Player("");
computer = new Player ("");
}
public void playGame()
{
int cardTotal = 0;
String answer, answer2;
deck.shuffle();
do{
for ( int i = 0; i < 2; i++)
{
human.acceptACard(deck.dealACard());
computer.acceptACard(deck.dealACard());
}
System.out.print(" Human hand: ");
human.showHand(0);
System.out.print("\n Computer hand: ");
computer.showHand(1);
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if(human.calcScore() == 21 && computer.calcScore() < 21)
System.out.println("You win");
else if (computer.calcScore() == 21 && human.calcScore() < 21)
System.out.println("Computer wins!");
else if (computer.calcScore() == 21 && human.calcScore() == 21)
System.out.println("Tie!");
else if (human.calcScore() < 21)
do{
System.out.println("\nWould you like to hit or stay? Type hit or" +
" stay.");
answer = scan.nextLine();
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
}while(cardTotal < 4 && answer.equals("hit"));
determineWinner();
System.out.println("Would you like to play again? Enter yes or no: ");
answer = scan.nextLine();
}while(answer.equals("yes"));
reportGameStatus();
}
public void dealHand(){
int i = 2; int j =2;
human.acceptACard(deck.dealACard());
System.out.println("New card: ");
human.showHand(i++);
while(computer.calcScore() < 17){
computer.acceptACard(deck.dealACard());
System.out.println();
System.out.println("Computer's new card: ");
computer.showHand(j++);
}
}
public void determineWinner(){
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if (computer.calcScore() > human.calcScore() && computer.calcScore()<22){
System.out.println("Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (human.calcScore() > computer.calcScore() && human.calcScore()
<22){
System.out.println("You win!!");
human.incrementChips();
computer.decrementChips();
}
else if (human.calcScore() == computer.calcScore() )
System.out.println("Tie!");
else if (human.calcScore() > 21){
System.out.println("You bust! The Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (computer.calcScore() > 21){
System.out.println("The Computer busts! You win!");
computer.decrementChips();
human.incrementChips();
}
}
public void reportGameStatus(){
if(computer.getChips() > human.getChips())
System.out.println("Overall winner is the computer!");
else if(human.getChips() > computer.getChips())
System.out.println("You are the overall winner!");
}
}
Any help would be much appreciated.
I think here is your problem:
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
Instead of making new Objects you use the old ones and keep their inner state. That means your construktor is not used a second time and therefore your score, hand, chips are not resetted.
How about trying this:
if(answer.equals("hit"))
{
dealHand();
Player human = new Player();
human.calcScore();
Computer computer = new Coputer();
computer.calcScore();
cardTotal ++;
}
Also you have to make a new Deck everytime you start a new game:
Deck deck = new Deck();
Edit:
If you want to keep your chipCount place it in an Object wich will be initialiset in the constructor of your Blackjack class. After that call a function chipcount.setChipcount(chips); if you want to change the chipCount. Obvisoulsly your chipcount-object should have a getter getChipcounts() as well to get the actual chipCount.
It could look like this:
public BlackJack(){
human = new Player("");
computer = new Player ("");
ChipCount chipCount = new Chipcount(0);
}
here is how your object would be:
class ChipCount{
int chipCount;
public ChipCount(int startChips){
this.chipCount = startchips;
}
public void setChips(int chipsToAdd){
this.chipCount = this.chipcount + chipsToAdd;
}
public int getChips(){
return chipCount;
}
}
Before youre asking. Of course you could make two objects (ChipCountPlayer & ChipCountComputer). Also there is the possibility of giving setChips & getChips another argument like:
class ChipCount{
int chipCountPlayer;
int chipCountComp;
public ChipCount(int startChips){
this.chipCountPlayer = startchips;
this.chipCountComp = startchips;
}
public void setChips(int chipsToAdd, String player){
if(player.equals("player")){
this.chipCountPlayer = this.chipcountPlayer + chipsToAdd;
} else if (player.equals("computer")){
this.chipCountComp = this.chipcountComp + chipsToAdd;
}
}
public int getChips(String player){
if(player.equals("player")){
return chipCountPlayer;
} else if (player.equals("computer")){
return chipCountcomp;
}
}
}
that would be the other solution :P
PS: I am not fond of blackjack, does the computer even have chips? Anyway you could replace the comp with another player if you want to further extent your programm :D

Converting a do while code to methods JAVA

I'm studying engineering at school and part of the course is to complete Computer Programming 1, which I am currently undertaking. I have been finding it very challenging seeing as I have no prior programming experience, especially this week.
The goal of this weeks quiz/assignment is to convert the code we made last week into methods and only perform 2 calls (not that I know what that means). We are learning Java and I have a textbook here that I have been getting help from up until now but I don't find the examples they display very helpful. I will paste my code below and if anyone can help me with how to convert it into methods I would hugely appreciate it!! Thanks
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String session = "C";
System.out.println("Welcome to the Assignment Manager");
System.out.println("This application will allow you to track your assignment across all your topics. It will keep track of the number of assignments, the due dates, their weighting, if they are group based and who is in your group. You will be able to log your progress with the assignment and calculate your current grade for specific topics");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println("This program was created by <<wfeffe>>");
System.out.println("<<11th March 2014>>, for the CP1 topic in Semester 1 2014");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println(" ");
int score;
do {
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score > 4 || score < 0);
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
if (score == 0 || score == 1) {
double gradeTotal = 0;
for (int i = 1; i < 5; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
} else {
System.out.println("Enter all ten assignments: ");
double gradeTotal = 0;
for (int i = 1; i < 11; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .1);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
}
System.out.println("Do you wish to continue or end session? (C to continue)");
} while (input.nextLine().equalsIgnoreCase("C"));
}
}
What they mean by converting it into methods is placing code within methods, then calling those methods.
class Main {
public static void main(String[] args) {
method1();
method2();
}
private static void method1() {
}
private static void method2() {
}
}
Im not sure if youre supposed to used static. If not, you need to look into creating instances.
Right now, everything is in your main method. Im sure the goal is to move your code into 2 seperate methods (depending on how your cose processes), then call those methods from thw method method.
Chances are, you are going to need to make reference variables (for your Scanner and possibly other things), so you can access it from multiple methods. (make current local variables like scanner field variables if needed)
A call is when you direct the program to enter or execute some method:
System.out.println();
^^^^^^^^^^^ This is a call to the println() method
What your teacher seems to be asking you to do is factor your code into methods. I will try to help you factor out some of your code into methods, but I will not do any writing for you.
Factoring is a process that works somewhat like factoring a mathematical expression. In general, you can identify a piece of code for factoring out if you see repetitive sections of code that all do the same task, or very similar pieces of code that only differ in similar places. For example, you have:
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
I can see at least one other place where this is repeated very nearly verbatim, with only one difference. This would be a good candidate for factoring, perhaps into a method which has this code but replaces the different spot with a variable. Maybe you can even factor some code beyond the code I mentioned.
Hope this helped!
They just want you to extract the methods out and call them.
You can create a new scanner in each method or you can just declare it as a variable of your overall class and use it there.
So you would do this:
public class YourClass
{
static Scanner input;
public static void main(String[] args)
{
input = new Scanner(System.in);
do {
method1();
method2();
//...
//other code here
//...
} while (input.nextLine().equalsIgnoreCase("C"));
}
public static void method1()
{
int score;
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score > 4 || score < 0);
}
public static void method2()
{
int score;
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
}
}
First off, line 22 (including spaces) needs to have >= 4 not just > 4. (Yes the cut of code was on purpose).
What you want to do is have one call that prints out all the menu stuff and returns the int "score".
private int displayMenu() {
Scanner input = new Scanner(System.in);
String session = "C";
System.out.println("Welcome to the Assignment Manager");
System.out.println("This application will allow you to track your assignment across all your topics. It will keep track of the number of assignments, the due dates, their weighting, if they are group based and who is in your group. You will be able to log your progress with the assignment and calculate your current grade for specific topics");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println("This program was created by <<Brayden Paver>>");
System.out.println("<<11th March 2014>>, for the CP1 topic in Semester 1 2014");
System.out.println("+-+-+-+-+-+-+-+-+");
System.out.println();
int score;
do {
do {
System.out.println("Display menu: ");
System.out.println(" 0. Add a new topic");
System.out.println(" 1. Add a new assignment to an existing topic");
System.out.println(" 2. Record a result for an existing assignment");
System.out.println(" 3. Quit");
score = input.nextInt();
} while (score >= 4 || score < 0);
do {
System.out.println("Display menu: ");
System.out.println(" 0. COMP1001");
System.out.println(" 1. COMP1002");
System.out.println(" 2. COMP1003");
System.out.println(" 3. COMP1004");
score = input.nextInt();
} while (score >= 4 || score < 0);
return score;
}
And another that takes score and performs the operation.
public void performOperation(int score) {
if (score == 0 || score == 1) {
double gradeTotal = 0;
for (int i = 1; i < 5; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .25);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
} else {
System.out.println("Enter all ten assignments: ");
double gradeTotal = 0;
for (int i = 1; i < 11; i++) {
do {
System.out.println("Enter score for assignment " + i + " from 0-100: ");
int grade = input.nextInt();
if (gradeTotal >= 0 && gradeTotal <= 100) {
gradeTotal += (grade * .1);
}
} while (!(gradeTotal >= 0 && gradeTotal <= 100));
}
System.out.println("Total is : " + gradeTotal);
}
System.out.println("Do you wish to continue or end session? (C to continue)");
}
Then in your psvm:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
int score = displayMenu();
performOperation(score);
//Or performOperation(displayMenu());
} while(input.nextLine().equalsIgnoreCase("C"));
}

Adding two loops to an elevator system?

So I'm creating an elevator system to go with another piece of code. The system currently works fine, however I would like to add a while loop, so that when an invalid floor is selected, I am given the chance to retry another floor at this point in the code;
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
System.out.println("Invalid floor entry");
}
I also wanted to add another loop to the system so that once a floor has been selected and the elevator arrives at the destination floor, the cycle will allow the user to select another destination from the current floor in a never ending cycle. Here is the remainder of the code;
else {
int direction = 0;
if(currentFloor < newFloor){
direction = 1;
} else if (currentFloor > newFloor) {
direction = -1; ;
} else {
direction = 0;
}
for (; currentFloor != newFloor; currentFloor += direction)
System.out.println("..." + currentFloor);
System.out.println("Elevator has arrived!");
}
}
public void fireAlarm() {
System.out.println("***FIRE ALARM*** Please exit the building safely.");
}
}
Due to the structure of my code, I can't figure out how to do this. How could I add these two loops?
You obviously need one loop that will loop forever until a break signal from keyboard input is sent (let's say that is number -1)
public static void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor= 0; //initalize to 0
while (newFloor != -1) { //loop forever until user gives -1 as input
System.out.println("Enter your destination floor >>> ");
System.out.println("To exit the programm enter: -1"); //tell the user how to exit
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
//if logic
} else {
//else logic
}
}
}
You may try it this way:
Scanner scnr = new Scanner(System.in);
int newFloor;
while (true) {
System.out.print("Enter your destination floor >>> ");
newFloor = scnr.nextInt();
if (newFloor >= 0 && newFloor <= 7) break;
System.out.println("Invalid floor entry");
};
int direction = Math.signum(newFloor - currentFloor);
while (currentFloor != newFloor) {
currentFloor += direction;
System.out.println("..." + currentFloor);
}
System.out.println("Elevator has arrived!"); }
This is my approach. I broke the whole interaction up into three methods: The first "tells the story". The second handles the input of the new floor and the third takes the elevator to the destination floor. Thus each method has a clear responsibility and can be altered at a later stage if needs be.
// Handles the whole thing
public static void elevatorAction() {
int currentFloor = 1;
int destinationFloor;
while(true) {
destinationFloor = selectNewFloor();
goToDestinationFloor(currentFloor, destinationFloor);
System.out.println("The elevator has arrived");
currentFloor = destinationFloor;
}
}
// Handles the traveling
public static void goToDestinationFloor(int currentFloor, int destinationFloor) {
int increment;
if(currentFloor == destinationFloor) {
return;
}
increment = (currentFloor < destinationFloor? 1: -1);
while(currentFloor != destinationFloor) {
currentFloor += increment;
System.out.println("..." + currentFloor);
}
}
// Lets the user select a new destination floor for the elevator
public static int selectNewFloor() {
Scanner scnr = new Scanner(System.in);
int tempNewFloor;
System.out.println("Please choose your destination floor.");
while((true) {
tempNewFloor = scnr.nextInt();
if(tempNewFloor < 0 || tempNewFloor > 7) {
System.out.println("Next floor: " + tempNewFloor);
break;
} else {
System.out.println("Invalid input: Please choose a floor between 1 and 7");
}
}
}

Compiler errors due to missing variables (the variable is defined in a different class)

I'm a beginner to java programming, and was trying to make a Rock Paper Scissors game.
I apologize for the lack of comments.
This is my main program, it calls on the other two objects.
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++){
player.makeThrow();
gameObject.makeThrow();
gameObject.announceWinner (compThrow, getPThrow);
}
//Final Output
System.out.print (gameObject.bigWinner(winner, rounds));
}
//accessor to return round to RPSGame
public static int getRound (int round){
this.round = round;
return round;
}
}
My first object is where the player inputs the number of throws that they would like, and it is processed there.
import java.util.*;
public class RPSPlayer {
public static 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 static 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 static int getThrow (int playerThrow){
this.playerThrow = playerThrow;
return playerThrow;
}
}
The last object is where all of the calculations happen.
There is a lot of variables that don't compile properly, and I can't quite figure out why...
import java.util.*;
public class RPSGame extends RPSPlayer{
RPSPlayer player = new RPSPlayer();
RPSGame game = new RPSGame ();
RPSMain mainRPS = new mainRPS();
public static void main (String args[]) {
Random generator = new Random ();
Scanner sc = new Scanner(System.in);
int rounds = mainRPS.getRound(rounds);
}
//Random Throw Generator
public static 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 static int getPlayerThrow (){
RPSPlayer player = new RPSPlayer();
int getPThrow = player.makeThrow();
return getPThrow;
}
//Does all of the calculatoins and ouputs who threw what.
public static 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;
}
}
When compiled again, 2 new errors appear after adding in WATTO Studios' suggestions, these are the compiler errors:
RPSMain.java:23: cannot find symbol
symbol : variable winner
location: class RPSMain
RPSGame.bigWinner(winner, rounds);
^
RPSMain.java:23: non-static method bigWinner(int,int) cannot be referenced
from a static context
RPSGame.bigWinner(winner, rounds);
Why can't it find the variable 'winner' if I'm referencing from RPSGame, and why is it still searching RPSMain for the variable?
For these errors, in your RPSMain class, you're trying to access variables from your other classes. Your code here...
for (int i = 0; i < rounds; i++){
player.makeThrow();
gameObject.makeThrow();
gameObject.announceWinner (compThrow, getPThrow);
}
Should actually be this...
for (int i = 0; i < rounds; i++){
int playerThrow = player.makeThrow();
int compThrow = gameObject.makeCompThrow();
gameObject.announceWinner (compThrow, playerThrow );
}
Note that when we call a method like makeThrow(), we capture the variable and call it playerThrow. Now we can use this variable in the announceWinner() method. The same for the compThrow variable.
You are doing the same thing in your RPSGame.bigWinner(winner, rounds); line - its complaining that winner doesn't exist. This is true - winner is not a variable in RPSMain, its only a variable in RPSGame - you can't share the variables between different classes like this.
Your gameObject.announceWinner() method returns an int that represents the actual winner. If you want to use this returned value, you need to capture it into a variable. Currently you have code like this in RPGMain...
for (int i = 0; i < rounds; i++){
int playerThrow = player.makeThrow();
int compThrow = gameObject.makeCompThrow();
gameObject.announceWinner (compThrow, playerThrow );
}
System.out.print (gameObject.bigWinner(winner, rounds));
If you want to keep the int returned from the announceWinner() method, you have to capture it by making the following adjustment...
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));
}
This now says that the value returned from gameObject.announceWinner() will be stored in a local variable called winner in the RPGMain class. Now When it tries to use the winner variable in the gameObject.bigWinner() method of the next line, it knows about the value.
To fix your non-static method bigWinner(int,int) cannot be referenced from a static context error, you need to change the following line...
public int bigWinner (int winner, int rounds){
to have the word static in it, like this...
public static int bigWinner (int winner, int rounds){
Or, better yet, remove the word static from everywhere in your code. If you're new to Java, trying to use static variables and methods will just make things more complicated then they really need to be, and I can't see any reason why you'd need them to be static in your program.
compThrow and getPThrow are local variables of RPSGame. You cant use them in RPSMain.
One way to use them would be to send these to RPSMain via a method call as arguments and redeclare variables in RPSMain to accept these.
Other and more preferable solution would be to make them protected instance variables in class RPSPlayer. That way they will be available to both RPSGame and RPSMain via inheritance.
Mental note: it seems like you've got a large # of static methods, and some classes that are composed entirely of static methods, yet you still instantiate the class and call the methods as if they are part of the object instance.
In general, when calling a static method, you should use a static reference:
RSPGame.makeCompThrow();
instead of this
RSPGame game = new RSPGame().
game.makeCompThrow();
which should generate compiler warnings.
I'll nitpick your makeThrow method:
} while (playerThrow > 3 && playerThrow < 1);
that will never loop, because no number is smaller than 1 AND (&&) bigger than 3.
It should read
} while (playerThrow > 3 || playerThrow < 1);
Bigger than 3 OR (||) smaller than 1. Now it should work as intended.

Categories