Die class in Java with external code - java

I have a section of code that someone else wrote, and I cannot figure out how to make the code work with it.
I'm supposed to make a single Die roll and display a number between 1 and 6 using:
(int)(math.random()*6 + 1);
The code provided is this:
import java.util.*;
public class Ch3_PrExercise6
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Die die1 = new Die();
Die die2 = new Die();
System.out.println("die1: " + die1.getRoll()):
System.out.println("die2: " + die2.getRoll());
System.out.println("After rolling, die1: " + die1.rollDie());
System.out.println("After rolling, die2: " + die2.rollDie());
System.out.println("After second roll, die1: " + die1.rollDie());
System.out.println("After second roll, die2: " + die2.rollDie());
}
}
So far, all I can come up with is:
public class Die
{
//Sets initial value to 1
public int startFace
{
startFace = 1;
}
//Roll the die
public int rollDie
{
rollDie = (int)(math.random()*6 + 1);
}
}
I'm having trouble figuring out what the other program wants from me in the getRoll line. I understand that rollDie is called in the last four print commands.
I'm using Processing 2.20, If that's important.

I don't think that compiles? You're expecting rollDie to be a function, you can tell that because you have
die1.rollDie()
Note the parentheses: a function call.
so make a function and have it return a value:
public int rollDie()
{
int rollResult = (int)(math.random()*6 + 1);
return rollResult
}

I would upvote djna and accept his answer. To elaborate, I think this is all you need:
public class Die
{
private int face = 1;
// Get current value
public int getRoll () {
return face;
}
//Roll the die, return new value
public int rollDie () {
face = (int)(Math.random()*6 + 1);
return face;
}
}

Related

Why does my Mooc.fi ski jumping programm not print the correct score? Is it overwritten?

