简体   繁体   中英

why is my program asking for output twice

 Scanner sam = new Scanner(System.in);
public class balance {
public double[] returnarray1() {
    System.out.print("Enter account balances seperated by coma:");
    String[] temp = sam.nextLine().split(",");
    double[] bal = new double[temp.length];
    for(int i=0; i<temp.length; i++) {
        bal[i] = Double.parseDouble(temp[i]);
    }
    return bal;
}

}
public class interest {
    public double[] returnarray2() {
    balance bl = new balance();
    double[] temp = bl.returnarray1();
    double[] inter = new double[temp.length];
    for(int i=0;i>temp.length;i++) {
        inter[i] = temp[i] * 0.02/12;
        
    }
     return inter;
    
    
}
}

public static void main(String[] args) {
    samiksood ss = new samiksood();
    balance bl = ss.new balance();
    interest it = ss.new interest();
    double[] balance = bl.returnarray1();
    double[] interest = it.returnarray2();
    for(int i =0; i<balance.length;i++) {
    System.out.print("Account "+ i +1);
    System.out.print(balance[i]);
    System.out.println(interest[i]);
    }
    
}

when i run it it asks me for output twice which should not happen why is my class repeating? this program is supposed to seperate a single output into multiple different ones and be placed into a array which is then converted to double the balance is then returned. similarly interest is calculated by preforming calculations on each balance array and returned.they are called into the main method and each array is supposed to be printed.

You both call returnarray1 in your main and inside returnarray2 so that's why returnarray1 is executed twice.

Assuming you want to use the result of the first time in the second time you can change

public double[] returnarray2() {
    balance bl = new balance();
    double[] temp = bl.returnarray1();
    double[] inter = new double[temp.length];
    for (int i = 0; i > temp.length; i++) {
        inter[i] = temp[i] * 0.02 / 12;
    }
    return inter;
}

to

public double[] returnarray2(double[] temp) {
    balance bl = new balance();
    double[] inter = new double[temp.length];
    for (int i = 0; i > temp.length; i++) {
        inter[i] = temp[i] * 0.02 / 12;
    }
    return inter;
}

and

double[] interest = it.returnarray2();

to

double[] interest = it.returnarray2(balance);

I believe there is also a small bug at this line

for (int i = 0; i > temp.length; i++) {

because it needs to be

for (int i = 0; i < temp.length; i++) {

There's a lot more room for improvement, because a lot of your code is not according to conventions, but it should work at least.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM