Code for adding doubles within a text file? Java - java

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.

Related

Array Index Out Of Bounds Java [duplicate]

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;

Find mean median mode from text file java

I have a text file called numbers.txt and its full of numbers. I need to find the mean median and mode of the numbers. I can read the file but I don't know any more than that.
import java.io.File;
import java.util.Scanner;
public class Terms {
public static void main(String[] args)throws Exception {
File file =
new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
According to the definitions of mean, median and mode:
public static void main(String[] args) {
File file = new File("C:\\Users\\coderva.org\\Documents\\numbers.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
return;
}
ArrayList<Float> list = new ArrayList<Float>();
while (sc.hasNextFloat())
list.add(sc.nextFloat());
int size = list.size();
if (size == 0) {
System.out.println("Empty list");
return;
}
Collections.sort(list);
for (int i = 0; i < size; i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
// mean value, classical way
float sum = 0;
for (float x : list) {
sum += x;
}
float mean = sum / size; // mean as integer
//median
float median;
if (size % 2 == 0) {
float x1 = list.get(size / 2 - 1);
float x2 = list.get(size / 2);
median = (x1 + x2) / 2;
} else {
median = list.get(size / 2);
}
//mode
Float mode = null;
int counter = 1;
for (int i = 0; i < size; i++) {
int freq = Collections.frequency(list, list.get(i));
if (freq > counter) {
mode = list.get(i);
counter = freq;
}
}
System.out.println("Mean=" + mean);
System.out.println("Median=" + median);
if (mode == null) {
System.out.println("No mode found");
} else {
System.out.println("Mode=" + mode);
}
}
You can create a list of numbers as such:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt())
numberList.add(sc.nextInt());
Or when you have doubles or floats:
List<Double> numberList = new ArrayList<>();
while (sc.hasNextDouble())
numberList.add(sc.nextDouble());
List<Float> numberList = new ArrayList<>();
while (sc.hasNextFloat())
numberList.add(sc.nextFloat());
From there you can calculate the mean as follows:
sum = numberList.stream().mapToInt(Integer::intValue).sum();
average = sum / numberList.size();
And so on for the other properties you need.
Note The types are of sum and average are depended on which types you read from the file.

Read data from file, write result into a new file(java)

I need to read some txt file, get data from it, find out average numbers and then write them into another file. I've done pretty much everything , but can not write needed values in a new file.
public static double KronKesk(double a, double b, double c){
return (a/2+b+c/2)/2;
}
public static double KronKesk2(double[] b){
int jag = 0;
double sum = 0;
for (int i = 0; i < b.length; i++) {
jag++;
}
jag = jag - 1;
sum = ArraySum(b) - b[0] - b[b.length-1];
return (b[0]/2 + sum +b[b.length-1]/2)/jag;
}
public static double ArraySum(double[] a){
double sum = 0;
for (int i = 0; i < a.length; i++) {
sum = sum+a[i];
}
return sum;
}
public static void main(String[] args) {
try{
String filePath = "C:\\Users\\user\\Desktop\\TLU\\Semester 2\\ProgPohikursus\\temp";
BufferedReader br = new BufferedReader(new FileReader(filePath + ".txt"));
String rida;
List<Andmed> andmed = new ArrayList<>();
int ridaCount = 0;
while((rida = br.readLine()) != null){
String[] temp = rida.split(",");
Andmed andmed0 = new Andmed();
andmed0.setKuupaev(Double.valueOf(temp[0]));
andmed0.setTemp0(Double.valueOf(temp[1]));
andmed0.setTemp6(Double.valueOf(temp[2]));
andmed0.setTemp12(Double.valueOf(temp[3]));
andmed0.setTemp18(Double.valueOf(temp[4]));
andmed0.setTemp24(Double.valueOf(temp[5]));
andmed.add(andmed0);
ridaCount++;
}
System.out.println(andmed);
br.close();
File fout = new File(filePath + "_avgtemp" + ".txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Andmed andmed0 = new Andmed();
for (int i = 0; i < ridaCount; i++) {
double[] andmed1 = {andmed0.getTemp0(), andmed0.getTemp6(), andmed0.getTemp12(), andmed0.getTemp18(), andmed0.getTemp24()};
double[] andmedFaili = {andmed0.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
bw.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
and another file with getters and setters:
public class Andmed {
private double k;
private double t0;
private double t6;
private double t12;
private double t18;
private double t24;
/*protected static List<Double> allTemp = new ArrayList<Double>();
public double tempListi(double t0, double t6, double t12, double t18, double t24){
allTemp.add(t0);
allTemp.add(t6);
allTemp.add(t12);
allTemp.add(t18);
allTemp.add(t24);
return 0;
}*/
public void setKuupaev(double k){
this.k = k;
}
public void setTemp0(double t0){
this.t0 = t0;
}
public void setTemp6(double t6){
this.t6 = t6;
}
public void setTemp12(double t12){
this.t12 = t12;
}
public void setTemp18(double t18){
this.t18 = t18;
}
public void setTemp24(double t24){
this.t24 = t24;
}
public double getKuupaev(){
return k;
}
public double getTemp0(){
return t0;
}
public double getTemp6(){
return t6;
}
public double getTemp12(){
return t12;
}
public double getTemp18(){
return t18;
}
public double getTemp24(){
return t24;
}
}
What I have in a first file is:
12.01,3,4,5,6,7,8
13.01,4,5,5,4,3,6
...
what i need to get into a new file:
12.01, chronological average of 6 previous numbers
what do I get for now is:
[0.0, 0.0]
[0.0, 0.0]
[0.0, 0.0]
Where is the mistake? :/
Thank You in advance!
In your for loop you are not using your list at all, but an empty andmed0 variable that you declared just before the loop.
Get rid of that variable and use the actual list :
// Andmed andmed0 = new Andmed(); // no need for that
for (int i = 0; i < ridaCount; i++) {
Andmed currentAndmed = andmed.get(i);
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}
Also note that you don't have to use a ridaCount variable to compute the size of the list, just call andmed.size() instead .
i.e :
for (int i = 0; i < andmed.size(); i++)
Finally as stated in the comments by #gilfernandes, you may simply use a foreach loop :
for(Andmed currentAndmed : andmed) {
double[] andmed1 = {currentAndmed.getTemp0(), currentAndmed.getTemp6(), currentAndmed.getTemp12(), currentAndmed.getTemp18(), currentAndmed.getTemp24()};
double[] andmedFaili = {currentAndmed.getKuupaev(), KronKesk2(andmed1)};
bw.write(Arrays.toString(andmedFaili) + "\n");
}

Get an average from number of objects

I'm trying to get the average score from objects but can't think of a good way to do it.
I have 10 objects and they all have their own score associated with it.
I created setter and getter class where it would get the average, but the problem I run into is that I would create something like this so that even if I do put object's score into this method the holder will go back to 0.
public double getAverage() {
return average;
}
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
I was also thinking of just creating setter and getter methods for every single score, but that takes up lots of space and I figured there has to be a better way to do it.
Here is a snippet of the code I'm using in the main method
public static void main(String[] args) {
final String STUDENT_INFO = "HW1_Students.txt";
List<GradeInfo> list = new ArrayList<GradeInfo>();
Scanner inputFile = null;
GradeInfo person1 = new GradeInfo();
GradeInfo person2 = new GradeInfo();
GradeInfo person3 = new GradeInfo();
GradeInfo person4 = new GradeInfo();
GradeInfo person5 = new GradeInfo();
GradeInfo person6 = new GradeInfo();
GradeInfo person7 = new GradeInfo();
GradeInfo person8 = new GradeInfo();
GradeInfo person9 = new GradeInfo();
GradeInfo person10 = new GradeInfo();
list.add(person1);
list.add(person2);
list.add(person3);
list.add(person4);
list.add(person5);
list.add(person6);
list.add(person7);
list.add(person8);
list.add(person9);
list.add(person10);
try {
inputFile = new Scanner(new File(STUDENT_INFO));
}
catch (FileNotFoundException ex) {
System.out.println("\n *** Exception occured while opening "
+ ex.getMessage() + " ***");
System.exit(-1);
}
readData(inputFile, STUDENT_INFO, person1, person2, person3, person4,
person5, person6, person7, person8, person9, person10);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
Any advice would be greatly appreciated, thanks.
public void setAverage(ArrayList<GradeInfo> grades) {
double average = 0;
for(int i = 0; i < grades.size(); i++){
average += grades.get(i);
}
average = average / grades.size();
this.average = average;
}
I hope this is what you meant to do....... This method will take your Arraylist, and set the correct average score in your wired "setter and getter class".
I dont really understand what you are trying to do here:
public void setAverage(double studentScore) {
double holder = 0;
average = holder + studentScore;
holder = average;
this.average = studentScore;
}
But its logical that holder will be reset to 0 because you initialize it and set it to 0 in the beginnig of your function, or do i misunderstand this?
Just create holder outside of your setter.
And if you just want to have the average of a bunch of values just add all the values together and divide the result by the number/quantity of your values.
For example:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
double average = totalAmount / l.size();
return average;
}
This is probably not applicable to your program insofar as you probably have at least one positive value going into your calculation. But I could see a professor taking off points for it if he is testing all possible cases.
If you do follow the advice of Sand, be sure to check that the size of the arraylist is greater than zero before you use the size in the average calculation. You cannot divide by zero in Java. Instead, do this:
public double getAverage(List <GradeInfo> l){
int totalAmount;
for(i = 0; i < l.size(); i++){
totalAmount += l.get(i);
}
if (l.size() > 0) {
double average = totalAmount / l.size();
return average;
else {
double average = 0;
}
return average;
}

converting single dimensional array into multidimensional array

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.

Categories

Resources