Java 我用加法得到相同的数?
我在一个银行账户项目上练习,我遇到了这个小问题 我把它作为一种更容易理解的方法 主要方法Java 我用加法得到相同的数?,java,addition,Java,Addition,我在一个银行账户项目上练习,我遇到了这个小问题 我把它作为一种更容易理解的方法 主要方法 public static void main(String[] args) { Scanner in=new Scanner(System.in); double b=0; while(b!=-1){ b=in.nextInt(); ddd(b); } } 加法 public static void Addition(double b){
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
double b=0;
while(b!=-1){
b=in.nextInt();
ddd(b);
}
}
加法
public static void Addition(double b){
double g=0;
g+=b;
System.out.println( "GGGGGGGG"+ g );
}
问题是每次输入的输入都是一样的。
我从一开始就知道这个问题
double g=0;
因为每次我调用方法addition
g
都会因为这个语句double g=0而被初始化为零代码>,但我应该先初始化它,否则会出现编译错误
我应该如何解决此问题 在while语句之前初始化它 在while语句之前初始化它 您可以通过在方法之外声明双g来将其作为类的成员。下面是一个示例类
class TestClass {
static double g = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double b = 0;
while (b != -1) {
b = scan.nextDouble() //you need to change nextInt() to nextDouble()
add(b);
}
System.out.println(g);
}
public static void add(double b) {
g += b; //g refers to the variable about the main method
}
}
这可能并不完全是类的工作方式,但是在方法外部使用变量g可以确保即使在方法结束时类仍保留其值。希望这有帮助 您可以通过在方法之外声明双g来将其作为类的成员。下面是一个示例类
class TestClass {
static double g = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double b = 0;
while (b != -1) {
b = scan.nextDouble() //you need to change nextInt() to nextDouble()
add(b);
}
System.out.println(g);
}
public static void add(double b) {
g += b; //g refers to the variable about the main method
}
}
这可能并不完全是类的工作方式,但是在方法外部使用变量g可以确保即使在方法结束时类仍保留其值。希望这有帮助 将g
设置为一个字段。局部变量只在方法调用的生命周期内存在。非常感谢我修复了它。将g
设置为一个字段。局部变量只在方法调用的生命周期内存在。非常感谢我修复了它。我非常感谢你的回答。非常感谢。没问题,如果您继续编码,您以后肯定需要知道这一点:)我非常感谢您的回答。非常感谢。没问题,如果您继续编码,您以后肯定需要知道这一点:)