Temp arrays not working after adding 3rd Item - java

I had to make a Temp array to keep resizing the array list if the user decides to keep adding items to the cart, but my Temp array works until I try to add 3 different items to the cart.
I was instructed to do it this way instead of an array list to show the difficulty of arrays.
orderProduct [productCount] = aProduct;
orderQuantity [productCount] = aQuantity;
}
}

You forgot to increase productCount when there is already a product in the cart.
Moreover, you can just set the product and quantity array to the temp arrays instead of copying back.
orderProduct = tempOrderedProducts;
orderQuantity = tempOrderedQuantity;

Because you forgot productCount++ after resizing the array.
The following code will work:
public void setOrderProduct(Product aProduct, int aQuantity) {
if (productCount == 0) {
orderProduct[0] = aProduct;
orderQuantity[0] = aQuantity;
} else {
Product[] tempOrderedProducts = new Product[orderProduct.length + 1];
int[] tempOrderedQuantity = new int[orderQuantity.length + 1];
for (int i = 0; i < orderProduct.length; i++) {
tempOrderedProducts[i] = orderProduct[i];
tempOrderedQuantity[i] = orderQuantity[i];
}
orderProduct = new Product[tempOrderedProducts.length];
orderQuantity = new int[tempOrderedQuantity.length];
for (int i = 0; i < orderQuantity.length; i++) {
orderProduct[i] = tempOrderedProducts[i];
orderQuantity[i] = tempOrderedQuantity[i];
}
orderProduct[productCount] = aProduct;
orderQuantity[productCount] = aQuantity;
productCount++; //you forgot this
}
}
What's more, there is a simple way to deal with array copy:
public void setOrderProduct(Product aProduct, int aQuantity) {
if (productCount == 0) {
orderProduct[0] = aProduct;
orderQuantity[0] = aQuantity;
} else {
Product[] tempOrderedProducts = new Product[orderProduct.length + 1];
int[] tempOrderedQuantity = new int[orderQuantity.length + 1];
//System.arraycopy is more convenient and efficient
System.arraycopy(orderProduct, 0, tempOrderedProducts, 0, orderProduct.length);
System.arraycopy(orderQuantity, 0, tempOrderedQuantity, 0, orderQuantity.length);
//you don't need to copy back, just re-assign the reference
orderProduct = tempOrderedProducts;
orderQuantity = tempOrderedQuantity;
orderProduct[productCount] = aProduct;
orderQuantity[productCount] = aQuantity;
productCount++;
}
}

Related

How can I shuffle an array and put them into buffered images?

