整个包的java变量

时间:2017-02-03 04:06:57

标签: java

我是Java的新手,我不知道如何使它在if语句中的这两个变量,每次都需要更新。

public class Ex3 {

public static void main(String[] args) {
    //Here will display what pi is
    System.out.println("Pi in Netbeans Java is "+ Math.PI);

    //This will give how many numbers the for loops go up to
    int maxNum = 20;

    //This is for the subtraction parts of the equation
    for(int i = 1; i <= maxNum; i++){
        int subNum = 3;
        final double subCount = 1 - (1./(subNum + 4));
        subNum += 4;
    }
    for(int y = 1; y <= maxNum; y++){
        int addNum = 5;
        double addCount = 1 + (1./(addNum + 4));
        addNum += 4;
    }
}
double finalNum = subCount + addCount;
}

1 个答案:

答案 0 :(得分:0)

变量仅限于声明的范围,因此如果在for块中声明变量,则只能在for块中看到它们。

要克服此问题,请在main方法

中使用之前声明变量
public static void main(String[] args) {
  //Here will display what pi is
  System.out.println("Pi in Netbeans Java is "+ Math.PI);

  //This will give how many numbers the for loops go up to
  int maxNum = 20;
  double subCount = 0.0;
  double addCount = 0.0;
  int subNum = 3;
  int addNum = 5;

//This is for the subtraction parts of the equation
  for(int i = 1; i <= maxNum; i++){
    subCount = 1 - (1./(subNum + 4));
    // maybe should be
    // subCount += 1 - (1./(subNum + 4));
    subNum += 4;
  }
  for(int y = 1; y <= maxNum; y++){
    addCount = 1 + (1./(addNum + 4));
    // maybe should be
    // addCount += 1 + (1./(addNum + 4));
    addNum += 4;
  }

  System.out.println ("the result is " + (subCount + addCount));
}

修改

不确定你的逻辑应该做什么