Car Search java - java

In one of my classes we created a program that randomly creates 10 cars with the price and star rating. Right now the program creates the 10 objects and then creates another object that it compare the 10 to. It searches by the star rating, sorts the 10 by star rating, then runs a binary search on the 10 objects. I have been trying to improve on it by adding in the car manufacturer name to each object but keep messing up the program. The program has two classes
import java.util.*;
import java.util.Scanner;
public class Sorter{
static Car [] ary; // declare
final static int NUM_CARS = 10;
public static void main() {
//Scanner rating = new Scanner(System.in);
//int r = rating.nextInt();
Car key = new Car();
ary = new Car[NUM_CARS]; // initialize
int i;
int position;
for (i=0; i<NUM_CARS; i++) {
ary [ i ] = new Car();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(ary));
System.out.println("Sequential search for " + key);
ary[0].reset();
position = sequentialSearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println("Found a position: " +position);
System.out.println();
System.out.println("Sorted:");
ary[0].reset();
Arrays.sort(ary);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println(Arrays.toString(ary));
System.out.println("Binary search for " + key);
ary[0].reset();
position = binarySearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Found a position: " +position);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
}
public static int binarySearch (Car keyCar) {
return Arrays.binarySearch(ary,keyCar);
}
public static int sequentialSearch (Car keyCar) {
int pos = -1;
int i;
int answer;
for (i=0; i<ary.length; i++) {
answer = ary[i].compareTo(keyCar);
if (answer==0) {
pos = i;
break;
}
}
return pos;
}
}
Second class
import java.util.*;
/**
* in class work
*/
public class Car implements Comparable<Car> {
// instance variables - replace the example below with your own
int stars;
double price;
String name [] = {"Ford", "Dodge", "Chevrolet", "Honda", "Toyota", "VW", "Hyundai"};
int myCounter;
static int allCounter;
/**
* Constructor for objects of class Sorter
*/
public Car() {
Random generator = new Random ();
price = generator.nextDouble()*50000 + 50000;
stars = generator.nextInt(5)+1;
reset();
}
public String toString()
{
return String.format("$%,7.0f(%d stars)",price,stars);
//$ put dollar sign infront
//up to 7 digits
//, puts commas
}
/**
* Resets counter to zero
*/
public void reset(){
myCounter=0;
allCounter=0;
}
public int getMyCount() {
return myCounter;
}
public int getAllCount() {
return allCounter;
}
/**
* #param other A house to compare to.
* #return Returns 0 if they are equal
*/
public int compareTo(Car other)
{
myCounter++;
allCounter++;
if (this.stars < other.stars) {
return -1;
} else if (this.stars> other.stars) {
return +1;
}
return 0; // equals
}
}
How do I make it so that the objects will display the price, star rating, and the manufacturer?
Also, another thing I'd like to do but haven't tried yet is making it so the user can input what star rating they want and it'll display those cars only. This part is the next thing I'd like to try when time comes around to do so.

To associate data with an object, a variable to store that data needs to be in the object's constructor. So, to associate a manufacturer with each car object, you'll have to add String manufacturer or something similar as a variable in your Car class's constructor. It seems like you would then want to set that manufacturer variable to a random element of your String name [] array.
To make the car "display" the manufacturer variable you just created, you would have to modify the toString() method in your car class to print manufacturer as well as price and stars.

Related

The array from another class doesn't update when scanner is used

