I have an assignment which I have to program that creates a standings table from match list input. I used the word "infinite" because input size is unknown so I have to create a program that works until there's no matches left. I created a football class for this(input contains 2 other sports and their own matches and teams indicating the sports type with first letter of the sport with "F, B, V" for example, they're only different in scoring part, so I though if I can make football work, I can make anything else work) that contains everything required in standings table, and methods for match results which looks like this:
public class Football {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int Score;
private int wins;
private int losses;
private int MatchCount;
private int draws;
public void teamValues(String teamName, int Sgoals, int Rgoals) {
this.teamName = teamName;
this.scoredGoals = Sgoals;
this.receivedGoals = Rgoals;
}
public void matched() {
MatchCount++;
}
public void winner() {
wins++;
}
public void draw() {
draws++;
}
public void loser() {
losses++;
}
public void winScore() {
Score += 3;
}
public void drawScore() {
Score += 1;
}
public String showTeams() {
return (teamName + " " + MatchCount + " " + wins + " " + draws + " " + losses + " " + scoredGoals+":"+receivedGoals + " " + Score);
}
}
And in main class I'm calling methods in if blocks to calculate wins, score, matches count etc. And main looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner scan = new Scanner(file);
String fileString = "";
Football teams[] = new Football[2];
HashSet<String> teamsArray = new HashSet<String>();
while(scan.hasNextLine()) {
fileString = scan.nextLine();
String[] match = fileString.split("\\t|:");
if(match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
teams[0] = new Football();
teams[0].teamValues(match[1], team1score, team2score);
teams[1] = new Football();
teams[1].teamValues(match[2], team2score, team1score);
teams[0].matched();
teams[1].matched();
if(team1score>team2score) {
teams[0].winner();
teams[1].loser();
teams[0].winScore();
}
if(team1score==team2score) {
teams[0].draw();
teams[1].draw();
teams[0].drawScore();
teams[1].drawScore();
}
if(team1score<team2score) {
teams[1].winner();
teams[0].loser();
teams[1].winScore();
}
String team0 = teams[0].showTeams();
String team1 = teams[1].showTeams();
teamsArray.add(team0);
teamsArray.add(team1);
}
}
scan.close();
}
}
Since the input is static, I used arrays to work around. My problem with my code is I cant find a way to store my teams without duplicates and the variables that comes within and update whenever that team has another match.
I tried;
Storing them in a 2D string array but since the amount of teams is unknown I think it won't be a healthy way to approach to the problem.
Storing them in a String[] array list, which ended up storing the adresses instead of the values of the teams.
Set which I still use to check if at least the methods are working as intended.
It feels like I hit the wall with this program and I need to start over, so any kind of advice is appreciated.
Here's an example of input and output:
Input:
Home Team Guest Team H : G
F Manchester U. Chelsea 2 : 2
F Liverpool Manchester City 3 : 2
F Leicester City Everton 1 : 3
V Team A Team B 3 : 0
F Tottenham Liverpool 3 : 1
B Team B Team A 90 : 96
F West Ham Manchester U. 2 : 1
F Arsenal Manchester City 0 : 2
F Chelsea Arsenal 3 : 3
Output:
Name Matches Wins Draw Lose Scored:Received Score
1. Manchester U. 10 6 2 2 27:22 20
2. Arsenal 10 6 2 2 25:24 20
3. Chelsea 10 5 3 2 28:20 18
4. Liverpool 10 4 4 2 22:19 16
5. Tottenham 10 4 4 2 22:21 16
There are teams with same scores, because calculating average of scored and received goals is another way to sort the teams.
First some changes to the Football class:
Override equals to be able to search the list
Override compareTo for sorting
Override toString instead of showTeams
Create a constructor
Combine most functions into teamValues
import java.util.Formatter;
public class Football implements Comparable<Football> {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int score;
private int wins;
private int losses;
private int draws;
private int matchCount;
public int compareTo(Football f) {
return score - f.score;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
else if (o instanceof Football) {
return teamName.equals(((Football)o).teamName);
}
else if (o instanceof String) {
return teamName.equals((String)o);
}
return false;
}
public Football(String teamName) {
this.teamName = teamName;
}
public void teamValues(int scoredGoals, int receivedGoals) {
this.scoredGoals += scoredGoals;
this.receivedGoals += receivedGoals;
matchCount++;
if (scoredGoals < receivedGoals) {
losses++;
}
else if (scoredGoals > receivedGoals) {
wins++;
score += 3;
}
else {
draws++;
score += 1;
}
}
public String toString() {
return new Formatter().format("%-20s %3d %3d %3d %3d %3d:%-3d %d",
teamName, matchCount, wins, draws, losses, scoredGoals, receivedGoals, score)
.toString();
}
}
For the main program, you don't want to create a new team every time - only when a team is first encountered in the file. Put all the teams in a List. When parsing a new game, first try to find the team in the list. If it is not in there, add it.
List<Football> teamsArray = new ArrayList<>();
while (scan.hasNextLine()) {
fileString = scan.nextLine();
String[]match = fileString.split("\\t|:");
if (match.length == 5 && match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
// Create a temp team to search the List
Football team1 = new Football(match[1]);
// Search the list
if (!teamsArray.contains(team1)) {
// Not in the list already. Add it
teamsArray.add(team1);
}
else {
// Already in the List. Use that one.
team1 = teamsArray.get(teamsArray.indexOf(team1));
}
// Repeat for team 2
Football team2 = new Football(match[2]);
if (!teamsArray.contains(team2)) {
teamsArray.add(team2);
}
else {
team2 = teamsArray.get(teamsArray.indexOf(team2));
}
team1.teamValues(team1score, team2score);
team2.teamValues(team2score, team1score);
}
}
System.out.println("Name M W D L S:R S");
// Sort and print
teamsArray
.stream()
.sorted(Comparator.reverseOrder())
.forEach(t -> System.out.println(t));
Related
I am trying to create program that shows 2 outputs to the screen.
The first one being null and the 2nd one, shows values from the input file that was stored in an array of objects.
Here is my code so far:
javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.File;
public class Testing {
public static void main(String[] args) {
//error checking for commandline input
if(args.length != 1){
System.out.println("Please enter at least one input file into the argument.");
//terminates the program if more than 1 is entered
System.exit(1);
}
//make an array of bird objects
final Integer SIZE = 9;
HawaiiNativeForestBirds array[] = new HawaiiNativeForestBirds[SIZE];
//output array of Nature objects to the screen (should be "null" for all elements)
System.out.println("Hawai'i Native Forest Birds ");
System.out.println("index element ");
for (int i = 0; i < SIZE; i++) {
System.out.println(" " + i + " " + array[i] );
System.out.println();
//read from file and store data from file in your Nature array of objects
//by initializing each array element using the constructor
File file = new File(args[0]);
Scanner inputFromFile = null;
array[0] = new HawaiiNativeForestBirds("'akiapola'au"," hemignathus munroi"," yellow", 800);
array[1] = new HawaiiNativeForestBirds("akepa"," loxxops coccineus"," red", 9301);
array[2] = new HawaiiNativeForestBirds("hawai'i creeper"," oreomystis mana"," yellow green", 2501);
array[3] = new HawaiiNativeForestBirds("i'iwi"," vestiara conccinea"," red green", 2501);
array[4] = new HawaiiNativeForestBirds("apapane"," himatione sanguinea"," white red", 5001);
array[5] = new HawaiiNativeForestBirds("hawai'ian amakihi"," hemignathus virens"," yellow brown", 3001);
array[6] = new HawaiiNativeForestBirds("hawaii'an hawk"," buteo solitarius"," white gray", 1100);
array[7] = new HawaiiNativeForestBirds("puaiohi"," myadestes palmeri"," brown", 125);
array[8] = new HawaiiNativeForestBirds("anianiau"," magumma parva"," light yellow", 2000);
//use toString() to display the array again with data from input file
System.out.println("index name Scientific Name Color Population");
for(int x=0;x<SIZE;x++){
System.out.println(" " + i + " " + array[i]);
}
}//end of main() method
}// end of class LastnameFirstname08
/**
* Class HawaiianTheme stores and displays the data for each HawaiianTheme object
*
*
*/
class HawaiiNativeForestBirds {
// data fields that store each object's data
private String name;
private String scientificname;
private String color;
private Integer population;
//constructor - used to initialize the three data fields
/**
* Stores the name,scientific name, color and population of the Hawaiian Birds
* This is a Constructor, which is used to Create EAch Object & Initialize DAta Fields.
*
* #param
* #param
* #param
* #param
*/
public HawaiiNativeForestBirds(String birdName, String scientificName,String birdColor, Integer birdPopulation) {
name = birdName;
scientificname = scientificName;
color = birdColor;
population = birdPopulation;
}//end of constructor
//toString() method - returns a String with the 4 data fields
public String toString() {
String output = name +" "+ scientificname + " "+ color +" "+ population;
return output;
}//end of toString()
}//end of class HawaiianTheme
The only thing missing now is the method that reads from file and stores the array of objects by initializing the arrays.
I'm still no good at combining both of these and as you can see from the code, I don't have the method yet nor I know how the format would look like to combined both.
edit 2: I finally fixed my output . I initiliazed stuff, now how to read from file and store to the array? ;_;
Output:
Hawai'i Native Forest Birds
index element
0 null
1 null
2 null
3 null
4 null
5 null
6 null
7 null
8 null
9 null
index name Scientific Name Color Population
0 'akiapola'au hemignathus munroi yellow 800
1 akepa loxxops coccineus red 9301
2 hawai'i creeper oreomystis mana yellow green 2501
3 i'iwi vestiara conccinea red green 2501
4 apapane himatione sanguinea white red 5001
5 hawai'ian amakihi hemignathus virens yellow brown 3001
6 oma'o myadester obscurus gray 17001
7 hawaii'an hawk buteo solitarius white gray 1100
8 puaiohi myadestes palmeri brown 125
9 anianiau magumma parva light yellow 2000
All I want is to show two outputs but I gotta read and store the array of objects for the 2nd output
1.Display HawaiiNativeForestBirds array array[] without initializing elements:
2.Display HawaiiNativeForestBirds array[] again but shows the array values from the file after initializing elements:
edit:
My CSV Content:
birds.csv
Try reading in each String and storing it into its own index in a array of Strings. Then check out this algorithm and see if it works. I am sure this is not the best way to handle the situation, but I am in class and thought I would give it a intuitive shot. I am going off of the base that your constructor takes 4 parameters, and also assuming that the parameters in the txt file are in order of how they would be put into the constructor. You will also have to cast the 4th parameter into a int so it matches the expected argument type for your constructor.
//Create String array and use for loop to fill temp array with words from txt file
temp[i] = scan.next()
for(int i = 0; i < temp.length; i++) {
if (i != 0) {
i = i + 3;
HawaiiNativeForestBirds[i - (3*i/4)] = new HawaiiNativeForestBirds(temp[(i-4)+4], temp[(i-4)+5], temp[(i-4)+6], temp[(i-4)+7)];
}
else {
HawaiiNativeForestBirds[i] = new HawaiiNativeForestBirds(temp[i],temp[i+1], temp[i+2], temp[i+3]);
}
}
I would solve this problem in following way.
Create a HawaiiNativeForestBirds java class
class HawaiiNativeForestBirds {
private String name;
private String scientificname;
private String color;
private Integer population;
public HawaiiNativeForestBirds(){
}
public HawaiiNativeForestBirds(String name, String scientificname,
String color, Integer population) {
super();
this.name = name;
this.scientificname = scientificname;
this.color = color;
this.population = population;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScientificname() {
return scientificname;
}
public void setScientificname(String scientificname) {
this.scientificname = scientificname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public String toString() {
String output = name +" "+ scientificname + " "+ color +" "+ population;
return output;
}
}
Edit: If you want read a csv file then you cans solve it as below:
Assuming csv file contains data in following format
puaiohi,myadestes palmeri,brown,125
puaiohi,magumma parva,yellow,2000
I have modified Testing class to read the csv file
public class Testing {
public static void main(String[] args) {
String csvFile = "birds.csv";
String line = "";
String cvsSplitBy = ",";
List<HawaiiNativeForestBirds> listofBirds = new ArrayList<HawaiiNativeForestBirds>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bird = line.split(cvsSplitBy);
HawaiiNativeForestBirds Hawaiinbird= new HawaiiNativeForestBirds(bird[0],bird[1],bird[2],Integer.valueOf(bird[3]));
listofBirds.add(Hawaiinbird);
}
} catch (IOException e) {
e.printStackTrace();
}
// First display null values
HawaiiNativeForestBirds[] hbirds=new HawaiiNativeForestBirds[listofBirds.size()];
System.out.println("index " + "element ");
int i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird);
}
// Now display actual values
hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
System.out.println("index " + "name "+ "Scientific Name "+ "Color " + "Population ");
i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird.toString());
}
}
}
Note: HawaiiNativeForestBirds class would remain as it is.
My question is how do I change my code so that it prints out my first print line along with the lines printed from the testBuildCodonMap method? The print line that currently doesn't print out is System.out.println(s+"\t"+codonMap.get(s));. I want this to be included with the other print statements.
import java.util.*;
import edu.duke.*;
public class CodonCount {
private HashMap<String,Integer> codonMap;
public CodonCount() {
codonMap = new HashMap<String,Integer>();
}
private void buildCodonMap(int start, String dna) {
//clear out map before building
codonMap.clear();
//This method will build a new map of codons mapped to
//their counts from the string dna with the reading frame
//with the position start (a value of 0, 1, or 2).
for (int index=start; dna.length() - index > 3;index+=3) {
String currentCodon = dna.substring(index,index+3);
if (!codonMap.containsKey(currentCodon)) {
codonMap.put(currentCodon,1);
}
else {
codonMap.put(currentCodon,codonMap.get(currentCodon)+1);
}
}
}
private String getMostCommonCodon() {
//get the codon in a reading frame that has the largest count
//this method assumes the HashMap of codons to counts has already been built
int currentHigh = 0;
String mostCommonCodon = "";
for (String s : codonMap.keySet()) {
int currentCount = codonMap.get(s);
if (currentCount > currentHigh) {
mostCommonCodon = s;
currentHigh = currentCount;
}
}
return mostCommonCodon;
}
private void printCodonCounts(int start, int end) {
//This method prints all the codons in the HashMap along with their
//counts if their count is between start and end, inclusive.
for (String s : codonMap.keySet()) {
if (codonMap.get(s) >= start && codonMap.get(s) <= end) {
System.out.println(s+"\t"+codonMap.get(s));
}
}
}
public void testBuildCodonMap() {
FileResource fileResource = new FileResource();
String dna = fileResource.asString();
dna = dna.toUpperCase();
for (int index=0;index <= 2;index++) {
System.out.println("\nTesting with start position "+index+":\n");
buildCodonMap(index,dna);
String mostCommonCodon = getMostCommonCodon();
System.out.println("Total unique codons found: "+codonMap.size());
System.out.println("\nMost common codon: "+mostCommonCodon
+"\t"+codonMap.get(mostCommonCodon));
printCodonCounts(4,8);
}
}
}
Sample file for testing: CGTTCAAGTTCAA
EDIT: I want the output to look something like this:
Reading frame starting with 0 results in 3 unique codons
and most common codon is TCA with count 2
Counts of codons between 1 and 5 inclusive are:
CGT 1
TCA 2
AGT 1
Reading frame starting with 1 results in 2 unique codons
and most common codon is CAA with count 2
Counts of codons between 1 and 5 inclusive are:
CAA 2
GTT 2
Reading frame starting with 2 results in 2 unique codons
and most common codon is TTC with count 2
Counts of codons between 1 and 5 inclusive are:
TTC 2
AAG 1
I got it! The line printCodonCounts(4,8); inside of the public void testBuildCodonMap() method needs to be changed to be printCodonCounts(1,3);.
That allows the print statement inside of method private void printCodonCounts(int start, int end) to execute.
Ok so i made a car race script in java . It has two classes. The Car class and TheRace class.
The Car class just has stuff about the car like the distance the car has traveled, and in TheRace, I have two arrays for the drivers (driverArray) and sponsors (sponsors). I made a Car class array so each driver have different speeds and distance traveled.
Anyway, as you can see I made a boolean called winner, and a while loop that will keep going until the winner is true. The drivers distance becomes more and more in a while loop until myDistance is equal to or greater than 100.
In the code you can see that, if(carList[i].myDistance() >= 100){ winner = true;}, So then i display the Winner.
I have been trying to make it so it shows all the people who eventually cross the finish line 100 , and display them in the corrector order they finished. Like sorting an array or something. How i can show what place everyone got. How do i do this?
TheRace class,
package NASCAR;
import java.util.Arrays;
import java.util.Random;
public class TheRace {
// variables
public static String[] driverArray = {"steave smith", "Cheese farlin","Bob Joe","Josh Svioda", "Andrew Kralovec", "Ricky Bobby","Ashey GirslCanDriveTo","Kelsey IAgree","Joe ThisIsAManSport","Jess TheHellItIs","Jesus Defualt","Jason seglad","Andrew Smith","Andrew Johnson","Andrew Kosevsky","Andrew Anderson","Andrew Andrew", "Kate Andrew","Blondey Gold","Golden Blonde","Im Twenty" };
public static String[] sponsors = {"CocaCola","Pepsi","CoorsLight","GOD"} ;
public int[] currentDistance = new int[20];
public static void main(String[] args) {
Car[] carList = new Car[20] ;
Random rand = new Random();
for(int i =0 ; i < carList.length;i++){
carList[i] = new Car(driverArray[rand.nextInt(20)], sponsors[rand.nextInt(4)]) ;
} //end for
int lapCounter = 0 ;
boolean winner = false;
while(!winner){
for(int i = 0; i < carList.length; i++){
carList[i].changeDistance();
if(lapCounter % 6 == 0){
carList[i].speedChange();
} // end if change speed
System.out.println(carList[i].trackProgress());
if(carList[i].myDistance() >= 100){
winner = true;
System.out.println("_____ THE WINNER OF THE RACE IS: "+carList[i].myName()+" For team: "+carList[i].myTeam());
break ;
}
}// end for
lapCounter++;
System.out.println("---------------------------------");
} // end while
}// end main
}
Car class,
package NASCAR;
import java.util.Random;
public class Car {
//variables
private float totalOdMiles ;
private float speedPerHour ;
private String driverName ;
private String sponsorName ;
private Random rand = new Random();
public Car(String driverName, String sponsorName){
this.driverName = driverName ;
this.sponsorName = sponsorName ;
this.totalOdMiles = 0;
this.speedPerHour = rand.nextInt( 60);
}
public String myName(){
this.driverName = driverName;
return driverName ;
}
public String myTeam(){
this.sponsorName = sponsorName;
return sponsorName ;
}
public float myDistance(){ //reprot distance
return totalOdMiles;
}
public void speedChange(){ //ChangeSpeed()
this.speedPerHour = rand.nextInt(60);
}
public void changeDistance(){ //UpdateProgress()
float milesPerSecond = this.speedPerHour / 3600;
this.totalOdMiles+=milesPerSecond;
}
public String trackProgress(){ //ToString()
return this.driverName +" driving the "+ this.sponsorName+" car is going "+ this.totalOdMiles +"MPS "+this.totalOdMiles;
}
}
Ideally you should avoid the problem of having to sort two arrays simultaneously by adding the currentDistance field to the Car class. Then you can sort the carList using currentDistance.
For example, using java 8 you can get the first 3 places with:
Arrays.stream(carList)
.sorted((c1, c2) -> c2.currentDistance - c1.currentDistance)
.map(c -> c.getName())
.limit(3);
Hava a look at this custom Comparator,
put this code after your while loop,
Collections.sort(Arrays.asList(carList), new Comparator<Car>() {
#Override
public int compare(Car o1, Car o2) {
return Float.compare(o2.myDistance(), o1.myDistance());
}
});
to print the sorted names along with their rank,
for (Car s : carList){
System.out.println(s.myDistance() + " " + s.myName());
}
Output:
THE WINNER OF THE RACE IS: Andrew Johnson For team: CocaCola
100.004135 Andrew Johnson
99.623375 Jesus Defualt
99.23477 Andrew Smith
99.20563 Andrew Andrew
98.94183 Jesus Defualt
98.87631 Blondey Gold
98.86331 Jesus Defualt
98.64405 steave smith
98.54269 Jason seglad
98.24685 Bob Joe
98.23995 Andrew Kosevsky
98.06155 Ricky Bobby
97.81364 Jess TheHellItIs
97.77215 Blondey Gold
97.72567 Ashey GirslCanDriveTo
97.57001 Ashey GirslCanDriveTo
97.54619 Cheese farlin
97.29426 Andrew Kralovec
96.68102 Andrew Kosevsky
96.018654 Ashey GirslCanDriveTo
to list the first 5 places, use this instead,
for (int i=0; i<5; i++){
System.out.println(carList[i].myDistance() + " " + carList[i].myName() + ", -- Rank: " + (i+1));
}
This could be done more easily if you are using Java 8,
Arrays.stream(carList)
.sorted((a, b) -> Float.compare(b.myDistance(), a.myDistance()))
.map(c -> c.myDistance() + " " + c.myName())
.forEachOrdered(System.out::println);
This will get you the ranks of all the drivers in descending order along with their respective speed.
I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding!
your car class could imlpement the Comparable interface :
public class Car implements Comparable<Car>
#Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
and the you can sort your array at the end of your while:
Arrays.sort(carList);
this should somehow work i guess :)
When I run my program it gives me this error. The errors are located in the MergeInventories class as well as the CombInv class. I have labeled them in the classes provided below.
java.lang.NullPointerException
at CombInv.print(CombInv.java:19)
at MergeInventories.main(MergeInventories.java:17)
I am simply trying to print out the data. My program essentially takes two arrays and MergeSorts them.
Here are the multiple classes of my program.
import java.io.*;
public class MergeInventories
{
public static void main()
{
header();
try
{
Inventory store1 = new Inventory(new File("F:\\M359 AP Computer Science\\JAVA\\Merge Inventories\\Store1.txt"));
Inventory store2 = new Inventory(new File("F:\\M359 AP Computer Science\\JAVA\\Merge Inventories\\Store2.txt"));
CombInv mergedInventory = mergeInventories(store1,store2);
//store1.print();
//store2.print();
mergedInventory.print(); //********THIS IS LINE 17 OF THE ERROR*************
}
catch(Exception e)
{
e.printStackTrace();
//System.out.print("Error.");
}
}
private static CombInv mergeInventories(Inventory a, Inventory b)
{
CombInv inv = new CombInv();
int i=0,j=0,k=0;
while(i<a.size()&&j<b.size())
{
if(a.getProduct(i).getID() == b.getProduct(j).getID())
{
inv.add(new Product(a.getProduct(i).getID(),a.getProduct(i).getQty()+b.getProduct(j).getQty(),a.getProduct(i).getUP()));
i++;
j++;
}
else if(a.getProduct(i).getID() > b.getProduct(j).getID())
{
inv.add(b.getProduct(j));
j++;
}
else
{
inv.add(a.getProduct(i));
i++;
}
k++;
}
if(j<b.size())
{
for(j=j;j<b.size();j++)
{
inv.add(b.getProduct(j));
}
}
else if(i<a.size())
{
for(i=i;i<a.size();i++)
{
inv.add(a.getProduct(i));
}
}
return inv;
}
private static void header()
{
System.out.println("Varun Pinto \n8th Hour \nM359 AP Comp Sci \n");
}
}
Then we have the Inventory class
import java.util.*;
import java.io.*;
import java.text.*;
public class Inventory
{
protected int increment = -1;
protected int size = 0;
protected Product[] inventory = new Product[11];
protected String header;
protected static String CATEGORIES = "ID\tQTY\tU\\P";
public Inventory()
{
header = "TOTAL INVENTORY";
}
public Inventory(File file)throws FileNotFoundException
{
Scanner fileScan = new Scanner(file);
header = fileScan.nextLine();
String throwaway = fileScan.nextLine();
while(fileScan.hasNextLine())
{
Scanner lineScan = new Scanner(fileScan.nextLine());
Product p = new Product(lineScan.nextInt(), lineScan.nextInt(), lineScan.nextDouble());
increment+=1;
inventory[increment]=p;
}
}
public void add(Product p)
{
increment +=1;
inventory[increment]=p;
size +=1;
}
public Product getProduct(int i)
{
return inventory[i];
}
public int size()
{
return size;
}
public void print()
{
System.out.println(header);
System.out.println(CATEGORIES);
for(Product p: inventory)
{
System.out.println(p.toString());
}
System.out.println();
}
}
Next I have the CombInv class where one of the errors is located.
import java.text.*;
public class CombInv extends Inventory
{
public void print(){
System.out.println(header);
System.out.println(CATEGORIES + "\tVALUE");
double total = 0;
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
f.setMaximumFractionDigits(2);
for(Product p: inventory)
{
System.out.println(p.toString() + "\t" + f.format(p.getQty() * p.getUP()));
//******THERE IS AN ERROR ON THE LINE ABOVE**************************
total += p.getQty() * p.getUP();
}
System.out.println("Total Value of Stock:\t$" + total);
System.out.println();
}
}
Finally we have the Product class which is a basic superclass where I am trying to access .toString() but cannot.
import java.text.*;
public class Product
{
private int idNum;
private int quantity;
private double unitPrice;
public Product()
{
idNum = 0;
quantity = 0;
unitPrice = 0;
}
public Product(int id, int q, double price)
{
idNum = id;
quantity = q;
unitPrice = price;
}
public int getID()
{
return idNum;
}
public int getQty()
{
return quantity;
}
public double getUP()
{
return unitPrice;
}
public String toString()
{
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
f.setMaximumFractionDigits(2);
return idNum + "\t" + quantity + "\t" + f.format(unitPrice);
}
}
Please be aware that the use of ArrayLists in the inventory do make this program work, however as this is a project I am NOT ALLOWED TO USE ARRAYLISTS only Arrays. Also I MUST use a MergeSort to sort the data.
Here are the two text files from which i read the data:
Store1.txt
STORE 1 INVENTORY
ID QTY U/P
362 5 12.98
471 2 6.70
792 13 25.00
901 7 2.98
and Store2.txt
STORE 2 INVENTORY
ID QTY U/P
163 4 7.20
209 5 11.98
471 5 6.70
608 4 5.90
627 2 9.99
792 1 25.00
812 4 6.00
Here is what I expect to be printed
My Name
8th Hour
M359 AP Comp Sci
TOTAL INVENTORY //It only prints out
ID QTY U\P VALUE //these two lines.
163 4 7.20 28.80
209 5 11.98 59.90
362 5 12.98 64.90
471 7 6.70 46.90
608 4 5.90 23.60
627 2 9.99 19.98
792 14 25.00 350.00
812 4 6.00 24.00
901 7 2.98 20.86
Total Value of Stock: $638.94
It took me while to answer this because I essentially put it off for the longest time. The error is a NullPointerException and i fixed it with a simple addition of:
if(p != null)
before all the instances in which I called the p.toString(). The answer is so simple I can't believe I lost my mind over it, all I had to do was check that the value wasn't a null and it would continue looping till it found actual values. I knew my Merge Sort worked. In the end it was a really simple fix and didn't require me to change the bulk my code at all.
Also, I had to increment size again in the while loop of the constructor method of the Inventory class. I forgot to do this, but my code worked, despite what people said about rewriting the MergeSorter!
When you merge two sorted lists, perhaps you should consider using the following strategy:
Consider how large the resulting sorted list will be
Make your loop for the size of the resulting merged list
at each step consider which of the input lists elements should be used next
Make sure you handle an input list "running out" of elements
[Homework .. so no code supplied]
I'm new to java and can't seem to wrap my head around a problem. I'm trying to take two arrays of stock information, and compare them against each other(only keeping the ones that appear in both arrays). I read a bit about generic algorithms and if a match, I wanted to be able to create classes to assign fitness scores to each array set. My code doesn't really work(I can get it to analyze each individual components of the array but not the range I want it to). To clear things up, here's a sample of my data:
ID date Ticker Shares
1 2011-06-19 goog 0
1 2011-06-19 ibm 0
1 2011-06-19 gs 0
1 2011-06-19 msft 0
1 2011-06-19 c 5
2 2011-06-19 goog 0
2 2011-06-19 ibm 0
2 2011-06-19 gs 0
2 2011-06-19 msft 1
2 2011-06-19 c 4
3 2011-06-19 goog 0
3 2011-06-19 ibm 0
3 2011-06-19 gs 0
3 2011-06-19 msft 2
3 2011-06-19 c 3
4 2011-06-19 goog 0
4 2011-06-19 ibm 0
4 2011-06-19 gs 0
4 2011-06-19 msft 3
4 2011-06-19 c 2
5 2011-06-19 goog 0
5 2011-06-19 ibm 0
5 2011-06-19 gs 0
5 2011-06-19 msft 4
5 2011-06-19 c 1
As so on, I have a array of this and another one for the previous date. I want to be able to compare(grouped by the id's) the two against each other, and find entire matches. But later on, I want to be able to take the successful matches and perform analytic on them via other classes. I think the first step is identifying a match. Here's my code(it only identifies a match of ticker/shares, and I'm not sure how to get it to match an entire ID set):
public void compare(int firstindex, int lastIndex, Object date1, ArrayList data1id, ArrayList data1ticker, ArrayList data1shares, ArrayList data1price, Object date2, ArrayList data2id, ArrayList data2ticker, ArrayList data2shares, ArrayList data2price) throws Exception {
ArrayList ticker = new ArrayList();
ArrayList shares = new ArrayList();
ArrayList price = new ArrayList();
while (firstindex < lastIndex) {
//System.out.print("date is " + date1);
ticker.add(data1ticker.get(firstindex));
shares.add(data1shares.get(firstindex));
price.add(data1price.get(firstindex));
firstindex++;
}
comparewithsecondarray(ticker, shares, price, date2, data2id, data2ticker, data2shares, data2price);
//System.out.println("***********");
}
public void comparewithsecondarray(ArrayList tickerarray, ArrayList sharesarray, ArrayList pricearray, Object date2, ArrayList data2id, ArrayList data2ticker, ArrayList data2shares, ArrayList data2price) throws Exception {
//get the total number of values in the array
int totalArrayList = tickerarray.size();
int counter= 0;
System.out.println("Array has been checked against second array and we're on " + counter);
System.out.println(tickerarray);
System.out.println(sharesarray);
System.out.println("+++++++");
while (counter < totalArrayList) {
Object ticker = tickerarray.get(counter);
Object shares = sharesarray.get(counter);
Object price = pricearray.get(counter);
loadSecondArray(ticker, shares, price, date2, data2id, data2ticker, data2shares, data2price);
counter++;
}
}
public void loadSecondArray(Object ticker, Object shares, Object price, Object date2, ArrayList data2id, ArrayList data2ticker, ArrayList data2shares, ArrayList data2price) throws Exception {
//System.out.println("ticker " + ticker);
//System.out.println("shares " + shares);
//System.out.println("price " + price);
//find the last number of the arrray
if (!data2id.isEmpty()) {
int counter2 = Integer.parseInt(data2id.get(data2id.size()-1).toString());
//System.out.println("last element in array2 is " + counter2);
}
//location is the id number we're looking for.
int location = 1;
while (location > counter2) {
boolean blnFound = data2id.contains(location);
//System.out.println("Does arrayList contain " + location + "? " + blnFound);
if (blnFound) {
if(firstindex == -1) {
//System.out.println("ArrayList does not contain " + location);
} else {
//System.out.println("ArrayList contains " + location + " at index :" + firstindex);
int firstindex = data2id.indexOf(location);
int lastIndex = data2id.lastIndexOf(location);
//send ranges to study
while (firstindex < lastIndex) {
//System.out.print("date is " + date1);
Object ticker2 = data2ticker.get(firstindex);
Object shares2= data2shares.get(firstindex);
Object price2 = data2price.get(firstindex);
if (ticker.equals(ticker2) && shares.equals(shares2)) {
System.out.println("We have a match!");
System.out.println(ticker);
System.out.println(ticker2);
System.out.println(shares);
System.out.println(shares2);
System.out.println("*****");
}
//add to the counter
firstindex++;
}
location++;
}
} else {
break;
}
}
Sorry in advance for the quality of the code, I'm pretty new and still learning. I think the first step is to identify the matches, then have a way to pass those matches(as arraylists, I guess) to other classes to analyze.
Any suggestions on how to achieve my goals of this project would be great(I am reading a book on genetic algo's but its a bit hard to grasp so I'm starting to review all the code I can find on the interne to understand how its being done).
Thanks in advance
I think you may need something like this:
import java.util.Calendar;
//class representing all your data
public class StockData implements Comparable<StockData>{
private int id;
private Calendar date;
private List<ShareBean> shares;
//this will return whichever StockData that has more total shares as being greater
#Override
public int compareTo(StockData arg0) {
int totalshares = 0;
int totalshares2 = 0;
for(ShareBean share: shares)
totalshares+=share.getShares();
for(ShareBean share: arg0.getShares())
totalshares2+=share.getShares();
return totalshares-totalshares2;
}
//this method is used to see if another StockData object has the same id
#Override
public boolean equals(Object arg0) {
try {
StockData arg1 = (StockData) arg0;
if (id == arg1.id)
return true;
} catch (Exception e) {
return false;
}
return false;
}
public void setDate(Calendar date) {
this.date = date;
}
public Calendar getDate() {
return date;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setShares(List<ShareBean> shares) {
this.shares = shares;
}
public List<ShareBean> getShares() {
return shares;
}
public String toString(){
String toReturn = "";
toReturn+="ID: "+id+"\n";
toReturn+="Date: "+date.getTime()+"\n";
for(ShareBean share: shares)
toReturn+="Shares: "+share.toString()+"\n";
return toReturn;
}
}
Using this, you just make a StockData object for every datapiece you have, and add it to an array of such objects. Then, should you wish to find out if they are the same, you just use the .equals(Object arg0) method of StockData, and compare it to another StockData object.
For instance:
//this method compares to Lists of StockData, and returns a list containing all
//the StockData objects that had matches
public List<StockData> comparewithsecondarray(List<StockData> StockData1, List<StockData> StockData2) {
List<StockData> list = new ArrayList<StockData>();
for(StockData sd1: StockData1){
for(StockData sd2: StockData2){
if(sd1.equals(sd2)){
//found a match! add it to the list
list.add(sd1);
//break so we don't add the same object multiple times
break;
}
}
}
return list;
}
It really looks like you have made this incredibly more complex than it needs to be. If you were to repost what SPECIFICALLY you want to do, it would make answering your question easier.
EDIT: I've modified my StockData class, and added this other class to keep track of shares:
public class ShareBean {
private String ticker;
private int shares;
public ShareBean(String ticker, int shares){
this.ticker = ticker;
this.shares = shares;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public String getTicker() {
return ticker;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getShares() {
return shares;
}
public String toString(){
String toReturn = "";
toReturn+="Ticker: "+ticker+", Shares: "+shares;
return toReturn;
}
}
ANOTHER EDIT:
Put this main method somewhere... it doesn't really matter.
public static void main(String[] args) {
List<StockData> listSD1 = new ArrayList<StockData>();
List<StockData> listSD2 = new ArrayList<StockData>();
StockData sd1 = new StockData();
StockData sd2 = new StockData();
List<ShareBean> listShares1 = new ArrayList<ShareBean>();
List<ShareBean> listShares2 = new ArrayList<ShareBean>();
//create the shares for sd1
listShares1.add(new ShareBean("goog", 3));
listShares1.add(new ShareBean("ibm", 5));
listShares1.add(new ShareBean("gs", 0));
listShares1.add(new ShareBean("msft", 0));
listShares1.add(new ShareBean("c", 1));
//create the shares for sd2
listShares2.add(new ShareBean("goog", 0));
listShares2.add(new ShareBean("ibm", 1));
listShares2.add(new ShareBean("gs", 3));
listShares2.add(new ShareBean("msft", 0));
listShares2.add(new ShareBean("c", 5));
//set their ids
sd1.setId(1);
sd2.setId(2);
//set the dates (using calendars)
sd1.setDate(Calendar.getInstance());
sd2.setDate(Calendar.getInstance());
//and finally set the shares
sd1.setShares(listShares1);
sd2.setShares(listShares2);
//now add each object to each list. the lists will be exacly the same
listSD1.add(sd1);
listSD1.add(sd2);
listSD2.add(sd1);
listSD2.add(sd2);
//now the lists are ready, and we can compare them
//I put the comparewithsecondarray method in the StockData class, but it could go anywhere
//I also overrode the "toString" method to make the output more readable (in both StockData and ShareBean)
System.out.println(Arrays.toString(sd1.comparewithsecondarray(listSD1, listSD2).toArray()));
}