Basically I'm making a domino game in Java; however I'm pretty new and can't figure out how to shuffle the dominoes up using arrays and buffered Images.
This code here is setting up the arrays for each hand and an array with each domino piece. Keep in mind that I am not using an AI for this domino game;
the program runner will just play as each player.
static String [] hand1 = new String[7];
static String [] hand2 = new String[7];
static String [] hand3 = new String[7];
static String [] hand4 = new String[7];
static String[] allDominoes = {"00","01","02","03","04","05","06","11","12","13","14","15","16","22","23",
"24","25","26","33","34","35","36","44","45","46","55","56","66"};
This is what I tried to use to shuffle the dominoes and put them into each hand array:
public static void newRound() // start a new round; shuffle the dominoes; hand them out
{
Arrays.fill(hand1, null);
Arrays.fill(hand2, null);
Arrays.fill(hand3, null);
Arrays.fill(hand4, null);
String[] shuffledDominos = new String[28];
List<String> shuffled = Arrays.asList(allDominoes);
Collections.shuffle(shuffled);
shuffled.toArray(shuffledDominos);
int pos = 0;
for (int j = 0; j < 7; j++)
{
hand1[pos] = shuffledDominos[j];
pos++;
}
pos = 0;
for (int y = 7; y < 14; y++)
{
hand2[pos] = shuffledDominos[y];
pos++;
}
pos = 0;
for (int x = 14; x < 21; x++)
{
hand3[pos] = shuffledDominos[x];
pos++;
}
pos = 0;
for (int z = 21; z < 28; z++)
{
hand4[pos] = shuffledDominos[z];
pos++;
}
However I think this part is completely wrong and there must be a better way of doing this since I'm not sure how to actually proceed from here on out.
This is assigning each domino Image the domino pngs.
public DominoPanel()
{
try
{
dom00 = ImageIO.read(DominoPanel.class.getResource("/Image/00.png"));
dom01 = ImageIO.read(DominoPanel.class.getResource("/Image/01.png"));
dom02 = ImageIO.read(DominoPanel.class.getResource("/Image/02.png"));
dom03 = ImageIO.read(DominoPanel.class.getResource("/Image/03.png"));
dom04 = ImageIO.read(DominoPanel.class.getResource("/Image/04.png"));
dom05 = ImageIO.read(DominoPanel.class.getResource("/Image/05.png"));
dom06 = ImageIO.read(DominoPanel.class.getResource("/Image/06.png"));
dom11 = ImageIO.read(DominoPanel.class.getResource("/Image/11.png"));
dom12 = ImageIO.read(DominoPanel.class.getResource("/Image/12.png"));
dom13 = ImageIO.read(DominoPanel.class.getResource("/Image/13.png"));
dom14 = ImageIO.read(DominoPanel.class.getResource("/Image/14.png"));
dom15 = ImageIO.read(DominoPanel.class.getResource("/Image/15.png"));
dom16 = ImageIO.read(DominoPanel.class.getResource("/Image/16.png"));
dom22 = ImageIO.read(DominoPanel.class.getResource("/Image/22.png"));
dom23 = ImageIO.read(DominoPanel.class.getResource("/Image/23.png"));
dom24 = ImageIO.read(DominoPanel.class.getResource("/Image/24.png"));
dom25 = ImageIO.read(DominoPanel.class.getResource("/Image/25.png"));
dom26 = ImageIO.read(DominoPanel.class.getResource("/Image/26.png"));
dom33 = ImageIO.read(DominoPanel.class.getResource("/Image/33.png"));
dom34 = ImageIO.read(DominoPanel.class.getResource("/Image/34.png"));
dom35 = ImageIO.read(DominoPanel.class.getResource("/Image/35.png"));
dom36 = ImageIO.read(DominoPanel.class.getResource("/Image/36.png"));
dom44 = ImageIO.read(DominoPanel.class.getResource("/Image/44.png"));
dom45 = ImageIO.read(DominoPanel.class.getResource("/Image/45.png"));
dom46 = ImageIO.read(DominoPanel.class.getResource("/Image/46.png"));
dom55 = ImageIO.read(DominoPanel.class.getResource("/Image/55.png"));
dom56 = ImageIO.read(DominoPanel.class.getResource("/Image/56.png"));
dom66 = ImageIO.read(DominoPanel.class.getResource("/Image/66.png"));
}
catch(Exception E)
{
}
I know I probably didn't explain this well so I will try to summarize it here as best as I can. I need to be able to assign a random domino to each player and then print them out in a JPanel using buffered Images.

Out of bounds string array java

I am facing a problem that I can't take elements from ArrayList and push them to my new String array. Actually right now I`m feeling lost. Receiving an exception out of bounds, but after a check with printing elements by their id everything works? By the way my darbuotojuArray looks like this:
Programuotojas: X X 1 X
Here's my code:
public String[] renkantDarbuotojus() {
String[] darbuotojaiIKomanda = new String[2];
if (darbuotojuArray.size() == 0) {
System.out.println("Nera darbuotoju kuriuos butu galima prideti i komanda.");
System.out.println("Pridekite nauju darbuotoju");
meniu.valdiklis();
} else {
for (int i = 0; i < darbuotojuArray.size(); i++) {
System.out.println("ID: " + i + " " + darbuotojuArray.get(i));
}
System.out.println("Pasirinkite pirmaji darbuotoja pagal ID");
Scanner SI = new Scanner(System.in);
int userSelects = Integer.parseInt(SI.nextLine());
darbuotojaiIKomanda[0] = String.valueOf(darbuotojuArray.get(userSelects));
darbuotojuArray.remove(userSelects);
System.out.println("Pasirinkite antraji darbuotoja pagal ID");
int userSelects2 = Integer.parseInt(SI.nextLine());
darbuotojaiIKomanda[1] = String.valueOf(darbuotojuArray.get(userSelects2));
darbuotojuArray.remove(userSelects2);
}
return darbuotojaiIKomanda;
}
So, you are removing an item from the listdarbuotojuArray.remove(userSelects);, which will change all the IDs. You either need to print your list again so the user can select the correct ID, or you can do this:
int userSelects2 = Integer.parseInt(SI.nextLine());
if(userSelects2 == userSelects)
System.out.println("Error, ID has been removed");
else if(userSelects2 > userSelects)
userSelects2 = userSelects2 -1;

Adding values into DataPoint array causing the application crash while running

I am using GraphView library code which contains DataPoint[] Array.
My code also contains a database named olddb which I use to insert the array length in the code below.
The first 2 for loops are for adding the values in the database into an array and the third for loop is to get the values out from the arrays arrayWeight and arrayId and add them to DataPoint[] array.
Though something seems to go wrong, after I run the program it just crashes, can anyone figure out what is causing the application to crash?
private DataPoint[] getDataPoint() {
if (olddb.check()) {
List<oldDetails> details = olddb.getDetails();
double[] arrayWeight = new double[olddb.getDetailsCount()];
int[] arrayId = new int[olddb.getDetailsCount()];
for (oldDetails cn : details) { //Adding weights and id of all time to an array.
double num = cn.getWeight();
int id = cn.getId();
for (int i = arrayWeight.length; i > 0; i--) {
arrayWeight[i] = num;
arrayId[i] = id;
}
}
DataPoint[] dp = new DataPoint[olddb.getDetailsCount()];
for (int i = 0; i < arrayId.length; i++) {
for (int j = 0; j < arrayWeight.length; j++)
dp[i] = new DataPoint(i, arrayWeight[j]);
}
return dp;
}
else {
DataPoint[] dp = new DataPoint[]{
new DataPoint(0, 0)
};
return dp;
}
}
Here is an example for working code of DataPoint array:
private DataPoint[] getDataPoint(){
DataPoint[] dp = new DataPoint[]{
new DataPoint(0,1),
new DataPoint(2,5),
new DataPoint(5,5),
new DataPoint(7,4)
};
return dp;
}
EDIT:
here is the error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.none.myapplication, PID: 3881
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.none.myapplication/com.none.myapplication.MainActivity}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM oldDetails
Database
You can fix it by replacing all 3 calls to olddb.getDetailsCount()
with
int count = olddb.getDetailsCount();
then:
double[] arrayWeight = new double[count];
int[] arrayId = new int[count];
DataPoint[] dp = new DataPoint[count];
However you need to understand the issue:
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM oldDetails is the error, which happens inside of DatabaseHandlerOld.getDetailsCount line 141
Android SQLite DB When to Close
Well after some researches and some of Blundell help, I figured out the problem was indeed the close(); method in my database.
Though the solution was to change the getDetailsCount() function to this:
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, TABLE_OLDDETAILS);
}
and in my main activity file:
private DataPoint[] getDataPoint() {
if (olddb.check()) {
List<oldDetails> details = olddb.getDetails();
long c = olddb.QueryNumEntries();
int count = (int) c;
Log.d("Count", "equals: " + count);
double[] arrayWeight = new double[count];
int[] arrayId = new int[count];
for (oldDetails cn : details) { //Adding weights and id of all time to an array.
double num = cn.getWeight();
int id = cn.getId();
Log.d("num", "equals: " + num);
Log.d("id", "equals: " + id);
for (int i = count; i < 0; i--) {
arrayWeight[i] = num;
arrayId[i] = id;
}
}
DataPoint[] dp = new DataPoint[count];
for (int i = 0; i < arrayId.length; i++) {
for (int j = 0; j < arrayWeight.length; j++) {
dp[i] = new DataPoint(arrayId[i], arrayWeight[j]);
Log.d("ArrayWeight", "equals: " + arrayWeight[j]);
Log.d("ArrayId", "equals: " + arrayId[i]);
}
}
return dp;
}
DataPoint[] dp = new DataPoint[]{
new DataPoint(0, 0)
};
return dp;
}