When I try to use scanner on another class I can't update the array.
private int numClients;
private int[] clients;
These are variables from my class Rooms.
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients = new int[numClients];
}
Of course I added setters and getters:
public String getName() {
return name;
}
public void setNaziv(String name) {
this.name = name;
}
public int getNumRooms() {
return numRooms;
}
public void setNumRooms(int numRooms) {
this.numRooms = numRooms;
}
public int getNumClients() {
return numClients;
}
public void setNumClients(int numClients) {
this.numClients = numClients;
}
When I tried to add it to test it in another class, name and numRooms change. numClients change too but array doesn't update.
Hotel h1 = new Hotel(" ", 0, 0);
String name= sc.nextLine();
h1.setName(name);
int numRooms= sc.nextInt();
h1.setNumRooms(numRooms);
int numClients= sc.nextInt();
h1.numClients(numClients);
h1.show();
This is the show method:
public void show(){
System.out.println("Name: " + this.name);
System.out.println("Rooms: " + this.numRooms);
System.out.println("Number of clients: " + this.numClients);
for(int i = 0; i < clients.length; i++) {
System.out.println(clients[i]);
}
}
Maybe there will be some typing errors I translated the var names to English for question purposes.
Once you have created the array, it's size is fixed. You can test this with a few rows:
int size = 10; // Start with size 10
int[] array = new int[size]; // Array is 10 elements long
System.out.println(size); // Prints 10
System.out.println(array.length); // Also prints 10
size = 1000; // Change size ??
System.out.println(size); // Prints 1000
System.out.println(array.length); // Still prints 10
Output:
10
10
1000
10
You also don't appear to actually set any elements in the array in your code. That would be something like
h1.getClients()[0] = 3;
Edit
When this line in your constructor is exectuted:
this.clients = new int[numClients];
The array is created with the size that numClients has right at that moment. After that, there is no relation between numClients and clients anymore.
You would need to create a new array, copy contents (if you want to preserve it) and reassign clients with the new array in order to change the size.
You can do this with Arrays.copyOf() :
int newLength = 20;
array = Arrays.copyOf(array, newLength);
System.out.println(array.length); // Prints 20!!
The constructor will run once for a single object. So, if you want to add more values in the clients array then a method is a must.
The main Class:
class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel("romeo",5,10);
hotel.addClients(6);
hotel.addClients(10);
hotel.addClients(5);
hotel.show();
}
}
The Hotel Class:
class Hotel{
private int numRooms,numClients;
private String name;
private int clients[] = new int[10];
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients[0] = numClients;
}
The method to add Clients in the clients array:
public void addClients(int numClients){
for(int i = 0; i < clients.length; i++){
if(clients[i] == 0){
clients[i] = numClients;
break;
}
}
}
Show method output:
Name: romeo
Rooms: 5
Number of clients: 10
10
6
10
5
The Total number of clients can be found by summation of the clients array.
To make the array dynamic, the linked list data structure can be applied.
What I did to fix this without updating and making new methods is defining values with scanner and putting it into constructor.
public void test(){
Scanner sc = new Scanner(System.in);
System.out.print("Type in the name of Hotel: ");
String name= sc.nextLine();
System.out.print("Type in number of rooms: ");
int numRooms = sc.nextInt();
System.out.print("Type in the number of clients");
int numClients= sc.nextInt();
Hotel h1 = new Hotel(name, numRooms, numClients);
h1.show();
}

Creating multiple objects of the same type with user input?

I'm trying to make a program with three class files, two Objects files and one Main that accesses both and runs operations. The first object file creates objects with one parameter, and then assigns attributes to itself based on said parameter, for example.
public class People {
private int height, weight;
private String specificPerson;
public People(String person){
this.specificPerson = person;
this.height = person.length * 12;
this.weight = person.length * 40;
}
public int getHeight(){return height;}
public int getWeight() {return weight;}
}
These objects are then stored within the array of another object which has a capacity and an array:
public class peopleIndexer {
private int pcapacity, size;
private String[] peopleArray;
public peopleIndexer(int capacity){
this.pcapacity = capacity;
this.peopleArray = new String [capacity];
}
public int getCapacity(){
return pcapacity;
}
public int[] getInfo(String person){
int[] getInfo = new int[2];
int found = Arrays.binarySearch(peopleArray,person);
getInfo[0] = ?.getHeight();
getInfo[1] = ?.getWeight();//I dont know the object name yet so I put "?" for I am not sure
System.out.println("Person" + person + "is " + getInfo[0] + "tall and " + getInfo[1] + " pounds.");
}
}
What I need to know is how to allow the user to make multiple people in the list with input that I can then allow them to retrieve later, for example:
String user_input;
People user_input = new People("user_input");
So that if the users input were to be jack, ryan, and nick, I would have three objects placed in the peopleIndexer as such:
People jack = new People(jack);
People ryan = new People(ryan);
People nick = new People(nick);
Your People constructor takes only one argument and creates a People object..You do not have setters for some of your private variables in the peopleIndexer class, so best to have your main method as part of the peopleIndexer class.
Your "length" attribute in the People constructor is not initialized or declared anywhere, so let's assume it's not there. You must change your "private String[] peopleArray;" to be "private People[] peopleArray;" in order to have people in the array.
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int capacity;
int peopleCount = 0; //used to keep track of people we have in our array
String person = "";
// get the capacity from the user
System.out.println("Enter the number of people you want to capture: ");
capacity = Integer.parseInt(input.nextLine());
//create peopleIndexer object using the given capacity
peopleIndexer pIndexer = new peopleIndexer(capacity);
while(peopleCount < capacity){
//prompt the user for the "People" name, this is the only attibute we need according to your constructor.
System.out.println("Enter person "+(peopleCount + 1)+" name: ");
person = input.nextLine();
//add a new person into the array
peopleArray[peopleCount] = new People(person);
//increase the number of people captured
peopleCount += 1;
}
}

