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.
Related
I'm attempting to create a programme which tracks the emails of people. I am using a string for the vertex in my graph (The string is their email) and a DefaultWeightedEdge from Jgrapht. If these people send one email between each other then the weight of the edge connecting that node is set to 1. If they send another email after already having sent one I increment the edge weight by 1.
I think I have the main bulk of the code correct, however I am getting this exception.
Exception in thread "main" java.lang.IllegalArgumentException: loops
not allowed at
org.jgrapht.graph.AbstractBaseGraph.addEdge(AbstractBaseGraph.java:203)
at groupProject.Analysis.StoreEmails(Analysis.java:58) at
groupProject.AnalyserRun.main(AnalyserRun.java:7)
Here is my code:
public class Analysis {
SimpleWeightedGraph<String, DefaultWeightedEdge> graph = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
jsonParser jP = new jsonParser("/Users/Kieran/test/test2.json");
int numEmails = jP.getNumEmails();
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> recipients = new ArrayList<String>();
ArrayList<String> all = senders;
ArrayList<DefaultWeightedEdge> edges = new ArrayList<DefaultWeightedEdge>();
public void StoreEmails(){
//Creates vertex's for every sender
for(int i = 0; i < numEmails; i++){
Email email = jP.parseJSON(i);
if(!senders.contains(email.getSender())){
graph.addVertex(email.getSender());
senders.add(email.getSender());
}
}
//creates vertex's for every recipient
for(int i = 0; i < numEmails; i++){
Email email = jP.parseJSON(i);
if(email.getRecipients().length != 0){
for(int j = 0; j < email.getRecipients().length; j++){
if(!recipients.contains(email.getRecipients()[j])){
graph.addVertex(email.getRecipients()[j]);
recipients.add(email.getRecipients()[j]);
}
}
}
}
all.removeAll(recipients);
all.addAll(recipients);
/*
* Adds all of the edges from senders to recipients and if the edge already exists then it will increase the weight by one
* however is is a directed graph so you need to check both pairs.
*/
for(int j = 0; j < numEmails; j++){
Email email = jP.parseJSON(j);
for(int k = 0; k < email.getRecipients().length; k++){
if(graph.containsEdge(email.getSender(), email.getRecipients()[k])){
int current_weight = (int) graph.getEdgeWeight(graph.getEdge(email.getSender(), email.getRecipients()[k]));
graph.setEdgeWeight(graph.getEdge(email.getSender(), email.getRecipients()[k]), current_weight+1);
}else{
DefaultWeightedEdge e = graph.addEdge(email.getSender(), email.getRecipients()[k]);
graph.setEdgeWeight(e, 1);
}
}
}
builder();
}
public int calcConnectedness(String s1,String s2){
int connectedness = 0;
int weightS1S2 = 0;
int weightS2S1 = 0;
if(graph.containsEdge(s1, s2)){
weightS1S2 = (int) graph.getEdgeWeight(graph.getEdge(s1, s2));
connectedness += weightS1S2;
}
/*if(graph.containsEdge(s2, s1)){
weightS2S1 = (int) graph.getEdgeWeight(graph.getEdge(s2, s1));
connectedness += weightS2S1;
}*/
return connectedness;
}
public void builder(){
for(int i = 0; i < all.size(); i++){
for(int j = i+1; j < all.size(); j++){
if(graph.containsEdge(all.get(i), all.get(j)))
make(all.get(i), all.get(j), calcConnectedness(all.get(i), all.get(j)));
}
}
}
public void make(String user1, String user2, int connectedness){
System.out.println(user1 + " " + user2 + " Are connected by a factor of: "+connectedness);
}
}
After some research the only information I was able to find which may be causing the problem is the fact that in Java, strings are immutable. However, I was still not able to resolve my issues.
The answer was in this section of code:
}else{
DefaultWeightedEdge e = graph.addEdge(email.getSender(), email.getRecipients()[k]);
graph.setEdgeWeight(e, 1);
}
It turns out that email.getSender() was in email.getRecipients() so the source and destination of the edge was the same i.e a loop. I solved the issue by doing a simple check beforehand with an if statement to only add an edge if it was not the same as the source.
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();
}
});
I'm trying to write a program that opens a txt file and display information from that txt file. Java is my first language, and I'm taking java as a second language class since there's no beginning java class in my school. I'm struggling with this code for about an week. Any little help would be helpful. Appreciate for your help.
It keeps saying :
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException:6
at store.Franchise.<init>(Franchise.java:10)
at store.FileIO.readData(FileIO.java:10)
at store.Driver.main(Driver.java:9)
Here is what I've got:
Sample txt file:
Day1 Day2 Day3 Day4 Day5
2541.56 2258.96 2214 2256 2154
2041.56 1758.96 1714 1756 1654
3041.56 2758.96 2714 2756 2654
3563.54 3280.94 3235.98 3277.98 3175.98
2547.21 2264.61 2219.65 2261.65 2159.65
4040.55 3757.95 3712.99 3754.99 3652.99
Store.java:
package store;
import java.io.IOException;
public class Store {
private float salesByWeek[][];
public Store() {
salesByWeek = new float[5][7];
// assign the array value at index 5, t to salesByWeek
}
public void setSaleForWeekDayIntersection(int week, int day, float sale) {
salesByWeek[week][day] = sale;
// store the sale value to SalesByWeek array at the index pointed to by week, day
// for exaample, it can be week 2 and day 3 (Wednesday)
}
float[] getSalesForEntireWeek(int week) {
// this will find the total sales for the whole week - all 5 days or 7 days including week ends Saturday and Sunday
float[] sales = new float[7];
// declare an array of type float and of size 7 - name the array as sales
for (int d = 0; d < 7; d++)
{
sales[d] = salesByWeek[week][d];
// the index d runs from 0 to 7
}
return sales;
}
float getSaleForWeekDayIntersection(int week, int day) {
return salesByWeek[week][day];
// the return value is the arraycontent pointed to by index week and day
}
float getTotalSalesForWeek(int week) {
float total = 0;
for (int d = 0; d < 7; d++)
{
total += salesByWeek[week][d];
// increment total by adding the array content salesByWeek at index week, d ( if d is the day)
}
return total;
// send the value of total back to the caller function
}
float getAverageSalesForWeek(int week) {
return getTotalSalesForWeek(week) / 7;
// divide the total sales for the whole week by 7 so that we get the average sales and return it
}
float getTotalSalesForAllWeeks() {
float total = 0; // declare a total variable of type float and initialize to 0 ( zero)
for (int w = 0; w < 5; w++)
{
total += getTotalSalesForWeek(w);
// sum up the total for the whole week and store it to the total variable
}
return total;
// return the sum computed above
}
float getAverageWeeklySales() {
return getTotalSalesForAllWeeks() / 5;
// AVERAGE for 5 days - just Monday to Friday only - excludes the week ends
}
int getWeekWithHighestSaleAmount() {
// top performing sales in the whole week
int maxWeek = 0;
float maxSale = -1;
for (int w = 0; w < 5; w++)
// run the for loop from 0 to 5 in steps of 1
{
float sale = getTotalSalesForWeek(w);
// first store the total sales in to the sale variable of type float
if (sale > maxSale)
{ // if at all if we find any amount greater than the max sale then replace max sale with the new sale amount
// and also note down the contributor - in the sense that which w ( week) achieved top sales
maxSale = sale;
maxWeek = w;
}
}
return maxWeek;
}
int getWeekWithLowestSaleAmount() {
int minWeek = 0;
float minSale = Float.MAX_VALUE;
for (int w = 0; w < 5; w++)
{
float sale = getTotalSalesForWeek(w);
if (sale < minSale)
{
minSale = sale;
minWeek = w;
}
}
// comments are same as the top sales except in reverse order
// first store an arbitary minimum sale figure
// then compare each running week's vaue with the lowest
// if at all when we encounter any value lower than the preset value then replace it
return minWeek;
// finally return the minimum value in that week
}
public void analyzeResults() {
for (int w = 0; w < 5; w++) // run the for loop from 0 to 5
{
System.out.printf("---- Week %d ----\n", w); // print a title decoration
System.out.printf(" Total sales: %.2f\n", getTotalSalesForWeek(w)); // display or print out the total sales summed earlier in called function
System.out.printf(" Average sales: %.2f\n", getAverageSalesForWeek(w)); // display the average sales figure
}
System.out.printf("\n");
System.out.printf("Total sales for all weeks: %.2f\n", getTotalSalesForAllWeeks()); // print sum of the sales for the entire week
System.out.printf("Average weekly sales: %.2f\n", getAverageWeeklySales()); // print weekly average sales
System.out.printf("Week with highest sale: %d\n", getWeekWithHighestSaleAmount()); // print highest performing or top sales
System.out.printf("Week with lowest sale: %d\n", getWeekWithLowestSaleAmount()); // print lowest sales or the struggling week
}
public void setsaleforweekdayintersection(int week, int day, float f) {
}
}
Franchise.java:
package store;
public class Franchise {
private Store stores[];
public Franchise(int num) { // now for a franchise store
stores = new Store[num]; // instantiate an array object of type class Store
// the class is Store
// the objects are named as stores
for(int i=0; i<=num; i++) stores[i] = new Store();
}
public Store getStores(int i) { // GETTER display or return values
return stores[i];
}
public void setStores(Store stores, int i) { // setter assign values
this.stores[i] = stores;
}
}
FileIO.java:
package store;
import java.io.*;
import java.util.StringTokenizer;
public class FileIO {
// Franchise readData(String filename)
Franchise readData(String filename, int numstores) {
Franchise f1 = new Franchise(numstores);
boolean DEBUG = true;
int ctr = 0;
// open the file
// read the line
// parse the line - get one value
// and set it in the correct location in 2 d array
try {
FileReader file = new FileReader(filename); // file is equivalent to a file pointer in c/c++
BufferedReader buff = new BufferedReader(file); // buffered reader will read a chunk in to the variable buff
boolean eof = false;
while (!eof) {
String line = buff.readLine();
ctr++;
if (line == null)
eof = true;
else {
if (DEBUG)
System.out.println(line);
if (ctr > 1) {
StringTokenizer a = new StringTokenizer(line);
for (int week = 0; week < 5; week++) {
for (int day = 0; day < 7; day++) {
String l = a.nextToken();
float f = Float.parseFloat(l); // parseFloat will store to variable f of type float
f1.getStores(ctr - 2)
.setsaleforweekdayintersection(week,
day, f);
if (DEBUG)
System.out.print("f" + f + " ");
}
}
}
}
}
} catch (IOException f2) {
}
return f1;
}
}
Driver.java:
package store;
public class Driver
{
public static void main(String[] args)
{
FileIO readdata = new FileIO();
Franchise f1 = readdata.readData("E:/Files/Salesdat.txt", 6);
System.out.println("Data read");
}
}
DriverImpl.java ( I got no idea why I need this subclass, but my tutor told me that I need this):
package store;
public class DriverImpl extends Driver {
}
I would like to change the line 10 in Franchise.java to
for(int i=0; i<num; i++) stores[i] = new Store();
Notice I removed the <= and put an = instead. Whenever dealing with array indices, one should always use the < comparator with the size as a good practice.
Valid indexes in an array are 0 to length - 1. Change <= to < like,
stores = new Store[num];
// the class is Store
// the objects are named as stores
for(int i=0; i<num; i++) stores[i] = new Store(); //stores[num] is invalid.
I have created a program for calculating the interest on given values. But when i calculate it, the output on the jList comes out in one line, 10 times.
Can anyone help me, and tell me why this happens :)?
From my calculate class
public ArrayList<String> calculateInterest(double years, double principal, double amount)
{
ArrayList<String> results = new ArrayList<>();
for (years = 1; years <= 10; years++)
{
amount = principal * Math.pow(rate + 1, years);
String amountToString = "" + amount;
results.add(amountToString);
}
return results;
}
ยด
From my GUI (Under the button)
double aar = Double.parseDouble(txtAntalAar.getText());
double belob = Double.parseDouble(txtBelob.getText());
double rente = Double.parseDouble(txtRente.getText());
ArrayList output = cal.calculateInterest(aar, belob, rente);
for (int i = 0; i < output.size(); i++)
{
myListModel.add(i, output);
}
I have also tried with:
for (String s : cal.calculateInterest(aar, rente, rente))
{
myListModel.addElement(output);
}
But same issue. Here is a photo of the output - I what them to switch line between each number:
You are adding the whole list instead of the element. Use
for (int i = 0; i < output.size(); i++)
myListModel.add(i, output.get(i));
That's because you are adding the entire ArrayList and not de item.
for (String s : cal.calculateInterest(aar, rente, rente))
{
//myListModel.addElement(output); this way you add the entire array
myListModel.addElement(s); // now you add only the item
}
I'm working on a programm in which I want my object "this" will be an array of Point but I have this error when I run the programm and I'm not understand why.
Error --> DouglasPeucker.
My programm :
public class DouglasPeucker {
private double epsilon;
protected Point[] coinImage;
public DouglasPeucker(Point [] tab) {
this.coinImage = new Point[tab.length];
for(int i = 0; i < this.coinImage.length; i++) {
double abscisse = tab[i].getX();
double ordonnee = tab[i].getY();
System.out.println(abscisse + " " + ordonnee);
this.coinImage[i].setX(abscisse);
this.coinImage[i].setY(ordonnee);
}
}
You're never assigning a value to coinImage[i], so it will have its default value of null, which you're the dereferencing. You need something like:
for(int i = 0; i < this.coinImage.length; i++) {
double abscisse = tab[i].getX();
double ordonnee = tab[i].getY();
System.out.println(abscisse + " " + ordonnee);
this.coinImage[i] = new Point();
this.coinImage[i].setX(abscisse);
this.coinImage[i].setY(ordonnee);
}
Or preferrably, IMO:
for (int i = 0; i < this.coinImage.length; i++) {
// I'm assuming Point has a sensible constructor here...
coinImage[i] = new Point(tab[i].getX(), tab[i].getY());
// Insert the diagnostics back in if you really need to
}