How to get data from LinkedList? - java

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

Related

Java - Iterating around for-loop to create players for game and setting their name

I haven't been programming for long and I have spent hours trying to get this method to do what I need so help would be very much appreciated at this point. I am creating a board game which prompts players for the number of players playing, after which they are prompted for their names in turn, and those new players will be created and their names set/stored. I also want to make sure that two players cannot have the same name.
Here is part of my player class:
public class Player {
private String name;
private int currentPosition;
private int distance;
private boolean quit;
public Player() {
}
public Player(String name, int currentPosition, int distance, boolean quit) {
this.name = name;
this.currentPosition = currentPosition;
this.distance = distance;
this.quit = quit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have a setNumberOfPlayers method which is working fine and getting the correct number of players when getNumberOfPlayers() is called.
public class SetUpGame {
Scanner sc = new Scanner(System.in);
public void addPlayers() {
String playerName;
ArrayList<Player> players = new ArrayList<Player>();
System.out.println("What are the names of the " + this.numberOfPlayers + " players?\n");
for (int loop = 1; loop <= getNumberOfPlayers(); loop++) {
System.out.println("Player " + loop + " please enter your name");
boolean valid = false;
do {
playerName = sc.nextLine();
Player player = new Player();
for (Player play : players) {
if (players.isEmpty() || !play.getName().equalsIgnoreCase(playerName)) {
player.setName(playerName);
players.add(player);
System.out.println("success, your name is: " +playerName);
valid = true;
} else {
System.out.println("please enter another name");
valid = false;
}
}
} while (valid == false);
}
sc.close();
}
When the add players method is called from main, it gives this output:
What are the names of the 2 players?
Player 1 please enter your name
...and the user can input their name but the scanner never closes or loops around to ask the next player their name. I have messed around with the code so much that I've confused myself at this point. Can anyone help with this, and also how to validate/check that the players have been created and their names set? Thank you
Your inner for loop is iterating on players array, but it is empty.
Maybe try this instead:
do {
System.out.println("Please enter name:");
playerName = sc.nextLine();
if(playerName.length()!=0){
valid = true;
for(Player play : players)
if(play.getName().equalsIgnoreCase(playerName))
valid = false;
if(valid){
Player player = new Player();
player.setName(playerName);
players.add(player);
}
}
} while (!valid);
I think you might be having a hard time debugging because of how similar all your variable names are. ('players','player','play')
EDIT: updated to check if a duplicate
First, list of players is defined as a local variable in the method addPlayers, so when this method is done, all the players data are lost. So it is necessary to modify this method either to add the players to a field of SetupGame class or to return the list of players to the calling method. The latter way is a cleaner functional way of populating the player list.
Next, in order to efficiently detect duplicate names, it is recommended to create and use Set<String> playerNames.
And the last, if Scanner is open on System.in it must not be closed, because after that no user input can be entered.
That being said, the code of addPlayers may look as follows:
public List<Player> addPlayers() {
List<Player> players = new ArrayList<>();
Set<String> playerNames = new HashSet<>();
Scanner sc = new Scanner(System.in);
System.out.println("What are the names of the " + this.numberOfPlayers + " players?\n");
for (int loop = 1; loop <= this.numberOfPlayers; loop++) {
while (true) {
System.out.println("Player " + loop + " please enter your name");
String playerName = sc.nextLine();
if (playerNames.add(playerName)) {// Set.add returns true if name was added to it
Player p = new Player();
p.setName(playerName);
players.add(p);
break; // input new player
}
}
}
return players;
}
You missed some getters and setters in your Player class.
Player.java
public class Player {
private String name;
private int currentPosition;
private double distance;
private boolean quit;
public Player() {
// no-args constructor
}
public Player(String name, int currentPosition, double distance, boolean quit) {
this.name = name;
this.currentPosition = currentPosition;
this.distance = distance;
this.quit = quit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public boolean isQuit() {
return quit;
}
public void setQuit(boolean quit) {
this.quit = quit;
}
}
You can implement the SetUpGame class as follows.
No need to create the do-while loop.
SetUpGame.java
import java.util.ArrayList;
import java.util.Scanner;
public class SetUpGame {
Scanner sc = new Scanner(System.in);
ArrayList<Player> players = new ArrayList<Player>();
int numberOfPlayers;
public int getNumberOfPlayers() {
return numberOfPlayers;
}
public void setNumberOfPlayers(int numberOfPlayers) {
this.numberOfPlayers = numberOfPlayers;
}
public void addPlayers() {
System.out.print("Enter number of players: ");
numberOfPlayers = sc.nextInt();
System.out.println("What are the names of the " + numberOfPlayers + " players?");
for(int loop = 1; loop <= numberOfPlayers; loop++) {
Player player = new Player();
System.out.print("Enter name for player " + loop + ": ");
player.setName(sc.next());
System.out.print("Enter current position for player " + loop + ": ");
player.setCurrentPosition(sc.nextInt());
System.out.print("Enter distance for player " + loop + ": ");
player.setDistance(sc.nextDouble());
System.out.print("Enter validity for player " + loop + ": ");
player.setQuit(sc.nextBoolean());
players.add(player);
}
sc.close();
}
public void displayAllPlayers() {
System.out.println("Displaying all players...");
for(Player p : players) {
System.out.printf("%s %d %f %b", p.getName(), p.getCurrentPosition(), p.getDistance(), p.isQuit());
}
}
}
Finally you can test your SetUpGame class.
TestSetUpGame.java
public class TestSetUpGame {
public static void main(String[] args) {
SetUpGame game = new SetUpGame();
game.addPlayers();
game.displayAllPlayers();
}
}

How to Add Sorting with Method and Array in Java

How to display the most fruit with the name and lots of fruit? Can you help me guys, I confusion to add method with sorting in this code. Thank you :D
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
String[] fruitName = new String[numberOfFruit];
int[] lotsOfFruit = new int[numberOfFruit];
nameAndLotsOfFruit(userInput, numberOfFruit, fruitName, lotsOfFruit);
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
nameFruit[i] = userInput.next();
System.out.print("Enter the lots of fruit " + nameFruit[i] + ": ");
lotsOfFruit[i] = userInput.nextInt();
}
}
static int theMostFruit(int numberOfFruit, String[] nameFruit, int[] lotsOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
....
}
}
You are holding name and amount informations in 2 different collections thus making it complexer to handle it. There are many ways to do it but I would've done:
Key-Value pair with fruit names as key and amounts as value
Create a custom class to hold the information
I would go for the second option now
public class FruitCounter {
static List<Fruit> listFruit = new ArrayList<>();
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the lots of fruit: ");
int numberOfFruit = userInput.nextInt();
nameAndLotsOfFruit(userInput, numberOfFruit);
theMostFruit();
}
static void nameAndLotsOfFruit(Scanner userInput, int numberOfFruit) {
for (int i = 0; i < numberOfFruit; i++) {
Fruit fruit = new Fruit();
System.out.print("Enter the name of fruit " + (i + 1) + ": ");
fruit.setName(userInput.next());
System.out.print("Enter the lots of fruit " + fruit.getName() + ": ");
fruit.setAmount(userInput.nextInt());
listFruit.add(fruit);
}
}
static void theMostFruit() {
Fruit mostFruit = listFruit
.stream()
.max(Comparator.comparing(Fruit::getAmount))
.orElse(null);
if (mostFruit != null)
{
System.out.print(MessageFormat.format("{0} has the highest amount with {1} pieces.", mostFruit.getName(), mostFruit.getAmount()));
}
}
static class Fruit
{
private String Name;
private int Amount;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
}
}
Please check where I use stream inside the method theMostFruit. It does the job for me. Altough if you have 2 fruits with the same amount, it would give you only one. I suggest you to handle that case by yourself as a practice with java streams.

