每当我在java中调用函数时,将数字增加1

每当我在java中调用函数时,将数字增加1,java,Java,每当我调用函数时,我都试图打印数字增量1,但我无法得到解决方案,下面是我的代码 打击就是功能 public class Functions<var> { int i=0; public int value() { i++; return i; } } 每当我运行程序时,我只得到1的输出,但我希望输出增加1。你能帮忙吗。提前谢谢。我相信你的答案取决于你的变量范围和你对它们的理解。在给定的示例中,您只调用该方法一次

每当我调用函数时,我都试图打印数字增量1,但我无法得到解决方案,下面是我的代码

打击就是功能

public class Functions<var> {

    int i=0;

    public int value()
    {

        i++;
        return i;

    }
}

每当我运行程序时,我只得到1的输出,但我希望输出增加1。你能帮忙吗。提前谢谢。

我相信你的答案取决于你的变量范围和你对它们的理解。在给定的示例中,您只调用该方法一次,因此1可以说是正确的答案。下面是一个工作示例,它将在运行时保持一个变量,并在每次调用函数时递增该变量。您的方法似乎没有遵循常见的Java模式,因此我建议您查找一些小示例Hello,World代码片段

public class Example{
 int persistedValue = 0; // Defined outside the scope of the method
 public int increment(){
  persistedValue++; // Increment the value by 1
  return persistedValue; // Return the value of which you currently hold
  // return persistedValue++;
 }
}
这是由于“persistedValue”的范围。它存在于类“Example”中,只要您持有“Example”的实例,它就会持有一个与递增值相对应的真值

测试依据如下:

public class TestBases {
 static Example e; // Define the custom made class "Example"
 public static void main(String[] args) {
  e = new Example(); // Initialize "Example" with an instance of said class
  System.out.println(e.increment()); // 1
  System.out.println(e.increment()); // 2
  System.out.println(e.increment()); // 3
 }
}

如果您不希望在运行时持久化(应用程序运行之间持久化的值),那么最好研究一些文件系统保存方法(特别是在您的Java实践中!)

您的主要问题是将数值1递增

但您只调用了一次函数。即使多次调用该函数,也只会得到值1,因为它不是静态变量,所以每次都会初始化为0。 所以请使用静态上下文检查下面的答案

Functions.java

public class Functions{

    static int i=0;   
    public int value()
    {
        i++;
        return i;
    }
}
Increment.java

public class Increment{

    public static void main(String []args){

        Functions EF = new Functions();

        System.out.println(EF.value());    
        System.out.println(EF.value());    
        System.out.println(EF.value());    
    }
}
输出:

一,

二,


3

如果设计多线程应用程序,最好使用AtomicInteger。 AtomicInteger类为您提供了一个可以原子地读写的int变量

AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet(); 

您是否尝试过返回i++;您只调用一次方法,那么它怎么可能大于1呢?您是否希望您的程序在执行之间保持状态。。。如果是,怎么做?这是因为每次运行时都会创建一个新对象。该对象值始终为0,并递增为1。退出main方法后,程序终止。如果您想让计数器覆盖应用程序的调用,则需要保留该值并在启动时读取它。复制此行,这样就有两行:
System.out.println(EF.value())然后您将看到调用之间的增量。嗨,Dawson,这里您对System.out.println(e.increment());,使用了三次;,应该只有一个System.out.println(e.increment());每次调用该函数时,我的输出都应该递增1。e.increment()正在调用该函数。system.out.println的存在纯粹是为了向您展示流程中的每个步骤。正如我在文章中解释的,您的代码是正确的,您对它应该如何工作的理解是问题所在。要么是这样,要么是你没有正确解释你的问题。由于我的声誉得分,我目前还不能对其他人的帖子发表评论——但我想指出的是,仅仅静止一个变量并忘掉它绝对不是一个好主意。也许在你的情况下,但如果你学习,那么这对你的教育是有害的,一点帮助都没有。明白吗?您是否需要任何澄清?在您的代码中,将变量设置为静态变量时,下面的代码是System.out.println(EF.value())的三倍;System.out.println(EF.value());System.out.println(EF.value());但是在我的代码中,我应该只有一次,并且输出应该打印递增的值。你能帮个忙吗?如果你打过一次电话,你怎么能得到最新的代码。那就是我们打了三次电话。
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();