Adding an Object to an Object Array - java

Goal: Add a new Movie object to an existing Movie[] if there is room to add.
Code:
// Create the new Movie object
Movie movieToAdd = new Movie (newTitle, newYear);
// Add it to the Array
count = addMovie(movieList, movieToAdd, count);
Method Code:
public static int addMovie (Movie[] movieArray, Movie addMe, int count)
{
if (count != movieArray.length)
{
count++;
movieArray[count] = addMe;
System.out.println("Movie added successfully!");
}
else
{
System.out.println("Array size of " + movieArray.length + " is full. Could not add movie.");
}
return count;
}
QUESTION:
Currently, when the movieList array is printed out, the new entry prints as null even though the created Movie object will print just fine outside of the way. Therefore, I'm assuming the best way to add the addMe object into the array is to create a second new Movie object initialized within the array and build it piece by piece (so addMe will remain in memory, and a "copy" of addMe will be set into the array).
This to me doesn't feel very efficient (I hate extra data laying about...). Is there a better way to do this?
NOTE: The Movie object actually has 10 private data members. For this exercise I only needed to pass in two parameters and set defaults for the rest. You can imagine why I don't to use ten GET statements to build this array and have extra objects stuck in memory...
EDIT:
Current Print Out (Portions):
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
7
Let's add the information for the new movie. Give me a Title and 4-digit Year, and I'll fill in the rest.
Title?
Me
Year of Release?
Please enter a valid 4 digit year: 1000 to 9999:
1213
Movie added successfully!
Menu options:
1. Show all movies:
2. Show movies sorted - manual
3. Show movies sorted - auto
4. Show Movie by Index
5. Search for movie Linearly
6. Search for movie using Binary Search
7. Add a movie
20. Quit
Please choose an option from the menu: 1 to 20:
25 | Les Vampires (1915) | Louis Feuillade | "Edouard Mathe, Marcel Levesque" | 1915 | 0 | http://www.imdb.com/title/tt0006206/ | http://www.guardian.co.uk/film/movie/117077/vampires | France | Horror | 175
null | 176
=============================================================================
MORE EDITS:
Constructor and Setters code - all this SHOULD be working right though.
public Movie (String t, int y)
{
// passed in
this.title = setTitle(t);
this.year = setYear(y);
// defaults
this.ranking = 0;
this.director = "No Director";
this.actors = "No Actors";
this.oscars = 0;
this.linkIMDB = "No IMDB Link";
this.linkGuardian = "No Guardian Link";
this.country = "No Country";
this.genre = "No Genre";
}
public String setTitle (String newTitle)
{
if (newTitle == null)
{
this.title = "No Title";
}
else
{
this.title = newTitle;
}
return this.title;
}
public int setYear (int newYear)
{
if (newYear >= 999 && newYear <=10000)
{
this.year = newYear;
}
else
{
newYear = 0000;
}
return this.year;
}

It isn't clear what you are asking, but this portion is incorrect:
count++;
movieArray[count] = addMe;
What if movieArray.length is 10, and count is 9? Then it will pass the count != movieArray.length check and then you will try to assign the element at index 10. Use post increment:
movieArray[count++] = addMe;

GOT IT!
I was using Count to set the index at which the new movie was stored.
Original count was 176.
Last index was 175.
I was increment BEFORE setting the movie, so the movie was being set at index 177.
So 176 was getting skipped.
It was only printing to 176 because that was the actual count, which wasn't accounting for the skipped space (there was an extra object in the array that wasn't getting printed).
(Figured this out when I attempted adding 2 new Movie objects to the array and got a null and then the first object only on print).
Solved by switching the set and the increment:
if (count <= movieArray.length)
{
movieArray[count] = addMe;
count++;
System.out.println("Movie added successfully!");
}

Related

How to calculate some specific data function from the data of a large CSV file