I am working on mooc.fi week 8, the last exercise: ski jumping. At the very bottomt of the page. Here is the link: https://materiaalit.github.io/2013-oo-programming/part2/week-8/
All tests are succesfull, except for the calculation of the output.
When the jumpers jump twice, the scores of the first and second jump are meant to be added. If the user decides to terminate the programm at this point, the jumpers are meant to be printed out, winner first, with their final scores assigned to them.
As the actual final scores printed can (based on the number) only be the result of one jump, I suspect that the programm overwrites the first jump with the second instead of adding them, but I am not sure.
The error message says, that the actual final score is supposed to be 275 but was actually 158, which with two rounds and therefore two executed jumps is just not a possible score if the jumper had actually been assigned the score of two jumps and not just one.
But it is difficult for me to assess that as the jump length and the points assigned by the judges (which together make up the jumper's score) are generated randomly.
The error message I receive when testing is the following:
"twoRoundsOneJumperCalculationCorrect Failed: Jumper Arto's points are printed incorrectly in the tournament results your programm prints.
I have tested the calculation in the programm while it is running and the points the jumpers receive while jumping are accurate. Only the final results seem to be off. I am not sure why that is the case though. They appear to be overwritten with new scores.
I have gone through the code again to find what I am doing wrong, but I just cannot see where the mistake is.
I have divided the programm in four classes:
-Main to execute the UserInterface
-UserInterface for the organizing and printing the programm
-Jumper for creating jumpers for the ski tournament and to execute everything related to them such as jumping and the calculation of the scores
-SortAgainstPoints to sort the jumpers in ascending order by score
Here is my code:
//Main:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
UserInterface ui = new UserInterface();
ui.start(reader);
}
}
//UserInterface:
import java.util.*;
import java.util.Set;
import java.util.TreeMap;
public class UserInterface {
private HashMap<String,Jumper> participants;
private Jumper participant;
public UserInterface()
{
this.participants = new HashMap<String,Jumper>();
}
public void start(Scanner reader)
{
System.out.println("Kumpula ski jumping week");
System.out.println("");
System.out.println("Write the names of the participants one at a time; an empty string brings you to the jumping phase.");
while(true)
{
System.out.print(" Participant name: ");
String name = reader.nextLine();
if(!name.isEmpty())
{
this.participant = new Jumper(name);
this.participants.put(name, participant);
}
if(name.isEmpty())
{
System.out.println("");
break;
}
}
System.out.println("The tournament begins!\n");
rounds(reader);
}
public void sortAgainstPoints(ArrayList<Jumper> list)
{
Collections.sort(list, new SortAgainstPoints());
}
public void rounds(Scanner reader)
{
int roundCounter = 0;
ArrayList<Jumper> list = new ArrayList<Jumper>(this.participants.values());
while(true)
{
sortAgainstPoints(list);//does that even work????
System.out.print("Write \"jump\" to jump; otherwise you quit: ");
String input = reader.nextLine();
System.out.println("");
roundCounter ++;
if(!input.equals("jump"))
{
break;
}
System.out.println("Round " + roundCounter + "\n");//Round 1 ...
System.out.println("Jumping order:");
int counter = 0;
for(Jumper p : list)
{
counter++;
System.out.println(" " + counter + ". " + p);
}
System.out.println("");
System.out.println("Results of round " + roundCounter);
for(Jumper p : list)
{
int jumpLength = p.jump();
p.addJumpLength(jumpLength);
int[] judgesScores = new int[5];
judgesScores = p.judgeScores();
int score = 0;
score += p.jumpScore(jumpLength, judgesScores);
p.setPoints(score);
System.out.print(" " + p.getName() + "\n" +
" length: " + jumpLength + "\n" +
" judge votes: " + p.printJudgesScores(judgesScores) +"\n"
);
}
sortAgainstPoints(list);
System.out.println("");
}
Collections.reverse(list);//highest scored jumper should now be first
System.out.println("Thanks!\n");
System.out.println("Tournament results:");
System.out.println("Position Name");
for(int i = 0; i < list.size(); i++)
{
System.out.println((i +1) + " " + list.get(i).getName() + " (" + list.get(i).getPoints() + ")\n"
+ " jump lengths: " + list.get(i).printJumpLengths());
}
//tournament result does not equal acutal points and jump lengths, assignment is most likely overwritten with each new jump
}
}
//Jumper:
import java.util.*;
public class Jumper {
private String name;
private int points;
private Random random;
private int[] judges;
private ArrayList<Integer> jumpLengths;
public Jumper(String name)
{
this.name = name;
this.points = 0;
this.jumpLengths = new ArrayList<Integer>();
}
#Override
public String toString()
{
return this.name + " (" + this.points + " points)";
}
public int getPoints()
{
return this.points;
}
public int jump()
{
this.random = new Random();
int jumpLength = random.nextInt(120 - 60 +1) + 60;
return jumpLength;
}
public int[] judgeScores()
{
this.judges = new int[5];
for(int i = 0; i< judges.length; i++)
{
int judgeScore = random.nextInt(20 - 10 +1) + 10;
judges[i] = judgeScore;//scores, unsorted
}
return judges;
}
//smallest and largest judge score are meant to be skipped as specified //by task
public int jumpScore(int jumpLength, int[] judges)
{
sort(judges);//sorted
//skip first and last:
int score = jumpLength;
for(int i = 1; i < judges.length-1; i++)//skips first and last index
{
score += judges[i];
}
return score;
}
public String printJudgesScores(int[] judges)
{
String judgesScores = "[";
for(int i = 0; i < judges.length-1; i++)
{
judgesScores += judges[i] + ", ";
}
judgesScores += judges[judges.length-1] +"]";
return judgesScores;
}
public String getName()
{
return this.name;
}
public void setPoints(int points)
{
this.points = points;
}
public int[] sort(int[] judges)
{
for(int i = 0; i < judges.length; i ++)
{
for(int j = i+1; j < judges.length; j++)
{
if(judges[i] > judges[j])
{
int temp = judges[i];
judges[i] = judges[j];
judges[j] = temp;
}
}
}
return judges;
}
public void addJumpLength(int jumpLength)
{
this.jumpLengths.add(jumpLength);
}
public String printJumpLengths()
{
String jumps = "jump lengths: ";
for(int i = 0; i < this.jumpLengths.size()-1; i++)
{
jumps += this.jumpLengths.get(i) + " m, ";
}
jumps += this.jumpLengths.get(this.jumpLengths.size()-1) + " m";
return jumps;
}
}
//SortAgainsPoints:
import java.util.Comparator;
public class SortAgainstPoints implements Comparator<Jumper> {
public int compare(Jumper jumper1, Jumper jumper2)
{
if(jumper1.getPoints() > jumper2.getPoints())
{
return 1;
}
else if(jumper1.getPoints() < jumper2.getPoints())
{
return -1;
}
else
return 0;
}
}
I would appreciate any help!
I have done my best to post a good question, I know there are many better ones out there. If there is anything I can do to make the question clearer, let me know!
Edit: In case anybody is wondering, it's because I did not update the points correctly, I just replaced the old score with the new. It should have been p.setPoints(p.getPoints() + score);
instead of p.setPoints(score);