Increment map value when meeting conditions

I have hit a brick wall and the revision book isn't much help as it provides flat examples, my revision assignment requires me to declare a local variable of a type to reference a list, Teams, then if should get the list of teams for the key value division, and assign it to the local variable.
It then ask me to increment the number of wins for teamA if it has a higher score than teamB and vice versa, if it is a draw then increment the number of draws.
I have managed to write the method to iterate over the list and an if-else statement to check he given arguments using a .get() method which works
The problem I am having is accessing in the incWon() method in the Team class to change the value of won for each map value. The material though gives quite flat examples of how map values are to be changed which don't really explain how I can change a value using a dynamic input.
any help would be greatly appreciated as if I can get won to work the rest will fall into place.
This is my class
{
private SortedMap<String, Set<Team>> teams;
/**
* Constructor for objects of class LeagueAdmin
*/
public LeagueAdmin()
{
// Create the HashMap
//Map<String, Team> teams = new HashMap<>();
super();
this.teams = new TreeMap<>();
}
public void addTeam(String division, Team team)
{
boolean changed;
if (!this.teams.containsKey(division)) // checks if the key division doesn't contain the value of divsioin
{
HashSet<Team> teamSet = new HashSet<>(); // instantiates a list of objects called Team and assigns them to local variable teamSet
teamSet.add(team); // adds a new team to the list
this.teams.put(division, teamSet);
changed = true;
}
else
{
Set<Team> teamSet = this.teams.get(division); // if list exists already adds new team to existing list
changed = teamSet.add(team);
}
}
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
Set<String> teamKeys = teams.keySet();
for (String eachDivision: teamKeys)
{
if(teamAScore > teamBScore)
{
teams.put(); // updates wins for teamA
// System.out.println(teamA);
}
else if (teamAScore < teamBScore)
{
teams.get(teamB); // updates wins for teamB
// System.out.println(teamB);
}
else
{
// teams.put(); //updates draws for both teams
}
// System.out.println(eachDivision + " teams are " + teams.get(eachDivision));
}
}
}
and this the TEAM class I am have to access to increment values.
public class Team
{
private String name;
private String division;
private int won;
private int drew;
private int lost;
// no need to record points as = 3*won + drew
/**
* Constructor for objects of class Team
*/
public Team(String aName, String aDivision)
{
name = aName;
division = aDivision;
// no need to set won, drew and lost to 0
}
/**
* getter for attribute points
*/
public int getPoints()
{
return 3 * won + drew;
}
/**
* getter for name
*/
public String getName()
{
return name;
}
/**
* getter for division
*/
public String getDivision()
{
return division;
}
/**
* getter for won
*/
public int getWon()
{
return won;
}
/**
* getter for drew
*/
public int getDrew()
{
return drew;
}
/**
* getter for lost
*/
public int getLost()
{
return lost;
}
/**
* increments the number of games won
*/
public void incWon()
{
won = won + 1;
}
/**
* increments the number of games drawn
*/
public void incDrew()
{
drew = drew + 1;
}
/**
* increments the number of games lost
*/
public void incLost()
{
lost = lost + 1;
}
/**
* setter for division
*/
public void setDivision(String aDivision)
{
division = aDivision;
}
public String toString()
{
return ("Team " + name + ", division: " + division + " stats: Won: " + won
+ ", drew: " + drew + ", lost: " + lost + ", points: " + getPoints());
}
}
I think you misunderstood the data structure requirement. You're looping through a list of teams, and never updating the loop variable. I believe the data structure should be something more like this:
private Map<String, Map<String, Team>> teams;
Using the division for the outer map key, and the team name for the inner map key. This separates div1's teamA from div2's teamA
This simplifies your recordResult method to pulling the specific team and updating them accorrdingly
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
Map<String, Team> teamKeys = teams.get(division);
if(teamAScore > teamBScore)
{
teams.get(teamA).incWon(); // updates wins for teamA
}
else if (teamAScore < teamBScore)
{
teams.get(teamB).incWon(); // updates wins for teamB
}
else
{
teams.get(teamA).incDrew();
teams.get(teamB).incDrew();
}
}