I'm trying to work out the most expensive county to rent a building from data in a CSV file. The data from each column I need the data from has been put into a list. The price range is set by the user so the outer most for loop and if statement ensure that the buildings considered are in the set price range.
The price of a building is also slightly complicated because the price is the minimum stay x price.
In the code below I am trying to get the average property value of one county just son I can get the basic structure right before I carry on, but I'm kind of lost at this point any help would be much appreciated.
public int sampleMethod()
{
ArrayList<String> county = new ArrayList<String>();
ArrayList<Integer> costOfBuildings = new ArrayList<Integer>();
ArrayList<Integer> minimumStay = new ArrayList<Integer>();
ArrayList<Integer> minimumBuildingCost = new ArrayList<Integer>();
try{
//Code to read data from the CSV and put the data in the lists.
}
}
catch(IOException | URISyntaxException e){
//Some code.
}
int count = 0;
int avgCountyPrice = 0;
int countyCount = 0;
for (int cost : costOfBuildings) {
if (costOfBuildings.get(count) >= controller.getMin() && costOfBuildings.get(count) <= controller.getMax()) {
for (String currentCounty: county) {
for (int currentMinimumStay: minimumStay) {
if (currentCounty.equals("sample county")) {
countyCount++;
int temp = nightsPermitted * cost;
avgCountyPrice = avgCountyPrice + temp / countyCount;
}
}
}
}
count++;
}
return avgCountyPrice ;
}
Here is a sample table to depict what the CSV looks like, also the CSV file has more than 50,000 rows.
name
county
price
minStay
Morgan
lydney
135
5
John
sedury
34
1
Patrick
newport
9901
7
Let’s describe the algorithm of your task: Group the CSV file by county, calculate the average price in each group, and find the country that has the highest average price for buildings. The code will be rather long if you try to finish the task using Java. It is convenient and simple to get this done in SPL, the open-source Java package. The language only needs one line of code:
A
1
=file("data.csv").import#ct().groups(county;avg(price):price_avg).top(-1;price_avg).county
 
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as mostExpensiveCounty.splx and invoke it in Java in the same way you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call mostExpensiveCounty()");
st.execute();
…

Create Global Multidimensional Array dynamically in Java

