Java: Use an Array over a Linked list - java

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;
}

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);

Java nested loop. Trying to reiterate the inside loop

I'm practicing 2d array and stumbled upon on how to reiterate the inside loop of array to accept another set of inputs. I got stuck on how to reiterate the inputs without sacrificing the reinitialization of the loop variable so that it will not reset the index pointer of the array.
Here's the main class:
public class Games {
public static void main(String args[]) {
GamesClass data = new GamesClass();
List output[][] = data.createlist();
data.print(output);
}
}
class List {
private String Gamers, Status;
private int Score;
public List()
{
Gamers = "";
Score = 0;
Status = "";
}
public List(String name, int score, String status)
{
Gamers = name;
Score = score;
Status = status;
}
public void setGamers(String name)
{
Gamers = name;
}
public String getGamers()
{
return Gamers;
}
public void setScores(int score)
{
Score = score;
}
public int getScores()
{
return Score;
}
public void setStatus(String status)
{
Status = status;
}
public String getStatus()
{
return Status;
}
}
And here's the invoking class:
import java.util.*;
class GamesClass {
private int ngames,ngamers;
private String[] games;
public void nloops()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter no. of games: ");
ngames = in.nextInt();
System.out.print("Enter number of gamers each game: ");
ngamers = in.nextInt();
games = new String[ngames];
}
public String[] inputgames()
{
Scanner in = new Scanner(System.in);
for(int i=0 ; i<ngames ; ++i)
{
System.out.print("Enter Game: ");
games[i] = in.next();
}
return games;
}
public List[][] createlist()
{
nloops();
inputgames();
List[][] list = new List[ngames*ngamers][3];
Scanner in = new Scanner(System.in);
int score, n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
for(; i<list.length/ngames ; ++i)
{
list[i][0] = new List();
System.out.print("Gamer " + (i+1) + ": ");
list[i][0].setGamers(in.next());
System.out.print("Score: ");
score = in.nextInt();
list[i][0].setScores(score);
if(score>=1 && score<=50) list[i][0].setStatus("Noob");
else if(score>=51 && score<=100) list[i][0].setStatus("Savage");
else if(score>=101 && score<=150) list[i][0].setStatus("Expert");
else if(score>=151 && score<=200) list[i][0].setStatus("Master");
else if(score>=201 && score<=250) list[i][0].setStatus("Veteran");
else if(score>=251 && score<=300) list[i][0].setStatus("Legendary");
}
i+=ngamers;
}
return list;
}
public void print(List[][] value)
{
int n, i=0;
for(n=0 ; n<ngames ; ++n)
{
System.out.println("\nGame#" + (n+1) + " " + games[n]);
System.out.println("\nGamer\t\tScore\t\tStatus");
for( ;i<value.length/ngames ; ++i)
{
System.out.println((i+1) + " " + value[i][0].getGamers() + "\t\t" + value[i][0].getScores() + "\t\t" + value[i][0].getStatus());
}
i+=ngamers;
}
}
}
The output keeps stucked after inputting the first set of inputs.
Enter no. of games: 2
Enter number of gamers each game: 2
Enter Game: VALORANT
Enter Game: LOL
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Game#1 VALORANT
Gamer Score Status
1 Jrk 100 Savage
2 Dash 200 Master
Game#2 LOL
Gamer Score Status
Change the condition in the loop from
i < list.length/ngames
to i < (list.length/ngames)*(n+1) and also remove this line at the end of the loop : i+=ngamers; The variable is being incremented in the loop itself, there's no need to change it again.
However, this will produce the output
Game#1 VALORANT
Gamer 1: Jrk
Score: 100
Gamer 2: Dash
Score: 200
Game#2 LOL
Gamer 3 : name
Score : 300
Gamer 4 : name2
Score : 400
If you want to display Gamer 1 and Gamer 2 for the second game as well, print (i - n*ngamers + 1) instead of just (i+1)
Make these same changes to the print function as well

Java lottery simulation using Sets, not generating the correct number of random results or comparing Sets correctly

