我是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;
}
答案 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));
}
修改强>
不确定你的逻辑应该做什么