Sorting array list

public class Saleitem {
public Product product = null;
public int numberofproduct = 0;
static ArrayList<Saleitem> Saleitemarray = new ArrayList<Saleitem>();
static ArrayList<Integer[]> total = new ArrayList<Integer[]>();
//read the sales data
public static void salesData() {
String SalesDataCSV = "SalesData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
System.out.println("\nThe Sales Data file has been opened\n");
try {
int currentcustomer = 1;
int lastcustomer = 1;
double sum = 0;
br = new BufferedReader(new FileReader(SalesDataCSV));
line = br.readLine();
System.out.println("-----------------------------------------------");
System.out.println("Sales Data File");
System.out.println("Customer ID, Product ID, Number of Units");
System.out.println("-----------------------------------------------");
while ((line = br.readLine()) != null) {
String field[] = line.split(cvsSplitBy);
if(field.length>1) {
String currentcustomerID = field[0];
String currentproductID = field[1];
String currentunitnumber = field[2];
Product currentproduct = null;
currentcustomer = Integer.parseInt(currentcustomerID);
int currentproductid = Integer.parseInt(currentproductID);
int currentproductunit = Integer.parseInt(currentunitnumber);
//-------------------------------------
// START OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
System.out.println(currentcustomer + " , " + currentproductid + " , " + currentproductunit);
////////////////////
if (lastcustomer == currentcustomer) {
Saleitem salesItemObject = new Saleitem(currentproductid, currentproductunit,
Product.getUnitPrice(currentproductid));
Saleitemarray.add(salesItemObject);
} else {
// sale receipt date, time, etc.
Salereceipt salesReceiptObject = new Salereceipt(lastcustomer, lastcustomer,
sum, "2/20/16", (int) (Math.random() * 2000));
Salereceipt.receipt.add(salesReceiptObject);
lastcustomer = currentcustomer;
Saleitemarray.clear();
sum = 0;
}
///////////////////////////
//Find the correct product that the customer ordered
for (int i = 0; i < Product.productData.size(); i++){
if (((Product.productData).get(i)).productID == currentproductid){
currentproduct = Product.productData.get(i);
}
}
Saleitem salesItemObject = new Saleitem(currentproduct, currentproductunit);
Saleitemarray.add(salesItemObject);
boolean found = false;
//update total
for (int i = 0; i < total.size(); i++){
//total is an array of arrays =)
//in the array, index 0 is the productID
// index 1 is the total sold of that product
//Find the correct product total
if ((total.get(i))[0] == salesItemObject.product.productID){
//if we found it then we will mark found
//so that we can add in the item if it doesnt exist
//in our total array
found = true;
//increment the total number of prodcuts sold
(total.get(i))[1] += salesItemObject.numberofproduct;
}
}
if (found == false){
Integer[] array = new Integer[2];
// index 0 = product id
// index 1 = total number of products sold
array[0] = salesItemObject.product.productID;
array[1] = salesItemObject.numberofproduct;
total.add(array);
}
//-------------------------------------
// END OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
//this is done inside of the constructor
if (currentcustomer == lastcustomer){
sum += currentproduct.productPrice * currentproductunit;
}
}
}
The Sales Data is imported from a file that has Customer_ID[0], Product_ID[1], Units_ordered[2]
I want to sort the ArrayList total by the Product_ID in ascending order. What would be the best way to do this. Im new to java so I don't know much of the syntax.
total.sort((item1, item2) -> item1.getProductId() - item2.getProductId());
You can use Collections#sort like below.
Add a getter for ProductId and you're done
Collections.sort(total, new Comparator<Saleitem>(){
#Override
public int compare(Saleitem s1, Saleitem s2) {
return s1.getProductId() - s2.getProductId();
}
});

How to fill an array with while loop?

I've a piece of code something like this and I want to insert the data by using a while.
Weather weather_data[] = new Weather[]{
new Weather(0, "Cloudy"),
new Weather(0, "Showers"),
new Weather(0, "Snow"),
new Weather(0, "Storm"),
new Weather(0, "Sunny")
};
How can I fill this list using a while ?
Thanks
Try this:
Weather weather_data[] = new Weather[5];
int i = 0;
while(i < weather_data.length){
//fill array [i]
i++;
}
I understand that you want to fill your array with the following String array as base:
String[] weatherTypes = {"Cloudy","Showers","Snow","Storm","Sunny"};
Then you can do this:
int i=0;
Weather[] weather_data = new Weather[];
for (String weatherType: weatherTypes){
weather_data[i] = new Weather(0,weatherType);
i++;
}
You could use also use a list:
List<Weather> weather_data = new ArrayList<Weather>();
for (String weatherType: weatherTypes){
weather_data.add(new Weather(0,weatherTypes));
}
Weather[] weather_data = new Weather[5];
public void addWeatherData(Weather newWeather) {
int counter = 0;
while (counter < weather_data.length) {
if (weather_data[counter] == null) {
weather_data[counter] = newWeather;
return;
}
counter++;
}
}

Categories

Resources