返回循环中每次迭代的结果

时间:2017-08-04 11:50:42

标签: java loops getter-setter getter

我正在做一些能产生正确结果的事情。但是,设计POV是错误的。

该计划的目的是列出一个数字的所有权力的结果,包括用户定义的限制。

我有一个构造函数,它接受来自Scanner的base和exponent。然后是一个方法,它利用for循环计算每个指数的功率。

现在,问题是我直接从这个方法打印每个循环迭代的结果。这超过了私有变量的点,它在第一位是无效的。

因此,我想定义一个getter方法,它将每个幂的结果返回给输出。我过去常常为if / switch语句设置它们,但我不知道如何为循环做同样的事情。如果我将结果分配给循环中的变量并从getter返回该变量,那么它将仅返回最终迭代的输出。

私人执行

package Chapter6Review;

public class Powers {

private int target;
private int power;


public Powers(int target, int power) {
    this.target = target;
    this.power = power;
}

public void calculatePower() {
    for (int i = 0; i <= power; i++) {
        System.out.println((int) Math.pow(target, i)); 
    }
}

/*
public int getPower() {
    return 
}
*/
}

用户界面

package Chapter6Review;

import java.util.Scanner;

public class PowersTester {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Enter your base: ");
    int target = in.nextInt();
    System.out.print("Enter your exponent: ");
    int power = in.nextInt();

    Powers tester = new Powers(target, power);
    tester.calculatePower();

}
}

4 个答案:

答案 0 :(得分:1)

You can simply use a List ;

public List<Integer> calculatePower() {

    int p;
    List<Integer> result = new ArrayList<Integer>();
    for (int i = 0; i <= power; i++) {
        p = (int) Math.pow(target, i); 
        result.add(p);
    }
    return result;
}

Then in you main method, you can iterate the list to print the powers like that :

List<Integer> result = new ArrayList<Integer>();
Powers tester = new Powers(target, power);
result = tester.calculatePower();

for (int i = 0; i < result.size(); i++) {
     System.out.println(result.get(i));
}

答案 1 :(得分:0)

You could store each of the results in a List:

List<Power> list = new ArrayList<>();

and when you call it add it as well

list.add(new Powers(target, power));

At the end you can iterate over the list like this:

for (Power power : list){
// your code
}

答案 2 :(得分:0)

You might consider using streams as well

public List<Integer> calculatePower() {
    return IntStream
            .rangeClosed(0, power). // iterate from 0 till power inclusive
            .mapToObj(i -> (int) Math.pow(target,i)) 
            .collect(Collectors.toList()); // get result as list
}

答案 3 :(得分:0)

Thanks for all the answers. Using a list seems to be a good choice. Since I haven't covered lists yet, I resorted to this solution for now. But I don't like having code that can affect the solution in the main. Ideally, the loop should go in the private implementation.

Main

    Powers tester = new Powers(target, power);

    for (int i = 0; i <= power; i++) {
        tester.calculatePower(i);
        System.out.println(tester.getPower());
    }

Private implementation

public void calculatePower(int iPower) {
    result = (int) Math.pow(target, iPower);
}

public int getPower() {
    return result;
}