I have an Ordering System that comprises of a number of steps before the data is finally submitted and stored in the database. I have already completed and implemented the web version of the same Ordering System. Below is the Multidimensional Array in PHP that I created dynamically based on the below values.
In the first step of Order, a Plan is to be selected. Based on that plan, the total number of days will be decided.
Plan 1 - Days Served 26
Plan 1 - Meals Served Per Day 2
Plan 1 - Refreshments Served Per Day 2
Plan 2 - Days Served 5
Plan 2 - Meals Served Per Day 3
Plan 2 - Refreshments Served Per Day 0
and so on...
In the second step, starting date of the Order is to be selected. Weekends are to be excluded and only Weekdays will be counted as days served.
The PHP Multidimensional Array generated dynamically is below
Array
(
[Day 1] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
[Day 2] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
In the above code, day number is added dynamically and numeric value in meal_id_1, meal_code_1 and meal_type_1 is also added dynamically.
To connect the App and Web Application logically, I want to post the selection from the App in similar Array.
Since I have Meals and Refreshments to be selected based on the plan, therefore I will be loading Meals for Day 1 and then based on the Plan selected Refreshments for Day 1. There will be 1 Activity for Meals, which be loaded with updated Day number and same for the Refreshments.
Using the below code, I am able to get the Unique ID of the Meals selected in an ArrayList.
int count = 0;
int size = list.size();
List<String> selected_meals = new ArrayList<String>();
for (int i = 0; i<size; i++){
if (list.get(i).isSelected()){
count++;
String selected_meal_string = list.get(i).getMeal_id();
selected_meals.add(selected_meal_string);
}
}
How can I transfer this selection to a Global Multidimensional Array so that in the final step I can post it to be saved in the database?
as per my comment I think you are really looking to use a class here, please see the example below to get you started. You may require some research into how OOP (Object Oriented Programming) works though.
public class Meal {
//I dont know what type of data each attribute is supposed to be so I chose ints. Feel free to change.
private int mealId;
private int mealCode;
private int mealType;
public Meal(int mealId, int mealCode, int mealType){
this.mealId = mealId;
this.mealCode = mealCode;
this.mealType = mealType;
}
public int getMealId() {
return mealId;
}
public int getMealCode() {
return mealCode;
}
public int getMealType() {
return mealType;
}
}
Now the Day class:
import java.util.ArrayList;
public class Day {
private ArrayList<Meal> meals = new ArrayList<>();
public Day(Meal...meals){
//This uses magic params to allow you to pass in as many meals as you want.
for(Meal meal : meals){
this.meals.add(meal);
}
}
public ArrayList<Meal> getMeals() {
return meals;
}
}
Now wherever your main method is:
import java.util.ArrayList;
public class Control {
public static void main(String [] args){
ArrayList<Day> days = new ArrayList<>();
//Create your meals.
Meal meal1 = new Meal(1, 1, 1);
Meal meal2 = new Meal(2, 3, 4);
//Add the meals to a day.
Day day1 = new Day(meal1, meal2);
//Add the day to the list of days.
days.add(day1);
//Getting the meal code for the first meal on the first day. This looks complex, but you would likely break it down before getting values.
System.out.println(days.get(0).getMeals().get(0).getMealCode());
}
}

How to retrieve previous values from HashMap?

I have the following code where I'm reading from a text file. The text file i as follows:
111 Laptop 500 10
222 Mobile 120 8
333 Notebook 4 100
444 Chocolates 3 50
555 Guitar 199 5
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5
If the user enters ID as 111, the following should be the output:
111 Laptop 500 10
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5
I'm storing the the contents of the text file in a HashMap. Here is the code:
public void comparableItems(String ID)
{
File f = new File("C://Class/items.txt");
HashMap<String, Item> map = new HashMap<String, Item>();
try
{
Scanner scan = new Scanner(f);
while(scan.hasNext())
{
String line = scan.nextLine();
String temp[] = line.split(" ");
Item it = new Item(temp[0], temp[1], Double.parseDouble(temp[2]), Integer.parseInt(temp[3]));
map.put(it.itemID, it);
}
if(map.containsKey(ID))
{
Item item = map.get(ID);
if(item.price>=item.price+100 && item.price<=item.price-100)
{
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Here is the Item class:
public class Item
{
String itemID;
String itemName;
double price;
int quantity;
public Item(String itemID, String itemName, double price, int quantity)
{
this.itemID = itemID;
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
public void printItemDetails()
{
System.out.println("ID\tItemName\tUnitPrice\tQuantity");
System.out.println("===================================================");
System.out.println(this.itemID+ "\t" +this.itemName+ "\t" +this.price+ "\t"+this.quantity);
}
}
How do I get the desired output? I'm in the learning stages of Java Collections. So please bear with me.
Can someone help me here?
Thanks!
Your Map isn't doing you much good. Since you know what reference item ID you're looking for before you even parse the file, you could just capture that item when (and if) you see it during the parse. You do need some kind of collection to hold all the other items, but a List would be a better choice for this particular task.
In any case, the thrust of your question seems to be about examining all the other items you parse from the file. For this, you want to iterate over the Map's values() view (and to get your comparisons right):
for (Item otherItem : map.values()) {
if((otherItem.price <= item.price + 100)
&& (otherItem.price >= item.price - 100)) {
otherItem.printItemDetails();
}
}
If you collected the items in a List instead of a Map, then you would replace map.values() in the above with just list (or whatever name you use for the List).
For what you say you want (items with prices near the desired item), a HashMap isn't an efficient datastore.
However, since it sounds like this is your homework, once you use map.get("111") to get your laptop, get the price P, and then iterate over the hashmap to get any item whose price is within your desired delta of P. The Collections tutorial tells you how to iterate over a collection.

How to retain newly added values on a two-dimensional array (JAVA)

I'm stuck at this part of my program. These are 2 options for my Student Information System (not using GUI/JOption and without linking to a database. I already have a 2-dimensional array (String records[][] = new String [5][3];) that has the first 2 "rows" ([0][0] to [0][2] and [1][0] to [1][2]) filled up with pre-assigned data (First Name, Last Name, Course).
If you look below, the part where "b" or "B" option is selected, this is for adding new values to a new array (incremented so that when option B is used, it will assign first [2][0], then [3][0]
and so on). It seemed to work since it does show that all the data I've entered was added and is displayed in the proper order. THE PROBLEM IS: when I choose 'Y" to return to the top menu and select option A to VIEW the newly added record (using ID number 2), it shows that it contains all "null". Is there something I've missed? This is the missing step I need in order to finish this program. Thanks ahead for the help.
if("a".equals(option1)|| "A".equals(option1)){
System.out.println("Please enter the Student ID for the record to view.");
String a = reader1.readLine();
idcheck = Integer.parseInt(a);
x1=idcheck;
for(int y=0;y<3;y++){
System.out.print(records[x1][y] + " ");
}
System.out.println("\nReturn to Main Menu or Exit? (Y/N)");
cont1= reader1.readLine();
}
else if("b".equals(option1)||"B".equals(option1)){
arr_count++;
for (int y = 0; y<3;y++){
System.out.println("Enter Value for "+ option [y]+":" );
String X = reader1.readLine();
records[arr_count][y] = X;
}

How do I populate a "ragged" array with values of a text file being read?

I'm new to Stack Overflow, and this is my first question/post! I'm working on a project for school using Java. The first part I'm having trouble with inolves:
Read each line in a file (listed at the end of my post) one time
Create a "ragged" array of integers, 4 by X, where my 4 rows will be the "region number" (the number found in the Nbr of Region) column, and fill each column with the state population for that region.
So, for example, Row 1 would hold the state populations of Region 1 resulting in 6 columns, Row 2 represents Region 2 resulting in 7 columns, and so on resulting in a "ragged" array.
My question is how to populate, or what would be the best way to populate my array with the results of my file read? I know how to declare the array, initialize the array and create space in the array, but I'm not sure of how to write my method in my State class to populate the results of my file read into the array. Right now I'm getting an "out of bounds" error when I try to compile this code using Netbeans.
Here is my code for Main and State. my input file is listed beneath it:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
// create new jagged array obj and fill it with some
// initial "dummy" values
int[][] arrPopulation =
{
{0,1,2,3,4,5},
{0,1,2,3,4,5,6},
{0,1,2,3,4,5,6,7,8,9},
{0,1,2,3,4,5,6,7,8,9,10}
};//end array declaration
// read in file States.txt, instantiate BufferedReader object,
// set new BufferedReader object to variable #newLine
FileReader f = new FileReader("States.txt");
BufferedReader br = new BufferedReader(f);
String newLine = br.readLine();
for (int rows = 0; rows < arrPopulation.length; rows++)
{
for (int col = 0; col < arrPopulation[col].length; col++) {
System.out.print(arrPopulation[rows][col] + " ");
}
// display on new lines; print out in a "table" format
System.out.println();
} // end for
State newState = new State(newLine);
int count = 0;
while(newLine != null)
{
newLine = br.readLine();
System.out.println(newState.getRegionNum());
}// end while
br.close();//close stream
} // end public static void main
} // end main
This is what I have for my State class so far:
import java.util.*;
public class State
{
private String statePop, stateNum, regionNum;
public State(String fileRead)
{
statePop = fileRead.substring(32,39);
regionNum = fileRead.substring(55,fileRead.length());
} // end constructor
public int getStatePop()
{
int population = Integer.parseInt(statePop);
return population;
} // #method getStatePop end method
public int getRegionNum()
{
int numOfRegion = Integer.parseInt(regionNum);
return numOfRegion;
}// end getRegionNum
public int getAvgPop()
{
int average = 2+2;
return average;
// total number of populations
// divide number of populations
}// #return the average population of states
public int getStateTotal()
{
//initialize static variable
int totalPopulation = 0;
int stateTotal = this.getStatePop() + totalPopulation;
return stateTotal;
} // #return stateTotal
public String toString()
{
return statePop + " " + stateNum + " ";
} // #method end toString method
} // end State class
The names of the columns (not used in the file read, just for explaining purposes) are:
State Capital Abbrev Population Region Nbr of Region
Washington Olympia WA 5689263West 6
Oregon Salem OR 3281974West 6
Massachusetts Boston MA 6147132New_England 1
Connecticut Hartford CT 3274069New_England 1
Rhode_Island Providence RI 988480New_England 1
New_York Albany NY18146200Middle_Atlantic2
Pennsylvania Harrisburg PA12001451Middle_Atlantic2
New_Jersey Trenton NJ 8115011Middle_Atlantic2
Maryland Annapolis MD 5134808Middle_Atlantic2
West_Virginia Charleston WV 1811156Middle_Atlantic2
Delaware Dover DE 743603Middle_Atlantic2
Virginia Richmond VA 6791345Middle_Atlantic2
South_Carolina Columbia SC 3835962South 3
Tennessee Nashville TN 5430621South 3
Maine Augusta ME 1244250New_England 1
Vermont Montpelier VT 588632New_England 1
New_Hampshire Concord NH 1185048New_England 1
Georgia Atlanta GA 7642207South 3
Florida Tallahassee FL14915980South 3
Alabama Montgomery AL 4351999South 3
Arkansas Little_Rock AR 2538303South 3
Louisiana Baton_Rouge LA 4368967South 3
Kentucky Frankfort KY 3936499South 3
Mississippi Jackson MS 2752092South 3
North_Carolina Raleigh NC 7546493South 3
California Sacramento CA32182118West 6
Idaho Boise ID 1228684West 6
Montana Helena MT 880453West 6
Wyoming Cheyenne WY 480907West 6
Nevada Carson_City NV 1746898West 6
Utah Salt_Lake_City UT 2099758West 6
Colorado Denver CO 3970971West 6
Alaska Juno AK 614010West 6
Hawaii Honolulu HI 1193001West 6
Am I on the right track here?
Thanks for any help in advance, and sorry for the long post!
The collections package would be useful here.
Create Map < Integer, List < < Integer > >
As you scan the file one line at a time, grab the region number and population.
Is the region number a key in the map?
No. Then create a new List < Integer > and add it to the map. Now it is.
Add the population to the list.
Now, the map should have four entries. Create the outer array like: int [ ] [ ] array = new int [ 4 ] [ ] ;
Then iterate over the lists in the map and populate the outer array like: array[i]=new int[list.size()];
Then iterate over the list and populate the inner array like: array[i][j]=list.get(j);
thanks for your quick response.
My professor hasn't gone over the Collections package yet (looking at some of the classes in the package, I think we'll go over those things next semester) so I'm not too familiar with the Map interface. Also, I think he wants us to use arrays specifically, although he did say that we could use ArrayList...
Up until I read your post, I was re-writing my code in another attempt to solve the problem. I'm going to look at the Map interface, but out of curiosity am I close with the following code? Seems like I just need to fix one line to correct my out of bounds error...
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
// read in file States.txt, instantiate BufferedReader object,
// set new BufferedReader object to variable #newLine
FileReader f = new FileReader("States.txt");
BufferedReader br = new BufferedReader(f);
String newLine = br.readLine();
//declare jagged array
int[][] arrPopulation;
arrPopulation = new int[4][];
//create state object, and get
State newState = new State(newLine);
//read file
int col = 0;
arrPopulation[0] = new int[col];
arrPopulation[1] = new int[col];
arrPopulation[2] = new int[col];
arrPopulation[3] = new int[col];
int stateRegion = newState.getRegionNum();
while (newLine != null)
{
switch (stateRegion)
{
case 1:
arrPopulation[0][col] = newState.getStatePop();
System.out.println("Population added:" +
arrPopulation[0][col]);//test if col was created
col++; //increment columns
break;
case 2:
arrPopulation[1][col] = newState.getStatePop();
col++; //increment columns
break;
case 3:
arrPopulation[2][col] = newState.getStatePop();
col++;
break;
case 6:
arrPopulation[3][col] = newState.getStatePop();
System.out.println("Population added:" +
arrPopulation[3][col]);
col++; //increment columns
break;
}
br.readLine();
}//endwhile
br.close();//close stream
} // end public static void main
} // end main
Sorry if I'm supposed to place all this in the Comments section, however, I hit my character limit and couldn't post my code. Thanks again for your help!

Categories

Resources