I have been programming a lottery simulation, with some help from questions I've been looking at on this site. I can't seem to get the program to display the correct number of results that I am requiring, and the two sets are not comparing correctly to say how many numbers have matched.
import java.util.Set;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 1;
private static final int MAX_NUMBER_POSSIBLE = 10;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Please choose " + INPUT_SIZE + " numbers from " + MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ", hit enter after each number.");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("Congratulations, you have won!");
} else {
System.out.println("Not a winner, better luck next time.");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nLotto numbers were : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChosen = input.nextInt();
if (numberChosen < MIN_NUMBER_POSSIBLE || numberChosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in " + MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE + " range.");
} else {
userNumbers.add(numberChosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
for (Integer randomNumber : randomNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been drawn.");
}
}
There 2 problems in your code:
1) In generateRandomNumbers you should take into account that the same random number could occur multiple times. So make sure that randomNumbers is really of INPUT_SIZE size in the end.
2) In doUserNumbersMatchRandomNumbers you iterate over randomNumbers but never use randomNumber.
You store your random numbers in a (Hash-)Set, One feature of Set as described in the API is that they do not contain duplicate values (by comparing them with their equals() method). Since the Random class may output the the same value multiple times you have less values in your Set.
The better approach for generating the random numbers would be to go with a while loop:
while (random.size() < INPUT_SIZE)
{
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
keep in mind that this could result in an endless loop. Although it is very unlikely though. At least this loop does have varying execution times.

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

How to get data from LinkedList?

Here is an example output that I am looking for, for my program.
Example Output
On each line enter a stadium name and the game revenue
Enter done when you are finished
Giants 1000
Foxboro 500
Giants 1500
done
Enter the name of a stadium to get the total revenue for:
Giants
The total revenue is 2500.00
I got everything working but the total revenue at the end. I'm not sure how to go into my linkedlist and grab the game revenue and display it.. This is my code right now, and what I have been messing with...
import java.util.LinkedList;
import java.util.Scanner;
public class LinkedLists {
private final Scanner keyboard;
private final LinkedList<String> stadiumNames;
private final LinkedList<Integer> gameRevenue;
public LinkedLists() {
this.keyboard = new Scanner(System.in);
this.stadiumNames = new LinkedList<String>();
this.gameRevenue = new LinkedList<Integer>();
}
public void addData(String stadium, int revenue){
stadiumNames.add(stadium);
gameRevenue.add(revenue);
}
public void loadDataFromUser() {
System.out.println("On each line enter the stadium name and game revenue.");
System.out.println("Enter done when you are finished.");
boolean done = false;
while(!done) {
System.out.print("Enter the name of the stadium:");
String stadium = keyboard.next();
if (stadium.equals("done")) {
done = true;
} else {
System.out.print("Enter game revenue: ");
addData(stadium, keyboard.nextInt());
}
}
}
// return -1 if not found
public int getIndexForName(String name) {
if(stadiumNames.contains(name)){
System.out.println("The total revenue is: " +gameRevenue.get(0));
System.exit(0);
}
return -1;
}
public void showInfoForName(String name) {
int index = getIndexForName(name);
if (index==-1) {
System.out.println("There is no stadium named " + name);
} else {
}
}
public void showInfoForName() {
System.out.println("Enter the name of the stadium to get the total revenue for it.");
showInfoForName(keyboard.next());
}
public static void main(String[] args) {
LinkedLists pgm = new LinkedLists();
pgm.loadDataFromUser();
pgm.showInfoForName();
}
}
Try this:
public int getIndexForName(String name) {
if (stadiumNames.contains(name)) {
int total = 0;
for (int i = 0 ; i < stadiumNames.size() ; i++)
if (stadiumNames.get(i).equals(name))
total += gameRevenue.get(i);
System.out.println("The total revenue is: " + total);
System.exit(0);
}
return -1;
}
There are better ways of doing this though. I would perhaps use a Map that maps each stadium name to its total revenue. You could update this map in the addData method.
using hash map is much cleaner, plus you can save the total on the side and not calculate it:
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
/**
* User: user
* Date: 09/09/2012
*/
public class Blah {
private Scanner keyboard;
private Map<String, Integer> stadiumRevenues;
private Integer total = 0;
public Blah() {
this.keyboard = new Scanner(System.in);
this.stadiumRevenues = new HashMap<String, Integer>();
}
public void addData(String stadium, int revenue){
stadiumRevenues.put(stadium, revenue);
total += revenue;
}
public void loadDataFromUser() {
System.out.println("On each line enter the stadium name and game revenue.");
System.out.println("Enter done when you are finished.");
boolean done = false;
while(!done) {
System.out.print("Enter the name of the stadium:");
String stadium = keyboard.next();
if (stadium.equals("done")) {
done = true;
} else {
System.out.print("Enter game revenue: ");
addData(stadium, keyboard.nextInt());
}
}
}
public int getTotal() {
return total;
}
// return -1 if not found
public int getIndexForName(String name) {
Integer rev = stadiumRevenues.get(name);
if(rev != null){
System.out.println("The total revenue is: " +rev);
System.exit(0);
}
return -1;
}
public void showInfoForName(String name) {
Integer rev = stadiumRevenues.get(name);
if (rev == null) {
System.out.println("There is no stadium named " + name);
} else {
}
}
public void showInfoForName() {
System.out.println("Enter the name of the stadium to get the total revenue for it.");
showInfoForName(keyboard.next());
}
public static void main(String[] args) {
Blah pgm = new Blah();
pgm.loadDataFromUser();
pgm.showInfoForName();
}
}

Categories

Resources