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();
}
});
Related
So I'm coding my text-based game with world generation and my friend coded the world generation. He's away right now so I have to ask this.
The code should generate an array with the X and Y positions of chests that spawn in random positions. The packages used are: java.util.Scanner,
java.util.Arrays,
java.util.Random,
Class is declared but I'm not including it in this snippet.
The Code for the method worldgen():
static double[] worldgen() {
//coded by *my friend, name censored*
int random_int_1 = 0;
int random_int_2 = 0;
int x;
int y;
int chest_x;
int chest_y;
double[] chest_x_values;
double[] chest_y_values;
int mineral_x;
int mineral_y;
// chest_x_and_y_values[something (or else)] = chest_x_values[something];
// chest_x_and_y_values[something else] = chest_y_values[something];
Random rand1 = new Random();
int num_of_chests = rand1.nextInt(100);
chest_x_values = new double[num_of_chests];
chest_y_values = new double[num_of_chests];
while (random_int_1 <= num_of_chests)
{
Random rand2 = new Random();
chest_x = rand2.nextInt(301);
System.out.println(chest_x);
chest_x_values[random_int_1] = chest_x;
System.out.println(Arrays.toString(chest_x_values));
if(random_int_1 <= num_of_chests) {
random_int_1++;
System.out.println(random_int_1);
}
}
while (random_int_2 <= num_of_chests)
{
Random rand3 = new Random();
chest_y = rand3.nextInt(301);
chest_y_values[random_int_2] = chest_y;
random_int_2 = random_int_2 + 1;
}
int random_int_3 = num_of_chests;
random_int_1 = 0;
random_int_2 = 0;
double[] chest_x_and_y_values = new double[random_int_3 = random_int_3*2+1];
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
chest_x_and_y_values[random_int_1+1] = -1;
while (random_int_2 <= random_int_3) {
chest_x_and_y_values[random_int_1 + 1 + random_int_2] = chest_y_values[random_int_2];
random_int_2 = random_int_2 + 1;
}
return chest_x_and_y_values;
}
public static void main(String[] args) {
//coded by EnZon3
Scanner uIn = new Scanner(System.in);
System.out.println("-------------------------------");
System.out.println(" *game name censored* ");
System.out.println(" 1: Generate new world.. ");
System.out.println(" 2: Generate w/ custom seed.. ");
System.out.println(" 3: See world data ");
System.out.println(" 4: Exit ");
System.out.println("-------------------------------");
int option = uIn.nextInt();
if (option > 4) {
System.err.println("Error 0x1: Not an option");
}
while (option != 4) {
if (option == 1) {
double[] world = worldgen();
System.out.println(Arrays.toString(world));
}
}
}
The error I get is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 77 out of bounds for length 77 at
.worldgen(.java:35) at .main(.java:86)
I've tried tweaking the values but that didn't work
while (random_int_1 <= num_of_chests)
This should be < (strictly less than), remember arrays are 0 indexed.
while (random_int_2 <= num_of_chests)
Same thing here
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
random_int_3 is 2 * num_of_chests +1, and chest_x_values is a list of length num_of_chests. In this part, random_int_1 can go all the way up to 2 * num_of_chests +1 which is higher than chest_x_values.
Hey everyone so I'm new to programming and recently I've been introduced to array's I've been having some problems in my current project. Essentially I am getting an array out of bounds exception when trying to calculate the discount price (afterDiscount located at the bottom) however when I run the program I get this error. I'm not sure how to fix it as I have not dealt with arrays before.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at StarterJ52PartPriceDiscount.main(StarterJ52PartPriceDiscount.java:108)
import java.io.*;
import java.util.*;
public class StarterJ52PartPriceDiscount
{
public static void main(String[] args) throws FileNotFoundException
{
// Constants
final int MAX = 30; // max records on parts.dat
final int SENTINEL = 999;
// File Objects - Parts and Trans files
Scanner inPartsFile = new Scanner(new FileReader("parts.dat"));
Scanner inTransFile = new Scanner(new FileReader("trans.dat"));
// Part file Variables
int stkPartNo;
double stkPartPrice; // ???
// Tx file Variables
int txPartNo;
int txQuantity;
int txDiscountCode;
// Arrays
int[] partNos = new int[MAX];
double[] prices = new double[MAX];
int[] discounts = {0,5,10,15,20,25,30,40,50}; // Discount Percentages
// Other Variables
Scanner console = new Scanner(System.in);
int recCount; // no records on file
int cnt, foundPosition,i,pos; // index
double beforeDiscount, afterDiscount, totalDiscount, cost;
boolean found;
// Initialise
recCount = 0;
foundPosition = 0;
totalDiscount = 0;
found = false;
pos =-1;
// Output Part No and Prices (for)
System.out.println("Part No Part Price");
for(i=0; i <MAX; i++)
{
stkPartNo = inPartsFile.nextInt();
stkPartPrice = inPartsFile.nextDouble();
//System.out.printf("%2d %4.2f %n",stkPartNo,stkPartPrice );
partNos[i] = stkPartNo;
prices[i] = stkPartPrice;
System.out.printf("%6d %7.2f %n",partNos[i],prices[i]);
}//for
// Initial Tx read of first record
txPartNo=inTransFile.nextInt();
System.out.println("Part Quantity Disc Code");
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d %4d %n",txPartNo,txQuantity,txDiscountCode );
txPartNo=inTransFile.nextInt();
}//While
// Verify Tx trans.dat contents (initially)
inTransFile.close();
inTransFile = new Scanner(new FileReader("trans.dat"));
System.out.println("xxxxxxx");
txPartNo=inTransFile.nextInt();//initial Read
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d ",txPartNo,txQuantity );
found = false;
pos = -1;
while (pos < partNos.length -1 && found == false)
{
++pos;
if (partNos[pos] == txPartNo){
found = true;
}
else if (partNos[pos] > txPartNo){ // Ordered
pos = partNos.length; // break;
}
} // inner while
if (found) { // == true
beforeDiscount = prices[pos];
//Throws out of bounds exeption
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
System.out.printf("%4.2f %n",beforeDiscount);
System.out.printf("%4.2f %n",afterDiscount);
}
else {
System.out.println("NOT Found");
}//if
txPartNo=inTransFile.nextInt();//Sub Read
}//While
} // main
}
ThankYou for your comments I was able to rectify the problem, my discount array was beginning at position 1 rather than position 2, therefore, cause the out of bounds exception
changed the code from this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
to this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode-1]);
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;
How can I add the units he/she enrolled every time the user inputs the code he/she wants to enroll? Is there any way I can add the units every time he/she enroll using arrayList?
int units = 3
arrList.add("A25"+"\t\tCS 212"+"\t\tData Structures\t\t\t\t"+ units);
arrList.add("A26"+"\t\tIT 312"+"\t\tData Base Management System 2\t\t"+ units);
arrList.add("A27"+"\t\tIT 312"+"\t\tData Base Management System 2\t\t"+ units);
System.out.println("\n\t\tCodes to enroll");
for(int i = 0; i < 3; i++,num++)
{
codeNo[i] = scan.next();
}
for (String s : arrList) {
for(int i =0; i < codeNo.length; i++)
if (s.startsWith(codeNo[i])) {
System.out.println("\t\t\t"+s);
/**
* this is what I tried
* units = units + units;
*/
}
}
tuitionFee = ( tuitionFee * units + miscFee ) / 3;
System.out.println("\n\n\t\tTOTAL FEE: ");
System.out.printf("\t\tPrelims: "+"%.2f",tuitionFee);
System.out.printf("\t\tMidTerm: "+"%.2f",tuitionFee);
System.out.printf("\t\tFinals: "+"%.2f",tuitionFee);
HashMap<String,Integer> mapCodeToUnit = new HashMap<String,Integer>();
mapCodeToUnit.put("A25", 3);
mapCodeToUnit.put("A26", 3);
mapCodeToUnit.put("A27", 3);
arrList.add("A25"+"\t\tCS 212"+"\t\tData Structures\t\t\t\t"+ mapCodeToUnit.get("A25"));
arrList.add("A26"+"\t\tIT 312"+"\t\tData Base Management System 2\t\t"+ mapCodeToUnit.get("A26"));
arrList.add("A27"+"\t\tIT 312"+"\t\tData Base Management System 2\t\t"+ mapCodeToUnit.get("A27"));
System.out.println("\n\t\tCodes to enroll");
String codeNo[] = new String[3];
for(int i = 0; i < 3; i++,num++)
{
codeNo[i] = scan.next();
}
int totalNumberOfUnit = 0;
for(int i =0; i < codeNo.length; i++) {
totalNumberOfUnit += mapCodeToUnit.get(codeNo[i]);
}
tuitionFee = ( tuitionFee * totalNumberOfUnit + miscFee ) / 3;
Make a list of EntrollmentDTO instead of list of String
EntrollmentDTO.java
class EntrollmentDTO {
private String id;
private String subId;
private String subName;
// Getters & Setters
}
Make a List of EntrollmentDTO as,
ArrayList<EntrollmentDTO> entrollmentList = new ArrayList<EntrollmentDTO>();
And add details as,
EntrollmentDTO entrollmentDTO = new EntrollmentDTO();
entrollmentDTO.setId("A25");
// set all values
entrollmentList.add(entrollmentDTO);
By this you can easily access needed values from the list.
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++;
}
}