How to use an enhanced for loop and an array for a dice game

Okay so for a project I need to loop through as many dice rolls as the user wants and store them in an array to print out at the end with an advanced for loop. I have everything else done but I am stuck on how to integrate an array/advanced for loop into my existing code.
This is the class used to deal with all the dice functions:
package paradiseroller;
public class PairOfDice
{
public int sides = 6;
public int die1; // Number showing on the first die.
public int die2; // Number showing on the second die.
public PairOfDice()
{
// Constructor. Rolls the dice, so that they initially
// show some random values.
roll(); // Call the roll() method to roll the dice.
}
public void roll()
{
// Roll the dice by setting each of the dice to be
// a random number between 1 and 6.
die1 = (int) (Math.random() * sides) + 1;
die2 = (int) (Math.random() * sides) + 1;
}
public int getDie1()
{
// Return the number showing on the first die.
return die1;
}
public int getDie2()
{
// Return the number showing on the second die.
return die2;
}
public int getTotal()
{
// Return the total showing on the two dice.
return die1 + die2;
}
}
This is the main file in which I need to use the array and for loop:
package paradiseroller;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y")) {
PairOfDice dice; // A variable that will refer to the dice.
int rollCount; // Number of times the dice have been rolled.
dice = new PairOfDice(); // Create the PairOfDice object.
rollCount = 0;
System.out.println("\nIt took " + rollCount + " rolls to get a 2.");
System.out.print("Would you like to continue? y/n");
choice = sc.nextLine();
}
}
}
For going as long as you want and storing it in a array then printing, let g be the amount the user wants
PairOfDice[] result = new PairOfDice[g];
// setting
for (int i = 0; i < g; i++)
{
result[i] = new PairOfDice();
}
// printing
for (PairOfDice r : result)
{
System.out.println(r.getDie1() + " " + r.getDie2());
}
Think of : as in so it's getting each int IN result and assigning it to r for each iteration.
Keep in mind this is for if you want to put it in a array (kinda bad in this case) if you just want to print immediately then you could use
for (int i = 0; i < g; i++)
{
dice = new PairOfDice();
System.out.println(dice.getDie1() + " " + dice.getDie2());
}
This also gives you access to the slot that it's in thanks to i.

Syntax error on token(s), misplaced construct(s) in Eclipse

So I'm having troubles with my program here. I'm supposed to write a program that calls for the Accelerate / Brake methods in a car. I'm getting the Syntax error in the first half of the code, but the second half is marked as correct.
Car class:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(String m, int year) {
yearModel = year;
make = m;
speed = 0;
}
// Declare mutators (methods).
// Declare accessors (methods).
public int getModel() { // Model year of car.
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public void setModel(int year) {
yearModel = year;
}
public void setMake(String carMake) {
make = carMake;
}
public void setSpeed(int s) { // Incorrect??? Possible outSpeed = speed;
speed = s; // Not sure if correct; should be "0" | or equal to "carSpeed"
}
public void accelerateSpeed() {
speed += 5;
// Each call will increase by 5.
}
public void brakeSpeed() {
speed -= 5;
// Each call will decrease by 5.
}
}
CarResults class:
import javax.swing.JOptionPane;
class CarResults {
public static void main(String[] args) {
String input, carMake;
int model, yearModel, year, s;
Car myCar = new Car("Car", 2011);
// Retrieve car's Make & Model.
carMake = JOptionPane.showInputDialog("What is the Make of your car? ");
myCar.setMake(carMake);
year = Integer.parseInt(JOptionPane.showInputDialog("What is the Model Year of your car? "));
myCar.setModel(year);
input = JOptionPane.showInputDialog("Enter your car's speed: ");
s = Integer.parseInt(input);
myCar.setSpeed(s);
for (int i = 0; i < 5; i++) {
myCar.accelerateSpeed();
System.out.println();
System.out.println("The " + " " + myCar.getModel() + " " + myCar.getMake() +
" is gradually accelerating. ");
// Apply acceleration.
System.out.println("Your current speed is: " + myCar.getSpeed());
}
// Begin applying brakes.
System.out.println();
System.out.println("\t>>> Now, let's get the results for applying the brakes... ");
System.out.println();
for (int i = 0; i < 5; i++) {
myCar.brakeSpeed();
System.out.println();
System.out.println("[Braking] Your" + " " + myCar.getModel() + " " + myCar.getMake() + " is now traveling at: ");
// Apply brakes.
System.out.println("Now your speed is: " + myCar.getSpeed());
}
// End the program.
System.exit(0);
}
}
I don't think there is anything wrong with this. I was able to compile and run this just fine. Try compiling on your command line with
javac CarResults.java Car.java
and then run it with
java CarResults

