I have created an app that recieves orders and i want to be able to cycle 4 sets of orders so each device can choose what set of orders it sees. I want to split the orders by the order_id so
a: 1 5 9 13 ect
b: 2 6 10 14 ect
c: 3 7 11 15 ect
d: 4 8 12 16 ect
I recieve the orders through a loop but can change to a list of array lists if nessecary. I have tried a couple ways to get the result im after but have had no luck. Thank you in advance
EDIT (Rough idea of what i want)
//Data from Json
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
final int objectsItem = oneObject.getInt("order_id");
if(checkboxA == checked)
{
//Show orders 1,5,9,13 ect
}
if(checkboxB == checked)
{
//Show orders 2,6,10,14 ect
}
if(checkboxA == checked)
{
//Show orders 3,7,11,15 ect
}
if(checkboxA == checked)
{
//Show orders 4,8,12,16 ect
}
}
`
This way i can show all orders, all parts of orders, so the orders can be equally split between many devices without interacting with each other - Hope this makes more sense
What about using a Map? You can set every order_id as the key for an entry and all orders as the value of the entry (for example List of orders).
For example:
Map<Character, List<Integer>> map;
Than you can get a certain order_id with:
List<Integer> orders = map.getValue('a');
for (Integer order : orders) {
//do logic here
}
Related
So I am trying to build this algorithm, what it will do is retrieve a reference (in this case a date), this date will be used to check against my firestore database to ensure that there are less than 3 employees who have booked this same date. So you will see here
startDateReference = 202131Thursday = Thursday, 1st of April, 2021
So I am running a loop, within this loop is a counter, this counter will take account the amount of times this reference is called in the loop. However, if it is looped 3 times the program will stop the loop, which is great, but I am unable to wrap my head around how to execute a condition if the loop has resolved as less than 3 iterations. For example, at the moment my database only has 2 of these reference stored, so I am successully able to call each iteration, but it does not take account that there is 1 more extra slot.
my code:
final Query query = db.collection("holidays").whereEqualTo("startDateReference",totalDateCode);
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
//creating a map to obtain information
Map<String, Object> test = new HashMap<>();
//counter
int counter = 0;
boolean flag = false;
//retrieve data as a hashmap document
for (QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
Note data = documentSnapshot.toObject(Note.class);
test.put("startDateReference", data.getStartDateReference());
Collection<Object> values = test.values();
//retrieve results as single values
for (Object string : values) {
do {
//System.out.println(string);
if (string.equals("202131Thursday")) {
counter++;
System.out.println("Checking for holidays" + counter);
} else if (counter == 3) {
System.out.println("could not save data it is packed");
} else {
System.out.println("storing details");
}
} while (counter == 3);
}
}
}
});
The results i get:
> I/System.out: 0
> Checking for holidays1 I/System.out: 1
> Checking for holidays2
But after this last result I expect this condition to execute as seen in the else condition within my code as there is a extra space (note i have not coded in my database store function i am using just string text to see how it would work right now and the database only has 2 of the reference, there is a extra slot which i am trying to store details in):
System.out.println("storing details");
Call another condition outside of all the loops and then after the loops have resolved you can use the counter as its final form to verify whether there is space or not using else if statements.
I have a list which is a java object like below.
public class TaxIdentifier {
public String id;
public String gender;
public String childId;
public String grade,
public String isProcessed;
////...///
getters and setters
///....///
}
Records in DB looks like below,
id gender childId grader isProcessed
11 M 111 3 Y
12 M 121 4 Y
11 M 131 2 Y
13 M 141 5 Y
14 M 151 1 Y
15 M 161 6 Y
List<TaxIdentifier> taxIdentifierList = new ArrayList<TaxIdentifier>();
for (TaxIdentifier taxIdentifier : taxIdentifierList) {
}
while I process for loop and get the id = 11, i have to check if there are other records with id = 11 and process them together and do a DB operation and then take the next record say in this case 12 and see if there are other records with id = 12 and so on.
One option is i get the id and query the DB to return all id = 11 and so on.
But this is too much back and forth with the DB.
What is the best way to do the same in java? Please advice.
If you anyway need to process all the records in the corresponding database table - you should retrieve all of them in 1 database roundtrip.
After that, you can collect all your TaxIdentifier records in dictionary data structure and process in whatever way you want.
The brief example may look like this:
Map<String, List<TaxIdentifier>> result = repositoty.findAll().stream().collect(Collectors.groupingBy(TaxIdentifier::getId));
Here all the TaxIdentifier records are grouped by TaxIdentifier's id (all the records with id equals "11") can be retrieved and processed this way:
List<TaxIdentifier> taxIdentifiersWithId11 = result.get("11");
I would leverage the power of your database. When you query, you should order your query by id in ascending order. Not sure which database you are using but I would do:
SELECT * FROM MY_DATABASE WHERE IS_PROCESSED = 'N' ORDER BY ID ASC;
That takes the load of sorting it off of your application and onto your database. Then your query returns unprocessed records with the lowest id's on top. Then just sequentially work through them in order.
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());
}
}
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.
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!");
}