Java int 不更新。它重置

标签 java int

import java.util.Scanner;

public class test {

    public static void main(String args[]){

        int a = 1000;
        while(a>0){

            System.out.println("Question to prevent infinite while loop");

            Scanner input = new Scanner (System.in);

            int inzet = input.nextInt();

            System.out.println(a);
            test(a);

         }  


    }

    public static void test(int a){


        System.out.println(a);
        a = a + 100;
        System.out.println(a);



        }
    }

我有一个问题。为什么int a不更新?每次都会重置为1000。我不想那样。有人可以帮帮我吗?如果我运行该程序,我会得到以下结果:

Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1000
1000
1100

我想获取此代码:

Question to prevent infinite while loop
2
1000
1000
1100
Question to prevent infinite while loop
2
1100
1100
1200
Question to prevent infinite while loop
2
1200
1200
1300

此外,这是我的第一篇文章。请给我一些反馈,告诉我下次如何更好地提出问题。

最佳答案

您的更新值仅在您的 test 方法中可见。您可以将 a 设为字段并结合删除当前声明(在 main 方法以及 test 参数中):

import java.util.Scanner;

public class test {

  private static int a = 1000;

  public static void main(String args[]) {

    while (a > 0) {
      System.out.println("Question to prevent infinite while loop");

      Scanner input = new Scanner(System.in);

      int inzet = input.nextInt();

      System.out.println(a);
      test();
    }
  }

  public static void test() {
    System.out.println(a);
    a = a + 100;
    System.out.println(a);
  }
}

或者您可以从方法中返回更新后的值,并将返回值分配给 a:

import java.util.Scanner;

public class test {

  public static void main(String args[]) {

    int a = 1000;
    while (a > 0) {
      System.out.println("Question to prevent infinite while loop");

      Scanner input = new Scanner(System.in);

      int inzet = input.nextInt();

      System.out.println(a);
      a = test(a);
    }
  }

  public static int test(int a) {
    System.out.println(a);
    a = a + 100;
    System.out.println(a);
    return a;
  }
}

关于Java int 不更新。它重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798072/

相关文章:

java - 如何在 Java Web 应用程序中显示 jFrame 表单 (NetBeans)

java - 如何在 Android 中以编程方式创建的水平 ScrollView 和 XML 创建的布局?

java - 从我的书中复制了这个确切的代码,但不起作用

python - 如何打印显示 4 位小数的整数?

c++ - 如何在 C++ 中创建带指针的 3 维 int?

java - 随机 com.android.volley.NoConnection 错误,java.io.InterruptedIOException,statuscode=0

java - Hadoop 方法 Counter.getName 和 Counter.getDisplayName 之间的区别

c++ - C++中的 float 到整数的转换

C:同时从管道 char 和 int 读取(棘手的一个)

c# - int (Int32) 是否被视为 .NET 中的对象或原语(不是 int?)?