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 :)
Related
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));
I have a project that is to create an array aRoad with a distinct length. I need to shift elements through this array and delete the object in the end, when it reaches the element just behind aRoad[N].
Let's suppose:
I have a number of objects ("cars") N and an array ("road") with the length L (=4).
i = 0: car1 is at road[0].
i = 1: car1 is at road[1].
i = 2: car1 is at road[2], car2 spawns at road[0].
i = 3: car1 is at road[3], car2 is at road[1].
i = 4: car1 vanishes from the road, car2 is at road[2], car3 spawns at road[0].
My Car-class:
package traffic;
public class Vehicle {
private int bornTime;
private char destination;
public Vehicle(int bornTime, char destination){
this.bornTime = bornTime;
this.destination = destination;
}
public int returnTime() {
return bornTime;
}
public char returnDest() {
return destination;
}
public String toString() {
System.out.print(destination);
return null;
}
}
My problem is: as soon as an object is leaving the array I get an error because the Index is out of Range. I tried to cover this with an IF-condition and thanks to the first answer I was able to create the code update.
How do I get a system, like that to run in Java? My updated approach:
public static void main(String[] args) {
int time = 1;
char[] aRoad = new char[6]; // lane length
Vehicle[] carList = {new Vehicle(1, 'X'), new Vehicle(4, 'Y')};
while(time < 15){
for(Vehicle car : carList){
if (car != null ){
int pos = time - car.returnTime();
if (pos >= 0){
if (pos >= 1){
aRoad[pos-1] = 0;
}
if (pos == (aRoad.length)){
aRoad[pos-1] = 0;
car = null;
}
if (car != null){
aRoad[pos] = car.returnDest();
}
}
}
}
//PRINT ARRAY EACH ITERATION, SET time = time + 1
}
The output looks like:
[...]
time = 6: [ , , Y, , , X]
time = 7: [ , , , Y, , ]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at traffic.Test1.main(Test1.java:19)
So my specific question is:
How do I prevent this exception without setting the X-object (-car) to null?
EDIT
Since the question was too unspecified I threw out all the useless information and tidied it up.
I will answer your most clear question, the answer to which should hopefully set you in the right direction.
but how do I actually create a lot of cars going down the road?
You may be getting stuck here because you haven't utilised your Vehicle object's borntime field. For each iteration of your while loop, a car's new position in the road should be be given by
current time - borntime
So if you have multiple cars and a while loop iterating over your time dimension
Vehicle car1 = new Vehicle(2, "X");
Vehicle car2 = new Vehicle(4, "Y");
...
int time = 2;
while(time < 10){
// calculate road positions
int car1Pos = time - car1.returnTime();
int car2Pos = time - car2.returnTime();
aRoad[car1Pos - 1] = 0;
aRoad[car1Pos] = car1.returnDest();
aRoad[car2Pos - 1] = 0;
aRoad[car2Pos] = car1.returnDest();
...
}
But whenever your code starts looking this repetitive its best to think in terms of more arrays and loops. Put the vehicles in a "Vehicle array" and loop over it to update each car's position in the array
Vehicle[] carList = {new Vehicle(2, "X"), new Vehicle(4, "Y")};
...
int time = 2;
while(time < 10){
for(Vehicle car : carList){
int pos = time - car.returnTime();
aRoad[pos-1] = 0;
aRoad[pos] = car.returnDest();
}
...
}
Once you have that working, the next step would be to dynamically add Vehicles to carList, perhaps every two seconds, and remove them from carList when they get to the end of the road. Using an ArrayList for your carList would be much easier for this part.
Note that I have not tested this code so their might be syntactic mistakes.
I am struggling with Arrays (java)
Since this is the first time to learn about java in my life, I have no idea how to start it. I have just learned how to declare arrays and so on. However, this is too complicated for me. I think I can get guidelines if I see this answer. Can anybody help me out?
the prog
Read the java.util.Scanner (API). Your code works. You can do what you want with the scores, just read them from the file and cast them to the appropriate data types (integers) for calculating average scores etc.
The variables are strings, so you must cast them to numbers to make your calculation.
You can use arraylist ArrayList<TeamMember> as an instance variable of TeamMembers for your Teams or a collection with primitive types for the team but I think best is if you make classes for Team, TeamMember and Score that you instanciate in your Bowling class. You can find this information anywhere.
import java.util.Scanner;
//...
Team usa = new Team();
Team mexico = new Team();
TeamMember person = new TeamMember(usa); //Harry plays for the US
...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
If you know that every third input is a score then you can check modulo 3 (% 3) to know which iteration is divisible by 3. .
I have done about 40% of your request, i think that's enough for you to go on. You should be able to finish it on your own.
If you have further question,just leave a comment.
( There are some hidden bugs for you,to handle it you should have an understanding of scope first, just for your learning. )
import java.io.*;
import java.util.*;
// declaration of the class
public class Bowling2 {
// declare arrays below
String Team, Member;
int Score, Scorew, Scoreb;
int[][] teamw = new int[10][3];
int[][] teamb = new int[10][3];
// declaration of main program
public static void main(String[] args) throws FileNotFoundException {
// 1. connect to input file
Scanner fin = new Scanner(new FileReader("bowling.txt"));
// 2) initialize array accumulators to zero
int i, j, Scoreb, Scorew = 0 ;
// 3) display a descriptive message
System.out.println(
"This program reads the lines from the file bowling.txt to determine\n"
+ "the winner of a bowling match. The winning team, members and scores\n"
+ "are displayed on the monitor.\n");
// 4) test Scanner.eof() condition
while (fin.hasNext()) {
// 5) attempt to input next line from file
Member = fin.next();
Team = fin.next();
Score = fin.nextInt();
// 6) test team color is blue
if (Team.toString() == "blue" ){
// 7) then store blue member and score
teamb[i][0] = Member;
teamb[i][1] = Team;
teamb[i][2] = Score;
// 8) increase blue array accumulator
sumArray("blue");
i++;
}
// 9) else store white member and score
else {
teamw[j][0] = Member;
teamw[j][1] = Team;
teamw[j][2] = Score;
// 10) increase white array accumulator
sumArray("white");
j++;
}
}
// 11) if blue team score is larger
// 12) then display blue team as winner
// 13) else display white team as winner
// 14 disconnect from the input file
fin.close();
}
// implement method `sumArray()` below
/* 1. initialize accumulator to 0
2. loop over initialized array indices
3. increase accumulator by indexed array element
4. return accumulator
*/
public double sumArray(string color) {
if (color == "blue") {
for (int k = 0;k < teamb.length(); k++) {
//do the calculation here, and return it
}
}else {
for (int h = 0;h < teamw.length(); h++) {
//do the calculation here, and return it
}
}
}
// implement method `printArray()` below
/* 1. display the team name as the winner
2. loop over initialized array indices
3. display member and score for that array index
*/
}
Can someone could be kind and help me out here. Thanks in advance...
My code below outputs the string as duplicates. I don't want to use Sets or ArrayList. I am using java.util.Random. I am trying to write a code that checks if string has already been randomly outputted and if it does, then it won't display. Where I am going wrong and how do I fix this.
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
So the output I am getting (randomly) is, "America, America, Chile" when it should be "America, Chile".
When do you expect this to be false?
countries[i].equals(countries[i])
Edit:
Here's a skeleton solution. I'll leave filling in the helper methods to you.
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
This doesn't check important things like the number of unique countries.
You need a data structure which allows you to answer the question "does it already contain item X?"
Try the collection API, for example. In your case, a good candidate is either HashSet() or LinkedHashSet() (the latter preserves the insert order).
You'd probably be better of using another structure where you save the strings you have printed. Since you don't want to use a set you could use an array instead. Something like
/*
...
*/
bool[] printed = new bool[countries.length];
for(int i=0 ; i<numOfTimes ; /*noop*/ )
{
int r = nums.nextInt(countries.length);
if (printed[r] == false)
{
i = i + 1;
printed[r] = true;
aTemp = aTemp + countries[r];
aTemp = aTemp + ",";
}
}
return aTemp;
Consider what you're comparing it to:
if (!countries[i].equals(countries[i]))
are you comparing c[i] to c[i]? or c[i] to c[i-1]? Or do you need to check the whole array for a particular string? Perhaps you need a list of countries that get output.
make list uniqueCountries
for each string called country in countries
if country is not in uniqueCountries
add country to uniqueCountries
print each country in uniqueCountries
When you do this, watch out for index out of bounds, and adjust accordingly
Much faster way to do it then using HashSets and other creepy stuff. Takes less code too:
public String randomCounties() {
List<String> results = Arrays.asList(countries);
Collections.shuffle(results);
int numOfTimes = Dice();
String result = " ";
for(int i=0 ; i<numOfTimes; i++) {
result = result + countries[i] + ", ";
}
return result;
}
If you want to avoid outputting duplicate values, you need to record what values have already been listed or remove values from the pool of possibilities when they get selected.
You mention that you do not want to use Sets or ArrayList (I assume you mean Lists in general), I assume that is a requirement of the assignment. If so, you can accomplish this by building arrays and copying data between them the same way that an ArrayList would.
one note, your current implementation chooses between 1 and 6 entries from and array of 4 entries. If you force the selections to be unique you need to decide how to handle the case when you have no more unique selections.
Question: Where does productArray come from in these:
for ( Product product : productArray )
&
Arrays.sort( productArray, new ProductComparator() );
Question: What am I doing wrong? How do I make this sort?
Related Post from Yesterday
EDIT
:::EDIT:::
Ok I took your advice here about
Product productArray[] = new Product[ARRAY_LENGTH]
Now it is broke here
/tmp/jc_22339/InventoryPart2.java:99: cannot find symbol
symbol : variable productArray
location: class InventoryPart2
for ( Product product : productArray ) {
^
/tmp/jc_22339/InventoryPart2.java:101: cannot find symbol
symbol : variable productArray
location: class InventoryPart2
inventoryValue += productArray.calcInventoryValue();
^
And if I do it like
for ( Product product : productArray[] ) {
I get
/tmp/jc_23524/InventoryPart2.java:69: '.class' expected
for ( Product product : productArray[] ) {
^
So I am back stuck.
Begin program
:::Updated Code:::
/**
This program stores a collection of a product and its variables in a java array
It will sort and display the information with a total
*/
// Import statements go here
import java.util.Scanner;// Import and use scanner
import java.util.Arrays;
public class InventoryPart2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {// begin main
// Define your array of product objects and index here
final int ARRAY_LENGTH = 5;// declare constant
final int version = 2;// declare int version number
// Create instance of Scanner class
Scanner input = new Scanner( System.in );// new Scanner for CL input
// Set counter to loop x times to populate your array of product objects
int counter = 0;
// Initialize your product array with the number of objects to populate it with
Product productArray[] = new Product[ARRAY_LENGTH];// create array Product of class Product
// Welcome message
System.out.printf( "\n%s%d\n" ,
"Welcome to the Productentory Program v.", version );
// Construct default values for Product
productArray[0] = new Product("EThe Invisible Man", 0, 8.50);
productArray[1] = new Product("DThe Matrix", 1, 17.99);
productArray[2] = new Product("CSe7en", 7, 12.99);
productArray[3] = new Product("BOceans Eleven", 11, 9.99);
productArray[4] = new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69);
/*// Loop as many times as your counter variable
{
// Instantiate a product object
// Prompt for product name and call the set method on your product object
// Prompt for item number and call the set method on your product object
// Prompt for units in stock and call the set method on your product object
// Prompt for unit price and call the set method on your product object
// store product object in array element
//Destroy product object reference
product = null;
// Flush the buffer
input.nextLine();
}*/
// Sort product array by product name using Comparator implementation class
sortProductArray();
// Print sorted array
for ( Product product : productArray[] ) {
if ( counter == 0 )
System.out.printf( "\n%s\n", "Sorted Inventory of DVD movies");
System.out.printf( "\n\n%s%d\n%s%s\n%s%d\n%s%,.2f\n%s%,.2f\n",
"Item Number: ",counter,
"DVD Title: ",productArray[counter].getProductTitle(),
"Copies in stock: ",productArray[counter].getUnitsInStock(),
"Price each disk: $",productArray[counter].getUnitPrice(),
"Value of disks: $",productArray[counter].calcInventoryValue());//End print
counter++;
if ( counter == productArray.length)// on last counter of loop print total
System.out.printf( "\n%s%,.2f\n\n\n",
"Collection Value: $",calcTotalInventoryValue());
}
// Calculate total Inventory value
}
// method to calculate the total Inventory value
private static double calcTotalInventoryValue()
{
double inventoryValue = 0;
// Iterate array of product objects and calculate total value of entire Inventory
for ( Product product : productArray ) {
// accumulate inventory value from each product object in array
inventoryValue += productArray.calcInventoryValue();
}
return totalInventoryValue;
} // end method calcInventoryValue
// method to sort product array
private static void sortProductArray()
{
Arrays.sort( productArray, new ProductComparator() );
} // end method calcInventoryValue
}
This
Product Product[] = new Product[ARRAY_LENGTH];
should be this:
Product productArray[] = new Product[ARRAY_LENGTH];
-- Edit
You'll also need to change relevant lines referring to this 'variable'.
If I may suggest, if you're confused by this, you ask your teacher/book to refresh your memory on "variables".
And don't worry if you don't get it: keep asking until you do. You're cut out for it if you're interested enough to learn. So be interested, ask questions, do your own research, and life will be good.
You either have to have an array of Product as a member of the InventoryPart2 class OR passed into the sortProductArray method. You'll have to change that method to return a reference to the sorted array if you choose the latter.
Your Product array is in the static main method and not part of the object, so you've got a problem. I'd recommend that you do something like this:
public class Inventory
{
private static final int DEFAULT_INVENTORY_SIZE = 5;
private Product [] products;
private int numProducts;
public Inventory()
{
this(DEFAULT_INVENTORY_SIZE);
}
public Inventory(int size)
{
products = new Product[size];
numProducts = 0;
}
public void addProduct(Product p)
{
products[numProducts++] = p;
}
public void sort()
{
// sort the array here
}
public String toString()
{
StringBuilder builder = new StringBuilder(1024);
// Create a string representation of you inventory here
return builder.toString();
}
}
Object oriented programming is about encapsulation and information hiding. Write the class in such a way that clients don't have to know or care whether you're using an array or something else to hold onto Products. You're abstracting the idea of Inventory here.
UPDATE:
This is your code, only better and running:
import java.util.Scanner;
import java.util.Arrays;
public class InventoryPart2
{
public static void main(String[] args)
{
final int ARRAY_LENGTH = 5;
final int version = 2;
int counter = 0;
Product productArray[] = new Product[ARRAY_LENGTH];
System.out.printf("\n%s%d\n",
"Welcome to the Productentory Program v.", version);
productArray[0] = new Product("EThe Invisible Man", 0, 8.50);
productArray[1] = new Product("DThe Matrix", 1, 17.99);
productArray[2] = new Product("CSe7en", 7, 12.99);
productArray[3] = new Product("BOceans Eleven", 11, 9.99);
productArray[4] = new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69);
productArray = sortProductArray(productArray);
// Print sorted array
for (Product product : productArray)
{
if (counter == 0)
{
System.out.printf("\n%s\n", "Sorted Inventory of DVD movies");
}
System.out.printf("\n\n%s%d\n%s%s\n%s%d\n%s%.2f\n%s%.2f\n",
"Item Number: ", counter,
"DVD Title: ", product.getProductTitle(),
"Copies in stock: ", product.getUnitsInStock(),
"Price each disk: $", product.getUnitPrice(),
"Value of disks: $", product.calcInventoryValue());
counter++;
}
System.out.printf("\n%s%,.2f\n\n\n",
"Collection Value: $", calcTotalInventoryValue(productArray));
}
private static double calcTotalInventoryValue(Product[] productArray)
{
double inventoryValue = 0;
for (Product product : productArray)
{
inventoryValue += product.calcInventoryValue();
}
return inventoryValue;
}
private static Product[] sortProductArray(Product[] productArray)
{
Arrays.sort(productArray, new ProductComparator());
return productArray;
}
}
I removed those comments you add everywhere. They're just clutter; I'd recommend that you not do that anymore. Better to make your code more readable and self-documenting by using better variable and method names.
This still isn't the way I'd recommend that you write it, but it works. You're more likely to see why this works if I don't alter it too much.
UPDATE 2:
Just in case you're interested, here's how I might write it:
import java.util.Scanner;
import java.util.Arrays;
import java.text.NumberFormat;
public class Inventory
{
private static final int DEFAULT_LENGTH = 5;
private static final int VERSION = 2;
private Product[] products;
private int numProducts;
public static void main(String[] args)
{
Inventory inventory = new Inventory(5);
inventory.addProduct(new Product("EThe Invisible Man", 0, 8.50));
inventory.addProduct(new Product("DThe Matrix", 1, 17.99));
inventory.addProduct(new Product("CSe7en", 7, 12.99));
inventory.addProduct(new Product("BOceans Eleven", 11, 9.99));
inventory.addProduct(new Product("AHitch Hikers Guide to the Galaxy", 42, 18.69));
System.out.println(inventory);
System.out.println("total value: " + NumberFormat.getCurrencyInstance().format(inventory.getTotalValue()));
}
public Inventory()
{
this(DEFAULT_LENGTH);
}
public Inventory(int size)
{
products = new Product[size];
this.numProducts = 0;
}
public void addProduct(Product p)
{
products[numProducts++] = p;
}
public double getTotalValue()
{
double inventoryValue = 0.0;
for (Product product : products)
{
inventoryValue += product.calcInventoryValue();
}
return inventoryValue;
}
public String toString()
{
StringBuilder builder = new StringBuilder(1024);
String newline = System.getProperty("line.separator");
if (products.length > 0)
{
Arrays.sort(products, new ProductComparator());
for (Product product : products)
{
builder.append(product).append(newline);
}
}
return builder.toString();
}
}
I think "productArray" is supposed to refer to the array of products you've created. So on the line:
Product Product[] = new Product[ARRAY_LENGTH];// create array Product of class Product
Change it too:
Product[] productArray = new Product[ARRAY_LENGTH];
Don't think to yourself that everyone here started out being able to spot syntax errors in a matter of seconds. We weren't born this way, we just know what to look for because we've made the exact same mistake hundreds of times.
So if you're convinced you want to be a programmer even when you're at your wits end because of stuff like this you are cut out for it. Dedication and passion are far more important than natural talent.
Keep your head up. We'll be here the next time you get stuck. :)