I'm trying to convert my single dimensional array into a multidimensional array. Convert the existing Interest Calculator Batch application from several single dimensional arrays
into 1 multi-dimensional array. Use the following data type: double[][] values;
Hint: The maximum number of data sets(5) will be your row and the each data array (from the original InterestCalculatorBatch)(7)will be a column.
2.All data will be contained within a
single multi-dimensional array.
3. Modify the sortBySimple and displayInterest methods to accept a single multi-dimensional array instead of multiple single dimensional arrays
I fixed the displayInterest to accept a single multi dimensional array. I am just confused if I have the sortBySimple set up correctly and when the program calculates the interest if I need to fix those or keep them as is. Thank you for the help.
import java.util.Scanner;
public class InterestCalculatorBatchMDA {
public static void main(String[] args )
{
int cnt = 0;
double[][] arrPrincipalAmt = new double[5][7];
double[][] arrInterestRate = new double[5][7];
double[][] arrTerm = new double[5][7];
double[][] arrSimple = new double[5][7];
double[][] arrCompoundMonthly = new double[5][7];
double[][] arrCompoundDaily = new double[5][7];
double[][] arrCompoundWeekly = new double[5][7];
do{
arrPrincipalAmt[cnt] = getPrincipalAmount(1);
arrInterestRate[cnt] = getInterestRate(1);
arrTerm[cnt] = getTerm(1);
arrSimple[cnt] = round(calculateSimpleInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt]),5);
arrCompoundMonthly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt],arrTerm[cnt] ,12.0 ),5);
arrCompoundWeekly[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 52.0 ),5);
arrCompoundDaily[cnt] = round(calculateCompoundInterest(arrPrincipalAmt[cnt], arrInterestRate[cnt], arrTerm[cnt], 365.0 ),5);
cnt++;
}while (cnt < 5 && askYesNo("Enter another set of data (Yes/No):"));
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
sortBySimple(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
displayInterest(arrPrincipalAmt,arrInterestRate,arrTerm,arrSimple,arrCompoundMonthly,arrCompoundWeekly,arrCompoundDaily,cnt);
}
/** Round **/
public static double round(double numb1, double numb2) {
double round = ((double) Math.round(numb1*(Math.pow(10, numb2)))/(Math.pow(10, numb2)));;
return round;
}
/** Calculate Simple **/
public static double calculateSimpleInterest(double numb1, double numb2, double numb3) {
double calculateSimpleInterest = ((numb1)*(numb2/100.0)*(numb3/12.0));
return calculateSimpleInterest;
}
/** Calculate Compounded Daily **/
public static double calculateCompoundInterest(double numb1, double numb2, double numb3, double numb4 ) {
double calculateCompoundInterest = (numb1*Math.pow((1.0+((numb2/100.0)/numb4)),(numb4*(numb3/12.0))))-numb1;
return calculateCompoundInterest;
}
/** Get principal amount **/
public static double getPrincipalAmount(double numb1) {
Scanner input = new Scanner(System.in);
double numb2 = 1;
do{System.out.print("Enter Loan Amount: ");
numb2 = input.nextDouble();
if(numb2 > 0);
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 < 0);
return numb2;
}
/** Get interest rate **/
public static double getInterestRate(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter Yearly Interest Rate (1 to 100 percent): ");
numb2 = input.nextDouble();
double getInterestRate = 0;
if (numb2 >= 0 && numb2 <= 100)
getInterestRate = numb2;
else{
System.out.println("Data Error: Interest rate must be greater than or equal to zero and less than or equal to 100. You entered " +numb2);
}
}while (numb2 <= 0 || numb2 >= 100);
return numb2;
}
/** Get term **/
public static double getTerm(double numb1) {
Scanner input = new Scanner(System.in);
double numb2=1;
do{System.out.print("Enter the Term (in months): ");
numb2 = input.nextInt();
double getTerm = 0;
if (numb2 > 0)
getTerm = numb2;
else{
System.out.println("Data Error: Loan amount must be greater than zero. You entered " +numb2);
}
}while (numb2 <= 0);
return numb2;
}
/** Sort by simple interest **/
public static void sortBySimple(double[][] arrPrincipalAmt ,double[][] arrInterestRate, double[][] arrTerm, double[][] arrSimple, double[][] arrCompoundMonthly, double[][] arrCompoundWeekly, double[][] arrCompoundDaily, double count){
for(int i = 0;i<count;i++)
{
for(int j=i+1; j<count;j++)
{
if(arrSimple[i][j] < arrSimple[i][j])
{
double temp = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp;
double temp1 = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = arrPrincipalAmt[i][j];
arrPrincipalAmt[i][j] = temp1;
double temp2 = arrInterestRate[i][j];
arrInterestRate[i][j] = arrInterestRate[i][j];
arrInterestRate[i][j] = temp2;
double temp3 = arrTerm[i][j];
arrTerm[i][j] = arrTerm[i][j];
arrTerm[i][j] = temp3;
double temp4 = arrSimple[i][j];
arrSimple[i][j] = arrSimple[i][j];
arrSimple[i][j] = temp4;
double temp5 = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = arrCompoundMonthly[i][j];
arrCompoundMonthly[i][j] = temp5;
double temp6 = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = arrCompoundDaily[i][j];
arrCompoundDaily[i][j] = temp6;
double temp7 = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = arrCompoundWeekly[i][j];
arrCompoundWeekly[i][j] = temp7;
}
}
}
}
/** Display Interest **/
public static void displayInterest(double[][] amt ,double[][] interest, double[][] term, double[][] simple, double[][] monthly, double[][] weekly, double[][] arrCompoundDaily, int count){
int i=0;
System.out.println("[Line #] [Principal Amount] [Interest Rate] [Term] [Simple Interest] [Compound Monthly] [Compound Weekly] [Compound Daily]");
do{
System.out.print((i+1)+" ");
System.out.print(amt[i][i]+" ");
System.out.print(+interest[i][i]+" ");
System.out.print(+ term[i][i]+" ");
System.out.print(+simple[i][i]+" ");
System.out.print(+monthly[i][i]+" ");
System.out.print(+weekly[i][i]+" ");
System.out.println(+arrCompoundDaily[i][i]);
i++;
}while(i < count);
}
/**ask yes or no **/
public static boolean askYesNo(String question) {
Scanner input = new Scanner(System.in);
String enteredText;
boolean isAnswerValid;
do{
isAnswerValid = false;
System.out.println(question);
enteredText = input.nextLine();
if (enteredText.length() > 0)
{
enteredText = enteredText.toUpperCase();
if(enteredText.equals("YES") || enteredText.equals("Y") || enteredText.equals("NO") || enteredText.equals("N"))
{
isAnswerValid = true;
}
}
if(isAnswerValid == false)
{
System.out.println("Please enter 'Yes' or 'No'?");
}
} while(isAnswerValid == false);
if(enteredText.equals("YES") || enteredText.equals("Y"))
{
return true;
}
return false;
}
}
Your code looks like an attempt to write C in Java. Java is an OO language, and you will have much more success if you design and write your programs in to make use of that. Data structures that are "smeared" across multiple arrays like that are fundamentally awkward to deal with.
The first thing you need to do to remedy this is to create a class that represents an entry in the arrays.
Trying to fix the program while retaining the current "smeared" data structure design is ... to be blunt ... a waste of time.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I have an array thats supposed to be a size of 3 which takes in 3 dive totals. It takes in an array of 7 scores from a double []. I have used a test scenario to see if the diveScore() method works and the calculations are correct. But when i try to read the numbers from a file and put them into an array, the scoreArray that holds the calculated dive score for each dive fails to store the data. The scoreArray in my hard coded test case works fine. Here is the exception from the console when run. I have tried to look at the line where the error states but the test data that I commented out in the main file works fine with the 3 arrays of scores for each dive. What am I missing? Every for loop doesn't have <= in it like many articles have been shown to me by everyone.
Exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3
at Diver.diveScore(Diver.java:33)
at Main.readFile(Main.java:74)
at Main.main(Main.java:10)
Main File:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Diver [] divers = new Diver[25];
int numDivers = readFile(divers);
System.out.println(numDivers);
/*Diver d = new Diver("Frank Stalteri", "Middlesex County College");
double [] scores = {6.2, 3.5, 8, 7.3, 6, 9.1, 4.8};
double [] scores2 = {7.4, 5.4, 8, 3.7, 2.5, 7.8, 4};
double [] scores3 = {4.6, 7.2, 7.3, 1.4, 3.6, 8, 4.7};
d.diveScore(1, scores, 2);
d.diveScore(2, scores2, 4);
d.diveScore(3, scores3, 3);
System.out.println(d.toString());
*/
}
public static int readFile(Diver [] divers) throws FileNotFoundException {
File f = new File("divers.dat");
Scanner kb = new Scanner(f);
Diver d;
int count = 0;
int diveNum = 1;
while (kb.hasNextLine()) {
String name = kb.nextLine();
String school = kb.nextLine();
String dive1 = kb.nextLine();
String dive2 = kb.nextLine();
String dive3 = kb.nextLine();
//String [] of size 8 (inlcudes the difficulty #)
String [] scores1 = dive1.split("\\s+");
String [] scores2 = dive2.split("\\s+");
String [] scores3 = dive3.split("\\s+");
//gets the difficulty from String [] then parses
double diff1 = Double.parseDouble(scores1[scores1.length - 1]);
double diff2 = Double.parseDouble(scores2[scores2.length - 1]);
double diff3 = Double.parseDouble(scores3[scores3.length - 1]);
//make new double [] of size 7
double [] scores1D = new double[scores1.length - 1];
double [] scores2D = new double[scores2.length - 1];
double [] scores3D = new double[scores3.length - 1];
//loops through String [] and casts numbers without difficulty number
for (int i = 0; i < scores1D.length; i++) {
scores1D[i] = Double.parseDouble(scores1[i]);
//System.out.println(scores1D[i]);
}
for (int i = 0; i < scores2D.length; i++) {
scores2D[i] = Double.parseDouble(scores2[i]);
//System.out.println(scores2D[i]);
}
for (int i = 0; i < scores3D.length; i++) {
scores3D[i] = Double.parseDouble(scores3[i]);
//System.out.println(scores3D[i]);
}
d = new Diver(name, school);
divers[count] = d;
count++;
d.diveScore(diveNum, scores1D, diff1);
diveNum++;
d.diveScore(diveNum, scores2D, diff2);
diveNum++;
d.diveScore(diveNum, scores3D, diff3);
//System.out.println(d.toString());
}
kb.close();
return count;
}
public static void printDivers(Diver [] divers, int numDivers) {
System.out.println("All Divers\n");
for (int i = 0; i < divers.length; i++) {
if (divers[i] != null) {
System.out.println(divers[i]);
}
}
}
}
Diver File:
public class Diver {
private String name;
private String school;
private double [] scoreArray = new double [3];
private double totalScore;
Diver() {
}
Diver(String name, String school) {
this.name = name;
this.school = school;
}
//loop through score array and calculate the total score for each dive attempt
public double [] diveScore(int diveNum, double [] scores, double difficulty) {
double min = min(scores);
double max = max(scores);
double total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
total -= max;
total -= min;
total *= difficulty;
scoreArray[diveNum - 1] = Math.round(total * 100.0) / 100.0;
return scoreArray;
}
//finds smallest score in array of scores
private double min(double [] scores) {
java.util.Arrays.parallelSort(scores);
double min = scores[0];
return min;
}
//finds largest score in array of scores
private double max(double [] scores) {
java.util.Arrays.parallelSort(scores);
double max = scores[scores.length - 1];
return max;
}
//calculates total of the 3 dives
public double totalScore() {
for (int i = 0; i < scoreArray.length; i++) {
totalScore += scoreArray[i];
}
return totalScore;
}
public String toString() {
String str = name + ", " + school + ": " + totalScore() + "\n" + "Dive 1: " + scoreArray[0] + "\n" + "Dive 2: " + scoreArray[1] + "\n" + "Dive 3: " + scoreArray[2] + "\n";
return str;
}
public boolean equals(Diver d) {
boolean value = true;
if (d == null || !(d instanceof Diver)) {
value = false;
return value;
}
Diver diver = (Diver) d;
if (this.totalScore == d.totalScore) {
value = true;
return value;
}
return value;
}
}
Your first diver must start at 0
Main > readFile > while loop
int diveNum = 0;
My program is working fine, but when it opens the JOptionPane.showInputDialog to enter a grade the text field for box has a highlighted -1 in it. I'm pretty clueless and searches came up with nothing. Thank you for your time!
import javax.swing.JOptionPane;
public class MeanDeviCalc extends javax.swing.JFrame {
//set array size
private double[] gradeArray = new double[25];
//intialize number of grades
private int GradeTotal = 0;
/**
* Creates new form MeanDeviCalc
*/
public MeanDeviCalc() {
initComponents();
}
//get function for mean
public double getAverage(double[] gradeArray, int numElem) {
//intialize total with 0
double total = 0;
for (int i = 0; i < numElem; i++)
{
//add one for total when grade inputed
total=total+gradeArray[i];
}
//divide for mean
return (total/numElem);
}
//get function for standard deviation
public double getstddev(double[] gradeArray, int numElem, double average) {
//intialize total with 0
double total = 0;
for (int i = 0; i < numElem; i++)
{
//standard deviation
total = total + Math.pow((gradeArray[i] - average), 2);
}
return Math.sqrt(total / numElem);
}
boolean exitloop = false;
do {
String gradeInput = JOptionPane.showInputDialog(
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
// When we receive empty/null input, we're done entering grades
if (gradeInput == null || gradeInput.length() == 0)
exitloop=true;
if(!exitloop){
double gradeValue = 0;
if (GradeTotal == 25) {
// max array size check
JOptionPane.showMessageDialog(this,
"You've already entered the maximum of 25 grades.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
gradeValue = Double.parseDouble(gradeInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this,
"Your input must be numeric!","Bad Data!",JOptionPane.ERROR_MESSAGE);
}
// Put grade in the array update total
gradeArray[GradeTotal] = gradeValue;
GradeTotal++;
// Add to grade total
txtGradeNumber.setText(Integer.toString(GradeTotal));
double gradeAverage = getAverage(gradeArray, GradeTotal);
txtMean.setText(Double.toString(gradeAverage));
double standardDeviation = getstddev(gradeArray, GradeTotal, gradeAverage);
txtStdDev.setText(Double.toString(standardDeviation));}
} while (GradeTotal < 25 && !exitloop) ;
Because you're using public static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue) and JOptionPane.PLAIN_MESSAGE is set to -1 (public static final int PLAIN_MESSAGE = -1;)
I think you meant to use public static String showInputDialog(Component parentComponent, Object message, String title, int messageType)
instead
I have the following piece of code used to calculate Heart Rate from an ECG Signal by detecting the QRS peaks:
public class Heart_Rate {
public static void main(String[] args) throws IOException{
// Read Text file
Path filePath = Paths.get("heartrate.txt");
Scanner scanner = new Scanner(filePath);
List<Double> rawData = new ArrayList<Double>();
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
rawData.add(scanner.nextDouble());
} else {
scanner.next();
}
}
System.out.println(rawData);
//Find Max value for Threshold Level
Double maximum = Collections.max(rawData);
Double threshold = 0.7*maximum;
System.out.println("Maximum = " + maximum);
System.out.println("Threshold = " + threshold);
//Calculate Heart Rate from list "Raw Data"
int upflag = 0;
int last = 1;
int p = 0;
int t = 0;
int count = 0;
//List<Double> heartRate = new ArrayList<Double>();
int heartRate2[] = new int[50];
for (int i = 0; i < rawData.size(); i++) {
if (rawData.get(i)> threshold){
if (upflag == 0){
if (last > 0){
t = i - last;
p = 100*60/t;
//100 is the sampling rate
heartRate2[count] = p;
count = count + 1;
//heartRate.add(p);
}
last = i;
}
upflag = 50;
}
else {
if (upflag > 0){
upflag = upflag -1;
}
}
}
System.out.println("Count = " + count);
System.out.println("Heart Rate = " + heartRate2);
System.out.println("Heart Rate = " + heartRate2);
}
}
When I add the heart rate values calculated(p) to my ArrayList (called HeartRate), I received a proper array of values.
However, I tried to change all my values to int and save my values in an integer array (called heartRate2) I get the following result:
Heart Rate = [I#dd1e765
I need my values to be integers since heart rate is calculated in beats per minute. I also tried converting the double values to int but ended up receiving a similar result as above.
Use Arrays.toString(arr) to get a meaningful String representation for some array arr.
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
I was wondering if the following code returns a sum of all the doubles in a text file. It seems to always appear as 0.0 when I test run it. What could be the problem? I
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
ArrayList <Double> assignments = new ArrayList <Double> ();
double num = test.nextDouble();
assignments.add(num);
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
}
return percentage;
}
You don't need the ArrayList at all, and it's hard to see how a percentage can be equal to a sum, or where your variables are being initialized:
public double honorsCalculation() throws IOException {
double sum = 0;
Scanner test = new Scanner(new File("Calculus - Test.txt"));
while (test.hasNext()) {
sum += test.nextDouble();
}
return sum;
}
You are treating the information before reading all the data.
public double honorsCalculation() throws IOException {
Scanner test = new Scanner(new File("Calculus - Test.txt"));
ArrayList <Double> assignments = new ArrayList <Double> ();
while (test.hasNext()) {
double num = test.nextDouble();
assignments.add(num);
}
for (int i = 1; i < assignments.size() - 1; i++) {
sum = sum + assignments.get(i);
percentage = sum;
}
return percentage;
}
This should be the correct approach.