How to find Values stored in object in an Array list in Java

I have read a lot of posts about this and nothing I've tried seems to work. Any help would be greatly appreciated.
I have 2 Classes, ColouredShape and ShapeMatchingGame.
I'm trying to create ColouredShape objects using 2 arguments and add them to an ArrayList in the ShapeMatchingGame Class.
I need 4 shapes and 3 colours of each of the 4 shapes * 3, so 36 items in the array.
I can see 36 objects are adding to the array in the loop but whenever i try to access the values of the objects in the array im not seeing the expected values for the object at its index.
I guess what I'm trying to ask is am I accessing the values incorrectly or have I done something wrong with creating the objects and adding them to the array?
public class ColouredShape {
static int shapeValue;
static int colourValue;
static String colour, shape;
public ColouredShape() // Default constructor
{
this.shapeValue = 1;
this.colourValue =1;
this.colour ="";
this.shape ="";
}
public ColouredShape (int shapeValue,int colourValue) // Constructor with 2 arguments
{
this.shapeValue = shapeValue;
this.colourValue =colourValue;
this.colour = colour;
this.shape =shape;
}
public int getColour()
{
return colourValue;
}
public int getShape()
{
return shapeValue;
}
public class ShapeMatchingGame {
static int noShapes;
static ArrayList<ColouredShape> ColouredShapes = new ArrayList<ColouredShape>();
static int index;
static int shapeValue=1;
static int colourValue;
public static void main(String[] args)
{
ObjectCreation();
}
public static void ObjectCreation()
{
do// runs loops 3 times to create 3 of every shape/colour combo
{
do // loop to continue onto the next shape until 4 are created
{
do // loop to create 3 of colours of same shape
{
colourValue++;
System.out.println("Shape value " +shapeValue + " colour value " +colourValue);
ColouredShape gameShapes = new ColouredShape(shapeValue,colourValue);
ColouredShapes.add(gameShapes);//creates an object of colourshapes and passes the current shapevalue + colourvalue as arguments then adds it to the arraylist
System.out.println ("Value of object at array index "+ index + " shape value " + ColouredShapes.get(index).getShape()+" colour value " +ColouredShapes.get(index).getColour()+ "colour variable value = " + colourValue);
index++;
for (ColouredShape colouredShape : ColouredShapes)
{
System.out.println(colouredShape.getClass().getName() + "/" +
colouredShape.shape + "/" +
colouredShape.colour);
}
}while(colourValue < 3 );
System.out.println ("Value of object at array index "+ "0" + " shape value " + ColouredShapes.get(0).getShape()+" colour value " +ColouredShapes.get(0).getColour()+ "colour variable value = " + colourValue);
colourValue=0;//reset colourValue to allow next iteration of the loop
shapeValue++;//incrementing shapeValue to add colours to next shape
System.out.println ("Value of object at array index "+ "0" + " shape value " + ColouredShapes.get(0).getShape()+" colour value " +ColouredShapes.get(0).getColour()+ "colour variable value = " + colourValue);
}while(shapeValue < 5 );
shapeValue=1; // resetting shapeValue to allow next iteration of the loop
noShapes++;
}while (noShapes<3);
}
}
There are several problems on your ColouredShape:
shapeValue and colourValue are static. This means there they are 'global' variables. Doesn't matter how many Colouredshapes you create, all of them will have the same values
the constructor sets the value of the static variables only, and you print the values of the string text.
Change the Object to be like this:
public class ColouredShape {
int shapeValue;
int colourValue;
public ColouredShape() // Default constructor
{
this.shapeValue = 1;
this.colourValue = 1;
}
public ColouredShape(int shapeValue, int colourValue) // Constructor with 2
// arguments
{
this.shapeValue = shapeValue;
this.colourValue = colourValue;
}
public int getColour() {
return colourValue;
}
public int getShape() {
return shapeValue;
}
}
and the result should be as expected

accessing objects in an array Java

I am having trouble understanding how to set and get objects in an array. Please keep it basic/simple; I am a beginner.
I cannot use a list as I am not there yet in my java class. We are supposed to use regular arrays.
I am building a program that creates solar system objects and puts planet objects in the solar system object array. I have to be able to insert the planet by index as well as get it by index.
Getting regular object info was simple but once arrays were added. It got tough. I understand better when I can comprehend how and why something works. Here is my code. Many thanks in advance!
Planet Class
public class Planet {
// private fields
private String planetName;
private int numMoons;
// param constructor
public Planet(String n, int m){
planetName = n;
numMoons = m;
}
public String toString(){
return planetName + " " + numMoons;
}
public void setPlanetName(String n){
this.planetName = n;
}
public String getPlanetName(){
return planetName;
}
public void setNumMoons(int m){
this.numMoons = m;
}
public int getNumMoons(){
return numMoons;
}
}
Here is the SolarSystem class
package project03;
public class SolarSystem {
private String solarSystemName;
private Planet[] allPlanets = new Planet[8];
private int numPlanets;
public SolarSystem(String ss, int np){
solarSystemName = ss;
numPlanets = np;
}
public void setSolarSystemName(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
/*public void setAllPlanets(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
*/
}
Finally here is my driver class that houses the main method
package project03;
public class Driver {
public static void main(String[] args) {
// creates planet object
Planet Mercury = new Planet("Mercury", 0);
Planet Venus = new Planet("Venus", 0);
Planet Earth = new Planet("Earth", 1);
Planet Mars = new Planet("Mars", 2);
Planet Jupiter = new Planet("Jupiter", 67);
Planet Saturn = new Planet("Saturn", 62);
Planet Uranus = new Planet("Uranus", 27);
Planet Neptune = new Planet("Neptune", 14);
SolarSystem ourSolarSystem = new SolarSystem("Sol-System", 8);
System.out.println("Planet name is : " + ourSolarSystem.getSolarSystemName());
//System.out.println("Moon number is :" + Mercury.getNumMoons());
}
}
You are missing a couple of methods from your SolarSystem class
public void setPlanet (Planet planet, int pos) {
allPlanets [pos] = planet; // pos is zero based
}
public Planet getPlanet (int pos) {
return allPlanets [pos]; // pos is zero based
}
Then you can use it as
ourSolarSystem.setPlanet (Mercury, 0);
You have to add methods in your solar system class to add objects to the internal array.
to populate an array , you need 2 things
1. Size
2. Elements.
Your solar system class has provisions for none at this point. Size is hardcoded to 8, which is fine for this example, ideally it should be passed in constructor while creating a solar system.
Ignoring that for a moment, you should add method in the class to add a planet.
Since this is for your learning, I am not adding exact code, just algorithm
public void addPlanet(Planet p, int pos){
//check pos is less than array size
// add planet to the index pos if pos is less than size.
}
You could also create an array outside and add it to the solar planet
public void addPlanets(Planet[] planetArray){
// replace current planet array with the array passed in input
}
The array outside can be created easily
Planet[] planetArray = new Planet[8];
planetArray[0] = Mercury ;
// and so on.

Categories