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());
}
}
Related
First, sorry for my English who may be poor, I hope you will understand me
I do not see how to recover my object count per hour.
I hope you can help me find out more about my question.
I have a mission object that contains a mission list that each have as attribute
a STRING name and a STRING time (hhmmss format)
here is an example :
0 : name1 102101
1 : name2 102801
2 : name3 104801
3 : name4 110501
4 : name5 120301
I wish I could make an array allowing me to count the number of missions for each hour
In this example I would have :
10 => 3
11 => 1
12 => 1
I do not know if you see what I would like to get :)
If you ever have small tracks I'm interested
Thank you for reading me !
I wish you a good evening
TL;DR
As the comments mentioned, you may want to use a HashMap with String keys reflecting the hour and Integer values for the count (missions per hour).
Since you're dealing with hours, meaning that you have a maximum of 24 of them, you can also replace the HashMap with an Array of 24 items.
The Mission class
Basically, all is needed here is a getter for the time attribute. If you feel fancy, you can also add a getHour which will return the hour instead of the whole time string.
class Mission {
private String name;
private String time;
Mission(String name, String time) {
this.name = name;
this.time = time;
}
String getHour() {
// This gives us the 2 first characters into a String - aka the "hour"
return time.substring(0, 2);
}
}
Using the HashMap
We want to keep the count per hour in a HashMap. So we'll iterate over the missionsList and for each item, we'll get its count, then we'll increment it.
If the hour is not in the HashMap yet, we would normally receive a null. To handle that with minimal boilerplate, we'll use the getOrDefault method. We can call it like this map.getOrDefault("10", 0). This will return the missions count of hour 10, and if that count doesn't exist yet (which means we didn't add it to the map yet) we will receive 0 instead of null. The code will look like this
public static void main(String[] args) {
// This will built our list of missions
List<Mission> missionsList = Arrays.asList(
new Mission("name1", "102101"),
new Mission("name2", "102801"),
new Mission("name3", "104801"),
new Mission("name4", "110501"),
new Mission("name5", "120301")
);
// This map will keep the count of missions (value) per hour (key)
Map<String, Integer> missionsPerHour = new HashMap<>();
for (Mission mission : missionsList) {
// Let's start by getting the hour,
// this will act as the key of our map entry
String hour = mission.getHour();
// Here we get the count of the current hour (so far).
// This is the "value" of our map entry
int count = missionsPerHour.getOrDefault(mission.getHour(), 0);
// Here we increment it (by adding/replacing the entry in the map)
missionsPerHour.put(hour, count + 1);
}
// Once we have the count per hour,
// we iterate over all the keys in the map (which are the hours).
// Then we simply print the count per hour
for (String hour : missionsPerHour.keySet()) {
System.out.println(String.format(
"%s\t=>\t%d", hour, missionsPerHour.get(hour)
));
}
}
First, I have searched. And all of the answers I have found have been about NOT having the same reference to the same object in two different array lists. so maybe that should tell me I'm doing this wrong in itself? But I'm not sure of how else to manage this.
I am trying to learn Java. And part of that is Swing.
My app I am working on is a simple tournament/bracket app (think march madness. or any simple bracket tree).
Simplified code with just the issue at hand:
class Bracket extends JPanel {
ArrayList<Round> rounds = new ArrayList<Round>();
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = rounds.get(currentRoundNum).games.indexOf(game);
int currentTeamNum = rounds.get(currentRoundNum).games.get(currentGameNum).teams.indexOf(team);
int nextRoundNum = currentRoundNum + 1;
int nextGameNum = (int) (Math.floor(gameNumber / 2));; // to position the team in the appropriate game slot in the next round
int nextTeamNum = ((gameNumber % 2) == 0) ? 0 : 1; // even game numbers will be the top team in the next round, odd team numbers will be the bottom team in the next round
// here is where things are getting wonky. Trying to set the next round slot to the team that is being declared the winner
rounds.get(nextRoundNum).games.get(nextGameNum).teams.set(nextTeamNum, team);
}
public Bracket(int numRounds) {
// code that creates the bracket structure. # of rounds. the correct # of games depending on the round. etc. Creates empty shell of "placeholder" teams with no name/info.
for(int i = 0; i < numRounds; i++) {
int numGames // set to (number of games of the last round added) * 2
rounds.add(0, new Round(numGames)
}
}
}
class Round extends JPanel {
ArrayList<Game> games = new ArrayList<Game>();
public Round(int numGames) {
for(int i = 0; i < numGames; i++) {
games.add(new Game());
}
}
// more code...
}
class Game extends JPanel {
ArrayList<Team> teams = new ArrayList<Team>();
// more code... creates two teams per each game in constructor
}
class Team extends JPanel {
String teamName;
public Team(String name) {
teamName = name;
add(new JLabel(name));
}
// simple team info, just going for functionality. not much else is here yet.
}
So, lets say in the first round (index 0 of rounds), in the first game (index 0 of rounds.get(0).games), Team 1 (index 0 of rounds.get(0).games.get(0).teams) wins. It's calculating all the stuff correctly. The team is placed in the correct slot. BUT, it completely removes the team from the current position in the round. So now I'm left with only 1 team in the first game of the first round.
It won't let me have the same Team object referenced in both ArrayLists in Rounds[0].Games[0].Teams and Rounds[1].Games[0].Teams. They are nested array lists in each, so 2 different Array Lists. Am I failing because it's bad to extend the JComponents on the classes themselves, and I should completely refactor this?
I can't see exactly what is going on in your example code, as it is not self-contained. However from your description it looks like you are falling foul of the property that Swing components can only be added to one container at a time. If you add the same component to a second container it is automatically removed from the first one.
This doesn't affect the contents of your ArrayLists in the slightest - you can have the same object in as many different ArrayLists as you like.
It also looks like you are muddying the waters by storing this sort of data inside objects which extend Swing components. I suggest you consider separating out a data structure (the Model) from the display components (the View) to make things clearer. Just get the data structure working first, then build the view from it once you have verified it is correct.
On an unrelated note, it looks like you could simplify the start of your code, where before you had:
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = rounds.get(currentRoundNum).games.indexOf(game);
int currentTeamNum = rounds.get(currentRoundNum).games.get(currentGameNum).teams.indexOf(team);
...
you could replace these lines with
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = round.games.indexOf(game);
int currentTeamNum = game.teams.indexOf(team);
...
since you already have references to those objects passed in as arguments.
I'm making a program to make a list of people, with 3 different marks of time (in double)
To do it, I made 4 arrays, One String, to save people names, and 3 Doubles to save the 3 marks on the years 2010, 2011, and 2012.
In the menu, I have to implement an option to sort the list on 2012s mark, in descending order.
Like this
m12[0] = 12.1
m12[1] = 34.1
m12[2] = 23.1
m12[3] = 23.5
into:
m12[1] = 34.1
m12[3] = 23.5
m12[2] = 21.1
m12[0] = 12.1
I did it with a basic algorithm, but now I want to know if it's possible to get the actual order of the arrays, ([1],[3],[2],[0]) and apply it to the other arrays I have to print it as a list based on the 2012 mark in descending order.
Thats the code I have to make the normal order list:
if(option==2){
System.out.println("# , Name, 2010, 2011, 2012");
for(i=0;i<dorsal.length-1;i++){
if(dorsal[i]!=0){
System.out.println(dorsal[i]+"- "+nom[i]+", "+m10[i]+", "+m11[i]+", "+m12[i] );
}
}
System.out.println("Press ENTER to return");
intro.nextLine();
}
Sorry if I didnt explained it very good, I started programming 3 months ago and I'm so newbie.
//EDIT
I'll paste here the head of the exercise:
Thats exactly the programs needs to do. I'm stucked at point 3.
The objective is to develop a program to manage a list of members of
in a competition of long jump. The number of places available is 15.
Their data will be introduced in the same order in which the athletes
enroll. Design a program that shows the following options:
1 – Register a participant
2 – List all the participant’s data
3 – List all the participant’s data by mark
4 – Quit
If 1 is selected, data of one of the participants will be introduced:
Name, best mark in 2012, best mark in 2011 and best mark in 2010.
If 2 is selected, we have to list all participant’s data ordered by dorsal
number (the order they’ve enrolled)
If 3 is selected, we have to list all participant’s data ordered by 2012
mark, from greater to smaller.
After processing each option, the main menu must be shown again,
till the option 4 is selected, quitting the program.
Thanks.
Define a class to contain the data for each person, such as:
public class Person
{
private String name;
Private Map<Integer,Double> marks = new HashMap<Integer,Double>();
public Person(String name) { this.name = name; }
public void setMark(int year, double mark) {
this.marks.put(year,mark);
}
public void getMark(int year) {
// return zero if there's no mark for the requested year
return this.marks.containsKey(year) ? this.marks.get(year) : 0;
}
}
Then write a Comparator<Person>
public PersonComparatorOnMarkDescending implements Comparator<Person>
{
private int yearToCompare;
public PersonComparator(int yearToCompare) {
this.yearToCompare = yearToCompare;
}
public compare(Person p1, Person p2)
{
Integer p1Mark = p1.getMark(yearToCompare);
Integer p2Mark = p2.getMark(yearToCompare);
return p2.compareTo(p1);
}
}
You can then define a List<Person> or a Person[] array and use the sorting methods available in java.util. Instantiate the comparator with, for instance:
Comparator<Person> comp = new PersonComparatorOnMarkDescending(2012);
This approach lets you sort the collection on any year's marks.
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!");
}
I'm implementing a JTable, where an user can define the TimeTable.
Every subject has a number of credits, and I have to count the sum of all credits in a week. Obviously, for do that it's necessary to count one time all duplicate subject(I would not count two time the credits of the same subject).
For example, if the JTable is
I would like to get the value Math,English,Science, Philosophy, Art only ONE time. I've tried to do this with the follower method:
private void getOnce (String[] dailyLessons)
{
Set<String> weekSubjects = new HashSet<String>();
int weeklyCredits=0;
//dailylessons is a String[] that contains the lessons of the day
Collections.addAll(weekSubjects, dailyLessons);
//String[] week would contain every subject only one time
String [] week = weekSubjects.toArray(new String[0]);
//for all the subject I get its credits
for (int i=0; i<week.length; i++)
{
if (!week[i].equals("no"))
{
String [] credits= week[i].getCredits;
weeklyCredits += credits;
}
}
}
But it does not work. Could you explain me why? A correct version of my code will be very appreciated.
But it does not work. Could you explain me why?
read Oracle tutorial How to use Tables
all data for JTables view are stores in (Creating a Table Model) XxxTableModel
if isn't there any definition for XxxTableModel then DefaultTableModel is used
A correct version of my code will be very appreciated.
good one