Java: Use an Array over a Linked list

I am relatively new to Java. And I am a Student in the second semester.
The following has been my last task, and I have already presented it. Everything was fine, and the task that was neccessary for me to accomplish has been completely fulfilled.
The task over the semester was making a little game (My choice was guess a number game), and the tasks were simply build upon eachother. (e.g. use at least 5 functions, at least 3 classes, show all four examples of OOP and make a Computer Player)
So having that said I do not mean for people to solve these task because as you will see they have been completed.
Just one additional thing gives me trouble.
I use a Linked list to store the guessed numbers and recall them when needed.
So finally my question is:
How would I go about switching the Linked list with an Array?
Here the code:
Here the Run Class:
package fourfive;
public class Run {
/*
The Game Initializing class!
>>>> "game.getNumPlayers()" //can be uncommented if you want to play
if left commented, you can watch the bots fight to the death.
------------------------------------------------------
game.setBotPlayers //Same as getNumPlayers - defines how many (Bot) players you want to add
------------------------------------------------------
game.setTopNum() // defines the maximum range of numbers
which you want to guess. Starting from 0!
-----------------------------------------------------
*/
public static void main(String[] args){
Game game = new Game(0);
//game.getNumPlayers();
game.setBotPlayers(100);
game.setTopNum(2000);
game.start();
}
}
Game Class:
package fourfive;
import java.util.Random;
import java.util.Scanner;
public class Game {
/*
Some Variables being defined here.
*/
private static Scanner input = new Scanner(System.in);
private int MAX_Tries;
private int TOP_Num;
private int numPlayers;
private int numBots;
private boolean gameWinner = false;
private Random rand = new Random();
private int num;
private Participants[] players; //inheritance 1
private Participants currentPlayer; //polymorphism 1
public Game(int numPlayers) {
this(numPlayers, 10);
}
public Game(int numPlayers, int maxTries) {
this(numPlayers, maxTries, 1000);
}
public Game(int numPlayers, int maxTries, int topNum) {
MAX_Tries = maxTries;
TOP_Num = topNum;
this.numPlayers = numPlayers;
resetPlayers();
resetTheNumber();
}
/*
Inheritance Example 1
The following is a piece of inheritance. Whereas an array of Players whenever of the type
"Participants". Which is then resolved into the type "Human" and that is being inherited from
"Participants". And whenever Bots or Human players are joined, they will be joined within
the same array
*/
public void resetPlayers() {
players = new Human[numPlayers + numBots];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Human(i + 1);
}
for (int i = numPlayers; i < (numBots + numPlayers); i++) {
players[i] = new Computer(i + 1, TOP_Num);
}
}
public void setNumPlayers(int numPlayers) {
this.numPlayers = numBots;
resetPlayers();
}
public void setBotPlayers(int numBots) {
this.numBots = numBots;
resetPlayers();
}
public int getMaxTries() {
return MAX_Tries;
}
public void setMaxTries(int maxTries) {
this.MAX_Tries = maxTries;
}
public int getTopNum() {
return TOP_Num;
}
public void setTopNum(int topNum) {
this.TOP_Num = topNum;
resetTheNumber();
resetPlayers();
}
private void resetTheNumber() {
num = rand.nextInt(TOP_Num);
}
public void start() {
resetPlayers();
System.out.println("Welcome to the Guess a Number Game!\n");
System.out.println("Guess a number between 0 and " + (TOP_Num - 1) + "!");
currentPlayer = players[0];
System.out.println("The num " + num);
/*
Polymorphism example.
Any object that can pore than one IS-A test is considered to be Polymorphic.
In this case we are setting up a condition in which any given player has
the ability to win, which is depicted from the "isCorrect()" Method.
*/
while (!gameWinner && currentPlayer.getNumTries() < MAX_Tries) {
for (int i = 0; i < players.length; i++) {
//currentPlayer = players[i];
players[i].guess();
if (isCorrect()) {
gameWinner = true;
printWinner();
break;
} else
printWrong();
}
if (!gameWinner) {
printTriesLeft();
}
}
if (!gameWinner)
printLoser();
}
public boolean isCorrect() {
return currentPlayer.getLastGuess() == num;
}
public void printWinner() {
if (currentPlayer instanceof Computer)
System.out.println("Sorry! The Bot " + currentPlayer.getPlayerNum() + " got the better of you, and guessed the number: [" + num + "] and won! Perhaps try again!");
else
System.out.println("GG Player " + currentPlayer.getPlayerNum() + "you guessed the Number [" + num + "] right in just " + currentPlayer.getNumTries() + " tries!");
}
public void printLoser() {
System.out.println("Too Sad! You didn't guess within " + MAX_Tries + " tries! Try again!");
}
public void printWrong() {
String word = "too high";
if ((Integer.compare(currentPlayer.getLastGuess(), num)) == -1)
word = "too low";
System.out.println("Nope! " + word + "!");
}
public void printTriesLeft() {
System.out.println(MAX_Tries - currentPlayer.getLastGuess() + " tries left!");
}
public void getNumPlayers() {
System.out.print("Enter number of Persons playing => ");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter the number of Players => ");
}
numPlayers = input.nextInt();
System.out.print("Enter number of Bots! =>");
while (!input.hasNextInt()) {
input.nextLine();
System.out.println("Invalid input! It must be a number!");
System.out.print("Enter number of Bots! =>");
}
numBots = input.nextInt();
resetPlayers();
}
}
Participants class:
package fourfive;
import java.util.LinkedList;
public abstract class Participants extends Run {
protected int numTries;
protected int playerNum;
protected LinkedList<Integer> guesses;
abstract void guess();
public int getLastGuess(){
return guesses.peek();
}
public int getPlayerNum(){
return playerNum;
}
public int getNumTries(){
return guesses.size();
}
}
Now the Human class: (basically the human player)
package fourfive;
import java.util.LinkedList;
import java.util.Scanner;
public class Human extends Participants {
protected static Scanner input = new Scanner(System.in);
public Human(int playerNum) {
numTries = 0;
this.playerNum = playerNum;
guesses = new LinkedList<Integer>();
}
public void guess(){
System.out.print("Player " + playerNum + "guess =>");
while(!input.hasNextInt()){
input.nextLine();
System.out.println("Invalid input!");
System.out.print("Player " + playerNum + "guess =>");
}
guesses.push(input.nextInt());
}
}
And Last the Computer class:
package fourfive;
import java.util.Random;
public class Computer extends Human {
protected static Random rand = new Random();
protected int maxGuess;
Computer(int playerNum) {
super(playerNum);
maxGuess = 1000;
}
Computer(int playerNum, int topNum){
super(playerNum);
maxGuess = topNum;
}
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
guesses.push(guess);
}
public int getMaxGuess() {
return maxGuess;
}
public void setMaxGuess(int num) {
maxGuess = num;
}
}
You would initialize the Array with a fixed size, e.g. 4 and resize if needed. For this, you need an extra attribute to store the fill level of the array.
int[] guesses = new int[4];
int guessFilling = 0;
[...]
#Override
public void guess() {
int guess = rand.nextInt(maxGuess);
System.out.println("Bot " + playerNum + " turn *" + guess + "*");
if (guessFilling == guesses.length) {
resizeGuesses();
}
guesses[guessFilling++] = guess;
}
private void resizeGuesses() {
int[] newGuesses = new int[guesses.length > 0 ? 2 * guesses.length : 1];
System.arraycopy(guesses, 0, newGuesses, 0, guesses.length);
guesses = newGuesses;
}

Return value executing a method?

import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.

Categories

Resources