How do you return items from ArrayList that is stored in a different file?

so the code I currently have can return a reference to the object in the array but wont display the data inside of it. The first bit of code is the main file which the user inputs the data, but the object reference only returns the last object the user entered, what i need is for the array to be searched and if it is found with the item display the data that is stored with that object.
the first file.
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
public class Inv
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
String str;
char c;
int n=0;
//Product product = new Product();
System.out.println(" INVENTORY MANAGEMENT SYSTEM");
System.out.println("===============================================");
System.out.println("1. ADD PRODUCT DATA");
System.out.println("2. VIEW PRODUCT DATA");
System.out.println("3. VIEW REPRLENISHMENT STRATEGY");
System.out.println("===============================================");
System.out.println("4. EXIT PROGRAM");
while(n!=4)
{
System.out.print("\n Please enter option 1-4 to continue...: ");
n = Integer.parseInt(System.console().readLine());
if (n>4||n<1)
{
System.out.print("Invalid input, please try again...");
continue;
}
if (n==1)
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.addItem();
System.out.print("Would you like to enter another product ? (Y or N) : ");
str = console.next();
}
continue;
}
if (n==2)
{
str="y";
while(str.equals("y")||str.equals("Y"))
{
Inv.prodData();
System.out.println("\n***************************************************\n");
System.out.print("Stay viewing this page? (Y or N) ");
str = console.next();
}
continue;
}
else
if (n==3)
{
System.out.print("View Replenishment Strategy.");
continue;
}
}
System.out.print("\nThank you for using this inventory management software.\n");
System.out.print("Developed by Xavier Edwards");
System.out.println("\n***************************************************\n");
}
public static Product product;
public static Store store;
public static void addItem ()
{
Scanner console = new Scanner(System.in);
product = new Product();
store = new Store();
String desc, id, str="";
double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
int stock = 0, demand = 0;
//if (product == null) //If product 1 is empty
//{
System.out.print("Please enter product description between 3 to 10 characters...: ");
desc = console.next();
desc = desc.toLowerCase();
product.setName(desc);
if ((desc.length() < 3 || desc.length() > 10))
{
System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
System.out.println("Try again with different input. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter price in $ : ");
price = console.nextDouble();
product.setPrice(price);
if (price < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter set up price. $ : ");
sUpPrice = console.nextDouble();
product.setsUpPrice(sUpPrice);
if (sUpPrice < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter unit- cost. $ : ");
unitCost = console.nextDouble();
product.setunitCost(unitCost);
if (unitCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the inventory cost. $ : ");
inventoryCost = console.nextDouble();
product.setinvCost(inventoryCost);
if (inventoryCost < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the amount in stock : ");
stock = console.nextInt();
product.setstock(stock);
if (stock < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.print("Please enter the demand of the product : ");
demand = console.nextInt();
product.setdRate(demand);
if (demand < 0)
{
System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
System.out.println("Because of incorrect input, program will restart. ");
System.out.println("\n*****************************************\n");
Inv.addItem();
}
System.out.println("\n*****************************************\n");
System.out.print(desc +" Product was added successfully ");
System.out.println("\n*****************************************\n");
store.add(product);
//}
}
public static void prodData()
{
Scanner console = new Scanner(System.in);
String pOption, str;
System.out.print("\nEnter product description to view the data...\n");
pOption = console.next();
if (product == null)
{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
System.out.println("The information for the product is..... ");
System.out.println("\n*****************************************\n");
System.out.println(store.ProductList.get(0));
if (product.equals(store.ProductList.get(0)))
{
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}*/
}
}
The second file which is where the array list is made and objects stored.
import java.util.*;
import java.util.ArrayList;
public class Store{
public ArrayList <Product> ProductList = new ArrayList<Product> ();
public Store()
{
//ArrayList = "";
}
public void add(Product product)
{
ProductList.add(product);
}
public Product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
}
Code for the storing of particular user entries
public class Product
{
public String name;
public double price, sUpPrice, unitCost, invCost;
public int stock, demand;
public Product()
{
name = "";
price = 0;
sUpPrice = 0;
unitCost = 0;
invCost = 0;
stock = 0;
demand = 0;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setsUpPrice(double sUpPrice) {
this.sUpPrice = sUpPrice;
}
public double getsUpPrice() {
return this.sUpPrice;
}
public void setunitCost(double unitCost) {
this.unitCost = unitCost;
}
public double getunitCost() {
return this.unitCost;
}
public void setinvCost(double invCost) {
this.invCost = invCost;
}
public double getinvCost() {
return this.invCost;
}
public void setstock(int stock) {
this.stock = stock;
}
public int getstock() {
return this.stock;
}
public void setdRate(int demand) {
this.demand = demand;
}
public int getdRate() {
return this.demand;
}
}
so thats the code within another file called product.java
If I understand correctly, you want the user to type in a product name, and then display all the product's data.
You should probably use your getProduct method.
product = store.getProduct(pOption);
if (product != null){
System.out.println("Product description : "+product.getName());
System.out.println("Price : $ "+product.getPrice());
System.out.println("Set-up Price : $ "+product.getsUpPrice());
System.out.println("Unit Cost : $ "+product.getunitCost());
System.out.println("Inventory Cost : $ "+product.getinvCost());
System.out.println("Amount of Stock : "+product.getstock());
System.out.println("Amount of Stock : "+product.getdRate());
}else{
System.out.println("\nThere is no information on this product.\n");
System.out.println("\nWould you like to try again? (Y or N) \n");
str = console.next();
Inv.prodData();
}
public class Inv {
//read data from any way you prefer and call the methods on store class
//since the class methods and the productlist are marked as static
//every class on your project is accessing and changing the same productlist
Store.add("your product object");
Store.getProduct("your name");
}
class Store{
public static ArrayList <product> ProductList = new ArrayList<product> ();
public static void add(product product){
ProductList.add(product);
}
public static product getProduct(String prodName) {
for (int i = 0; i < ProductList.size(); i++) {
if (ProductList.get(i).getName().equals(prodName)) {
return ProductList.get(i);
}
}
return null;
}
//implement new static methods to remove products from productlist
public static removeProduct(String name){
//code to remove product
}
public static removeAll(){
//code to clear the productlist
}
}
you need to follow this approach in your code explanation is provided inside the comments

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

Search hashmap for key and print certain values

I have a program where I want to input a fake stock symbol, number of shares, and price per share. I want the user to be able to search the arraylists of stocks, and if a certain stock is found, the LIFO average price of the last 250 stocks bought is displayed. The user should be able to input a stock more than once, for example
AAPL 50 99.99
and
AAPL 300 50.00
So if the user bought 50 shares at 99.99 and 300 shares at 50.00, it should average the last 250 bought stocks using the correct prices.
Here is where I am so far, I'm having trouble with searching the hashmap and then displaying the average of that certain stock.
package stocks;
import java.util.*;
public class Stocks {
private String sym;
private List<Purchase> purchases;
public Stocks(final String symbol) {
this.sym = symbol;
purchases = new ArrayList<Purchase>();
}
public void addPurchase(final int amt, final double cost){
purchases.add(new Purchase(amt,cost));
}
public String getSym(){
return sym;
}
public void setSym(){
this.sym = sym;
}
public double getAvg250() {
int i = 0;
int total = 0;
int shares = 0;
while (i < purchases.size()) {
Purchase p = purchases.get(i);
if (shares + p.getAmt() >= 250) {
total += (250 - shares) * p.getCost();
shares = 250;
break;
}
shares += p.getAmt();
i++;
}
return total * 1.0 / shares;
}
class Purchase {
private int amt;
private int cost;
public Purchase(int amt, double cost){
}
public int getAmt() {
return amt;
}
public void setAmt(int amt) {
this.amt = amt;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public static void main(String[] args) {
int choice = 0;
while (choice == 0){
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner (System.in);
choice = sc1.nextInt();
if(choice==1){
ArrayList<Stocks> StocksList = new ArrayList<Stocks>();
Scanner sc2 = new Scanner (System.in);
System.out.println("Please enter the stock symbol: ");
String sym = sc2.next();
System.out.println("Please enter the number of shares: ");
int amt = sc2.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc2.nextDouble();
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
Stocks s = stocks.get(sym);
if (s == null) {
s = new Stocks(sym);
stocks.put(sym, s);
}
s.addPurchase(amt, cost);
StocksList.add(s);
}
choice = 0;
if (choice == 2){
Scanner sc3 = new Scanner (System.in);
System.out.println("Please enter the symbol of the stock you wish to see: ");
String search = sc3.next();
}
if(choice==3){
System.exit(0);
}
}
}
}
If you want to iterate over the HashMap you can do below. Thouhg I am not clear about your question totally
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
for (Object key : stocks.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ stocks.get(key));
}
Or you can do
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
UPDATE
you can do something like below
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if( pairs.getKey() != null && pairs.getKey().equals(sym)) {
pairs.getValue() // this is the cost for share. write logic here to find the last 259 shares and calculate avg
}
}

Categories

Resources