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
}
Related
Struggling to understand where I went wrong with the iteration at the get best fare method
The array holds [5.77, 2.44, 2.35] and should return the second index, however it seems that it is stuck at the double lowestPrice = lowestPriceRide[0];
I thought that maybe I was putting the return out of scope, but it didn't work.
> import java.lang.*;
import java.util.Arrays;
public class TransitCalculator {
double numberOfDays = 0.0;
double numberOfRides = 0.0;
double pricePerRide = 2.75;
double pricePerWeek = 33.00;
double priceUnlimited = 127.00;
double perRide = 0.00;
public TransitCalculator(double days, double rides){
numberOfDays = days;
numberOfRides = rides;
}
public double unlimited7Price(){
double numOfWeeks = Math.ceil(numberOfDays/7) ; // Math.ceil will return the largest integer that is divisble without a remainder //
double totalPrice = numOfWeeks * pricePerWeek;
return totalPrice / numberOfRides;
}
public double[] getRidePrices(){ // 28/06/2020 Sunday. Math is verified.
double perRide = pricePerRide * numberOfRides / numberOfDays;
double perWeek = unlimited7Price();
double unlimited = priceUnlimited / numberOfRides;
double ridePrices[]; // Declared Array //
ridePrices = new double[] {perRide, perWeek, unlimited}; // New array, with added elements. Could be a mistake since I failed to declare elements//
return ridePrices;
}
public String getBestFare(){ // Error in the iteration and lowest value find! //
double lowestPriceRide[];
lowestPriceRide = getRidePrices();
double lowestPrice = lowestPriceRide[0];
for(int i = 0; i< lowestPriceRide.length; i++) {
if (lowestPrice < lowestPriceRide[i]) {
lowestPriceRide[i] = lowestPrice;
}
}
if(lowestPrice == lowestPriceRide[0]){
System.out.println("You should take the 'Pay per Ride' option in our NYC transit");
}
else if(lowestPrice == lowestPriceRide[1]){
System.out.println("You should take the 'Weekly Unlimited' plan in our NYC Transit");
}
else if(lowestPrice == lowestPriceRide[2]){
System.out.println("You should take the Unlimited ride plan in our NYC Transit");
}
return "at " + lowestPrice + "$ per Ride";
}
public static void main(String[] args){
TransitCalculator test = new TransitCalculator(26, 54);
System.out.println(test.getBestFare()); //
}
}
You are not setting the right value; currently, you set the element in the array to the lowest price instead of setting the lowest price to the element of the array. You also compare against the wrong value; you should check that the current array element is less than the best price, instead of the other way around.
Change
if(lowestPrice < lowestPriceRide[i])
lowestPriceRide[i] = lowestPrice;
To
if(lowestPriceRide[i] < lowestPrice)
lowestPrice = lowestPriceRide[i];
See the updated code in action here.
Note that it is unnecessary to import java.lang, as the package is implicitly imported.
The problem is in your if condition:
if (lowestPrice < lowestPriceRide[i]) {
lowestPriceRide[i] = lowestPrice;
}
You need to see if the current lowestPriceRide[i] is less than the already existing lowestPrice then update your existing lowestPrice. So the condition would be now:
if (lowestPriceRide[i] < lowestPrice) {
lowestPrice = lowestPriceRide[i];
}
This should be your comparison for lowest price :
double lowestPrice = lowestPriceRide[0];
for(int i = 0; i< lowestPriceRide.length; i++) {
if (lowestPriceRide[i] < lowestPrice) {
lowestPrice = lowestPriceRide[i];
}
}
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.
So I have a list of doubles that I am trying to add up. I am rather new to Java so this might be a dumb question: how do I return the arraylist's doubles together in a single variable? Any help is appreciated :)
public double totalVolume(){
double volume = 0;
if (cList.size() != 0) {
volume = cList.get(0).volume();
}
else {
return 0;
}
int indexVolume = 0;
while (indexVolume < cList.size()) {
if (!(indexVolume < cList.get(indexVolume).volume())) {
volume = cList.get(indexVolume).volume();
}
// how do I take volume and add it to itself after each while loop?
indexVolume++;
}
return volume;
}
Are you just trying to keep a running total?
You could just type this:
volume = volume + cList.get(indexVolume).volume();
or, shorter,
volume += cList.get(indexVolume).volume();
I am continuing to get this error. Now I have gotten it for my SortSearchUtil. I've tried to do some debugging but can fix the issue. The error reads:
----jGRASP exec: java PostOffice
Exception in thread "main" java.lang.NullPointerException
at SortSearchUtil.selectionSort(SortSearchUtil.java:106)
at PostOffice.sortLetters(PostOffice.java:73)
at PostOffice.main(PostOffice.java:15)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
line 106 of selection Sort is:
if (array[indexSmallest].compareTo(array[curPos]) > 0)
I don't know what could be wrong with my method. It's a standard method that was given to me by my instructor. I've tried to debug my program but I'm pretty stuck. Here is the method that the error is originating from, selectionSort:
public static void selectionSort(Comparable[] array)
{
int curPos, indexSmallest, start;
Comparable temp;
for (start = 0; start < array.length - 1; start++)
{
indexSmallest = start;
for (curPos = start + 1; curPos < array.length; curPos++)
if (array[indexSmallest].compareTo(array[curPos]) > 0)
{
indexSmallest = curPos;
}
// end for
temp = array[start];
array[start] = array[indexSmallest];
array[indexSmallest] = temp;
} // end for
}
The sort method is at the bottom which calls SortSearchUtil.selectionSort of this Post Office Method:
import java.util.*;
import java.io.*;
public class PostOffice
{
private final int max = 1000;
private Letter [] ltrAra = new Letter[max];
private int count;
public static void main(String [] args)
{
PostOffice postOffice = new PostOffice();
postOffice.readLetters("letters.in");
postOffice.sortLetters();
postOffice.printLetters();
}
public PostOffice()
{
Letter [] Letters = ltrAra;
this.count = 0;
}
public void readLetters(String filename)
{
int count = 0;
int iWork = 0;
Scanner fin = new Scanner(filename);
String toName, toStreet, toCity, toState, toZip;
String fromName, fromStreet, fromCity, fromState, fromZip, temp;
double weight;
String sWork;
fin = FileUtil.openInputFile(filename);
if (fin != null)
{
while (fin.hasNext())
{
toName = fin.nextLine();
toStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
toCity = sWork.substring(0, iWork);
iWork = iWork + 2;
toState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
toZip = sWork.substring(iWork);
fromName = fin.nextLine();
fromStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
fromCity = sWork.substring(0, iWork);
iWork = iWork + 2;
fromState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
fromZip = sWork.substring(iWork);
sWork = fin.nextLine();
weight = Double.parseDouble(sWork);
ltrAra[count] = new Letter(toName, toStreet, toCity, toState, toZip, fromName, fromStreet, fromCity, fromState, fromZip, weight);
count++;
}
fin.close();
}
}
public void sortLetters()
{
SortSearchUtil.selectionSort(ltrAra);
}
public void printLetters()
{
for (Letter ltr : ltrAra)
{
System.out.println(ltr);
System.out.println();
}
}
}
My file looks like this "letters.in":
Stu Steiner
123 Slacker Lane
Slackerville, IL 09035
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
0.50
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
Chris Peters
123 Some St.
Anytown, CA 92111-0389
1.55
Obviously you get a NPE because:
You initialize ltrAra as array of 1000 items, but you read in less than 1000 items within method readLetters(). So at the end of this array some null references remain un-initialized (remember array-creation does itself not set the single items to any objects). Therefore following sorting-method gets some null-references => NPE.
Suggested solution:
You should use an ArrayList instead of an array because that will automatically prevent you from accessing too much items due to internal range check.
In addition to the above answer that Meno has well stated, you need to understand when you get a Null pointer Exception.
your error-line : if (array[indexSmallest].compareTo(array[curPos]) > 0)
If we get NPE in this line, it is obvious that array[indexSmallest] is null
And when you invoke an action on null, you get NPE. Hope this helps you to debug, down the line.
Also, One of the main reasons when we choose ArrayList over Arrays is when we do not know the length of the array.
One more suggestion, you can create an ArrayList and then convert to Arrays if you want to stick with Arrays
To convert ArrayList of any class into array, Convert T to the respective class. For eg: if you want String array, convert T to 'String'
List<T> list = new ArrayList<T>();
T [] students = list.toArray(new T[list.size()]);
I have a list of dates and prices:
Date Price
1/3/2000 10.00
1/5/2000 10.45
1/7/2000 10.25
... ...
I have a separate list of dates with all dates:
Date
1/1/2000
1/2/2000
1/3/2000
...
I need to have them combined so that the prior price is filled in for the dates that are missing prices:
Date Price
1/1/2000 10.00
1/2/2000 10.00
1/3/2000 10.00
1/4/2000 10.00
1/5/2000 10.45
1/6/2000 10.45
1/7/2000 10.25
... ...
I am currently trying to loop through array lists holding the data but can't line the dates up correctly, especially at the beginning and end. I am using Java/Mysql/JDBC right now but am open to R also. Thanks for any suggestions.
Thanks to everyone for your help. Here's what I ended up doing:
-I created a list of all indexes where the dates matched.
-I then inserted the prices into an array with the same number of elements as the full time list.
-I then created 3 loops, one for the elements before the first matching time, one for the elements after the last matching element and finally one for everything in between.
-These three filled in the prices that were missing.
Just though I'd share. Thanks for all your help.
public static void checkLengths(ArrayList<String> masterTimes, ArrayList<String> testTimes, ArrayList<Double> prices){
ArrayList<Double> temp = new ArrayList<Double>();
ArrayList<Integer> matches = new ArrayList<Integer>();
Double[] temp2 = new Double [masterTimes.size()];
int mt = masterTimes.size();
int tt = testTimes.size();
if(mt == tt){
return;
}else{
int mast = 0;
int test = 0;
String mt1 = masterTimes.get(0);
String tt1 = testTimes.get(0);
test = 0;
for(int i = 0; i < masterTimes.size(); i++){
mt1 = masterTimes.get(i);
tt1 = testTimes.get(test);
System.out.println(" | mt1: " + mt1 + " | tt1: " + tt1);
if(mt1.equals(tt1)){
matches.add(i);
System.out.println("Inserting: " + i);
if(test < testTimes.size()){
test++;
}
if(test == testTimes.size()){
break;
}
}
}
System.out.println("Matches:");
printAL(matches);
// puts in known prices.
for(int i = 0; i < matches.size(); i++){
int g = matches.get(i);
temp2[g] = prices.get(i);
}
System.out.println("FirstPrices:");
printAR(temp2);
// Finds index of first and last matching times.
int matcher1 = matches.get(0);
int ind = matches.size() - 1;
int matcher2 = matches.get(ind);
System.out.println("Matcher1:" + matcher1 + " | Matcher2: " + matcher2);
// If a price is empty/null, it puts the prior price in it.
for(int i = matcher1; i < matcher2; i ++){
System.out.println(i + " | " + temp2[i]);
if(temp2[i] == null){
System.out.println(temp2[i] + " | " + temp2[i-1]);
temp2[i] = temp2[i-1];
}
}
System.out.println("SecondPrices:");
printAR(temp2);
// Deals with start.
for(int i = matcher1; i >= 0; i--){
if(temp2[i] == null){
temp2[i] = temp2[i+1];
}
}
System.out.println("ThirdPrices:");
printAR(temp2);
// Deals with end.
for(int i = matcher2; i < temp2.length; i++){
if(temp2[i] == null){
temp2[i] = temp2[i-1];
}
}
System.out.println("FourthPrices:");
printAR(temp2);
prices.clear();
System.out.println("Final Check:");
for (int i = 0; i < masterTimes.size(); i++){
System.out.println(i + " | " + masterTimes.get(i) + " | " + temp2[i]);
}
}
}
It is difficult to help without looking at the code but it seems like your indexes are not matching up or something is wrong with your looping logic.
Consider using a HashTable or a HashMap using the date strings as keys and price as values.
Loop through your date range one day at a time look up the price in the HashTable, if not found then use the previous price.
This sort of problem does take a bit of doing to do correctly. Sometimes using a flow chart helps if you get stuck.
Try using the following sample code:
import java.sql.*;
import java.util.*;
public class FillDates
{
public static void fillUnknownDates(Connection c) throws SQLException
{
// Loads in a Vector of Strings of all the dates
Statement state = c.createStatement();
ResultSet results = state.executeQuery("SELECT d FROM Dates ORDER BY d;");
Vector<String> dates = new Vector<String>();
while (results.next())
{
dates.add(results.getString("d"));
}
// Load in a list of all date/price combinations
Vector<DatePrice> pairs = new Vector<DatePrice>();
state = c.createStatement();
results = state.executeQuery("SELECT d, p FROM DatePrices ORDER BY d;");
while (results.next())
{
pairs.add(new DatePrice(results.getString("d"), results.getString("p")));
}
// Now go through the two lists and add missing prices
state = c.createStatement();
int dateIndex = 0;
DatePrice last = pairs.get(0), current;
for (int pairIndex = 1; pairIndex < pairs.size(); pairIndex++)
{
current = pairs.get(pairIndex);
while (dateIndex < dates.size() && dates.get(dateIndex).compareTo(current.getDate()) < 0)
{
// Batch things up so it takes less time to run
state.addBatch("INSERT INTO DatePrices VALUES (\""+dates.get(dateIndex)+"\", \""+current.getPrice+"\");");
dateIndex ++;
}
last = current;
}
state.executeBatch();
}
// A convenience class
public static class DatePrice
{
private String date, price;
public DatePrice(String date, String price)
{
this.date = date;
this.price = price;
}
public String getDate()
{
return date;
}
public String getPrice()
{
return price;
}
}
}
Note that it's not complete, and you'll need to change the names of your tables and columns before trying it out.
Okay... I just shooting at it while being on the fon :)
In MySQL, let's assume you got two tables, dates_prices and all_dates. Then LEFT JOIN them on dates and order them by date.
If you use R and MySQL you can use the RMySQL package to load the resulting table to R.
In R you can convert the dates to POSIX with as.POSIXlt. You also might want to use the lagfunction in R (but I am not sure yet if that helps with lags of varying spans).
Apart from that you could use R's ´sqldf` package if you want to try with "plain" R but want to use SQL functionality. If you post some reproducible code to set up the data.. I could try to the give something more concrete back.
EDIT:
The impute package might be what you really looking for... see also here
Here is an R solution.
Uncomment the two install.packages lines if you don't have those packages already installed. Also textConnection(Lines1) and textConnection(Lines2) are just to keep the example self contained and in reality would be replaced with something like "myfile1.dat" and "myfile2.dat" assuming the data is in those files.
It reads in the data creating zoo object z and a Date vector dt. It then merges z with a zero width zoo object (i.e. it has dates but no data) whose date index is made from dt. na.locf (last observation carried forward) fills out the missing values in reverse order since fromLast = TRUE
Lines1 <- "Date Price
1/3/2000 10.00
1/5/2000 10.45
1/7/2000 10.25"
Lines2 <- "Date
1/1/2000
1/2/2000
1/3/2000"
# install.packages("zoo")
# install.packages("chron")
library(zoo)
library(chron)
z <- read.zoo(textConnection(Lines1), header = TRUE, FUN = as.chron)
dt <- as.chron(scan(textConnection(Lines2), skip = 1, what = ""))
na.locf(merge(z, zoo(, dt)), fromLast = TRUE)
The result is:
> na.locf(merge(z, zoo(, dt)), fromLast = TRUE)
01/01/00 01/02/00 01/03/00 01/05/00 01/07/00
10.00 10.00 10.00 10.45 10.25
There are three vignettes (PDF documents) that come with the zoo package and R News 4/1 Help Desk article has info and references on dates.