Several errors keep occurring in eclipse - java

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.

Related

Unable to assign values to multi dimensional array which shows is not assignable in objective c

Ive written this java code how can i do the equivalent in objective c. Is this a correct approach of doing aa am new to objective c
public double[][] valuesR = new double[100][16];
public double[][] valuesIR = new double[100][16];
public int snrDataBufferSize = 0;
public String Test()
{
//ch1 ch2... are the the values in float
double[] channelValuesR = {ch1R, ch2R, ch3R, ch4R, ch5R, ch6R, ch7R, ch8R, ch9R, ch10R, ch11R, ch12R, ch13R, ch14R, ch15R, ch16R};
double[] channelValuesIR = {ch1IR, ch2IR, ch3IR, ch4IR, ch5IR, ch6IR, ch7IR, ch8IR, ch9IR, ch10IR, ch11IR, ch12IR, ch13IR, ch14IR, ch15IR, ch16IR};
if (snrDataBufferSize > 99){
//Reset buffer counter to 0
snrDataBufferSize = 0;
//Get signal SNR
getSNR();
}
else{
//Build double array values with 16 channels of value
valuesR[snrDataBufferSize] = channelValuesR;
valuesIR[snrDataBufferSize] = channelValuesIR;
//Iterate bufferSize counter
snrDataBufferSize++;
}
}
ive wriiten like this but am getting the error in building the double array value with 16 channels of value
double valuesR[100][16];
double valuesIR[100][16];
int snrDataBufferSize = 0;
-(void) Test {
double channelValuesR[] = {ch1R, ch2R, ch3R, ch4R, ch5R, ch6R, ch7R, ch8R, ch9R, ch10R, ch11R, ch12R, ch13R, ch14R, ch15R, ch16R};
double channelValuesIR[] = {ch1IR, ch2IR, ch3IR, ch4IR, ch5IR, ch6IR, ch7IR, ch8IR, ch9IR, ch10IR, ch11IR, ch12IR, ch13IR, ch14IR, ch15IR, ch16IR};
if (snrDataBufferSize > 99){
//Reset buffer counter to 0
snrDataBufferSize = 0;
}
else{
//Build double array values with 16 channels of value
valuesR[snrDataBufferSize] = channelValuesR;
valuesIR[snrDataBufferSize] = channelValuesIR;
//Iterate bufferSize counter
snrDataBufferSize++;
}
}
Is this a right way or is there any other way to do this

How to iterate to find the lowest value

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];
}
}

Unable to calculate discount

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]);

Java Array skipping Outputs?

I'm currently working on an assignment for my programming class and I cannot figure out why my output is coming out wrong.
We are supposed to "Print the “Difference” of population from the previous year. (Of course, this value is blank for the first year in the list.)
Use format control to print the values for Year, Population value and Difference from previous year. "
And my teacher gave us what the output is supposed to look like:
Desired Output:
But I keep getting this:
My Output:
This is my code:
import java.util.Scanner;
import java.io.*;
public class AssignmentOne
{
public static void main(String[] args) throws IOException
{
// Array Version
ArrayVersion();
System.out.println("Finished Array Version of Assignment");
}
// Method for ArrayVersion
public static void ArrayVersion() throws IOException
{
// Year as variables
int year = 1950;
final int ARRAY_SIZE = 41;
// Array to use for Population data
int[] population = new int[40];
// Call the method to get data into array
population = getDataFromFile("USPopulation.txt");
if(population == null)
{
System.out.println("Error: Population did not load");
return;
}
// Output
System.out.println("This is the Simple Array Version of \nPopulation Data US");
System.out.println("\nYear \tPopulation \tDifference");
System.out.println("");
System.out.printf("%d \t%,d,000\n", year, population[0]);
for(int i = 1; i < population.length; i++)
{
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], Math.abs(population[i] - population[++i]));
}
// Calculating the average + displaying it
int sum = 0;
for(int g = 0; g < population.length; g++)
{
sum += population[g];
}
int average;
average = sum / population.length;
System.out.println("Average:" + average);
}
// Method to get data from specified "filename" into an array of ints
public static int[] getDataFromFile(String USPopulation) throws IOException
{
// Array to use for Population data
// Opening file
File file = new File("E:/Programming 2/Assignment 1/src/USPopulation.txt");
Scanner inputFile = new Scanner(file);
int fileSize = 0;
while(inputFile.hasNext())
{
inputFile.nextInt();
fileSize++;
}
Scanner input2 = new Scanner(file);
int[] fileData = new int[fileSize];
for(int i = 0; i < fileSize; i++)
{
fileData[i] = input2.nextInt();
}
// System.out.println(fileData[40]);
// return the array fileData
return fileData;
}
population[++i]
There's your problem.
The prefixed increment simply increments the value of i before it gets the value, where i++ gets the value then increments i.
Just change it to population[i+1] and you'll be good. :P
Edit:
for(int i = 1; i < population.length; i++)
{
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], population[i] - population[i-1]);
}
The whole problem is in this line:
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], Math.abs(population[i] - population[++i]));
First, using ++i bumps your loop counter i one extra time per iteration, so you're only looking at every other year. No doubt you were trying to find the difference between one year's population and that of the next year; the correct way to look at next year's population would have been population[i+1]. But, as you say, using population[i+1] eventually gives you IndexOutOfBoundsException. Well, that's because when i is pointing to the last year, i+1 points beyond the end of the array of population data.
The second problem, then, is that you really want to be finding the difference between each year's population and that of the previous year: population[i] - population[i - 1]. So now, when i points at the last year, i-1 will still be within the array bounds, and because your loop actually starts with i == 1, i - 1 will still be a valid index.

For loop return to previous for validation

I'm making an Earliest Deadline Algorithm and I need a validation. I have a for loop which accepts 3 inputs, for example if I enter first these values which are arrival time, burst time and deadline:
5 5 10
and the next values are
0 1 20
What I need is to validate if the second input for arrival time is lower than the previous input. If so, it will output an error message and it will again enable me to enter values for second job. It will continue doing this until it sees a valid input.
for(int m=1;m<=n;m++)
{
System.out.println("enter arrival time, burst time and deadline of process "+(m)+"(0 for none):");
arrival[m]=sc.nextInt();
burst[m]=sc.nextInt();
deadline[m]=sc.nextInt();
}
Store your old value (v in the sample) and compare it to the new one (vn in the sample):
class Values {
public final int arrival;
public final int burst;
public final int deadline;
public Values(int a, int b, int d) {
this.arrival = a;
this.burst = b;
this.deadline = d;
}
}
Values v = new Values(Integer.MIN_VALUE, Integer.MIN_VALUE,
Integer.MIN_VALUE);
Values vn;
do {
vn = new Values(sc.nextInt(), sc.nextInt(), sc.nextInt());
} while (vn.arrival < v.arrival);
To do a quick resume, you could do something like this.
Let's say you read the values from console.
int[] array = new int[2];
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int j = 0; j < array.length ; j++) {
int k = Integer.parseInt(br.readLine());
array[j] = k;
if((j == 1) && (array[j] > array[j-1])) {
System.out.printLn("Burst time must be lower than arrival time");
j--;
}
}
}
catch (Exception e) {
e.printStackTrace();
}

Categories

Resources