【问题标题】:How to make a variable increment on every running of a method?如何在每次运行方法时使变量递增?
【发布时间】:2023-04-09 16:25:01
【问题描述】:

我试图让 int 计数在每次运行程序时递增。即:因此,如果我运行程序 9 次,并且调用了 9 次 doMethod,则 count 的值将是 9。但是由于我必须将 count 初始化为 = 0,因此 count 在该方​​法的每次迭代中都会将自身重置为 0。有没有办法解决这个问题?

public class Test {

    public static void main (String[] args) {

        Test test1 = new Test();

        test1.doMethod();

    }

    public void doMethod ()  {

        int count = 0;

        count++;
        System.out.println(count);
    }
}

【问题讨论】:

  • 我试图让 int 计数在每次 我运行程序时递增。您确定还是希望计数在只执行main方法???
  • 你不能每次使用i时都使用++i吗?
  • 你的标题和你问题的内容不匹配。每次运行方法每次运行程序都不一样>.
  • 如果我们忽略标题问题就很清楚了...!
  • 对不起,伙计们,这个问题经过深思熟虑。我的意思是每次我“运行程序”因为我正在做的是将数据放在文本文件中并运行程序以导入该数据。所以当我运行 main() 方法时,int count 似乎总是重置为 0。事实上,如果我第 34 次运行这个程序,我需要 count 为 34。所以我相信即使我将'int count = 0'设为实例变量,它也会被覆盖。但是我认为 gkbStar 的优秀代码将有助于解决我的问题。谢谢

标签: java variables


【解决方案1】:

不要将其作为本地方法,而是将其作为实例成员。

int count = 0;
-----
public void doMethod() {
    count++;
    System.out.println(count);
}

这样它就不会在每次调用doMethod() 时重置为0

【讨论】:

    【解决方案2】:

    如果你想在每次运行程序时增加计数,

    • 您必须将您的counter 变量计数存储到文件或数据库表中
    • 所以每次执行开始时从存储中获取值-初始化计数-在方法中递增和打印存储到方法完成后存储
    • 如果您这样做,变量 count 将在程序每次运行时初始化为新值。

    【讨论】:

    • But since I have to initialize count to = 0 count keeps resetting itself to 0 on every iteration of the method. 如果我理解正确的话,这里没有保存值的线索。
    • @sᴜʀᴇsʜᴀᴛᴛᴀ - 我不知道 OP 是要求重新运行程序还是只是方法
    • 你应该将count的存储值读入变量count并增加它............不要在你的代码中将它初始化为零......
    • @sureshatta- 你是在运行程序 9 次......还是调用 doMethod 9 次......这两件事是不同的...... ..!
    • @Jaitheradevi 根据标题How to make a variable increment on every running of a method? b.好的让我们取消并等待OP的响应。
    【解决方案3】:

    因为您想知道您的程序执行了多少次,包括当前执行。因此,为此,您需要将计数写入文件,或者您需要创建一个注册表,您可以在其中放置计数器并增加程序通过程序执行的所有时间:

    以下是将执行计数器存储到文本文件的示例。

    class Test {
        public static void main(String[] args) {
    
            Test test1 = new Test();
    
            test1.doMethod();
    
        }
    
        public int getCount() {
    
            int count = 0;
            try {
                if ( !new File("d:\\myCount.txt").exists())
                    return 1;
                else {
                    BufferedReader br = new BufferedReader(new FileReader(new File("d:\\myCount.txt")));
                    String s = br.readLine();
                    count = Integer.parseInt(s);
                    br.close();
                }                
            } catch(Exception e) {
                e.printStackTrace();
            }
            return count;
        }
    
        public void putCount(int count) {
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(new File("d:\\myCount.txt")));
                bw.write(Integer.toString(count));
                bw.close();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
        public void doMethod() { 
            int count = getCount();            
            System.out.println("You are running this program " + count + " number of times");
            count++;
            putCount(count);            
        }
    }
    

    【讨论】:

    • 那是一段出色的代码,我将保存以供将来参考谢谢。
    【解决方案4】:
    public class Arguments {
    
       private static int i = 1;
    
       //   Arguments() {
       //       System.out.println("Main method thread constructor incremented for "+ i++ + " time" +"\n");
       //   }
    
       public static void main(String[] args) {
            new Arguments().method();
            new Arguments().method();
            new Arguments().method();
            new Arguments().method();
            new Arguments().method();
            new Arguments().method();
       }
    
       private void method() {
           System.out.println("Main method value incremented for "+ i++ + " time" +"\n");
       }
    }
    

    【讨论】:

      【解决方案5】:

      使用该方法定义您的计数变量:

      public class Test {
          int count = 0;
          public static void main(String[] args) {
              Test test1 = new Test();
      
              test1.doMethod();
      
          }
      
          public void doMethod() {
      
              count++;
              System.out.println(count);
          }
      }
      

      【讨论】:

        【解决方案6】:

        如果您在方法之外声明变量,则会记住状态。

        解决方案可能是:

        public class Test {
        
            int count = 0;
        
            public static void main(String[] args) {
                Test test1 = new Test();
                test1.doMethod();
                test1.doMethod();
                test1.doMethod();
            }
        
            public void doMethod ()  {
                count++;
                System.out.println(count);
            }
        }
        

        这样count 会在您调用new Test() 的那一刻被创建,并且会被记住直到对象被销毁。变量有一个叫做“范围”的东西。它们只能在其范围内访问,并且仅存在于该范围内。因为您在 void doMethod() 方法中创建了 count,所以它在其他任何地方都不存在。查看范围的一种简单方法是查看括号{ },您的变量仅存储在这些括号内。在我的解决方案中,count 的括号是整个 Test 类的括号。因此,变量会一直存储到 Object 被销毁。

        关于范围的更多信息:http://en.wikipedia.org/wiki/Scope_(computer_science)

        我刚刚注意到您提到您希望在运行程序后保留 count 值。您可以通过将其保存在数据库或文件中来执行此操作。但是,您可能的意思是希望在运行 void doMethod() 方法后保留 count 值。我已经编辑了我的解决方案以执行 void doMethod() 方法 3 次,因此您会看到运行该方法后该值实际上仍然存在。

        【讨论】:

          【解决方案7】:

          instance 级别或 class 级别声明 int count = 0;

          public void doMethod() {
              int count = 0; // a new count variable is created each time doMethod() is called
              count++;
              System.out.println(count);
          }
          

          【讨论】:

          • @user3804738 - 实际上我不认为 有你的问题.. :P
          【解决方案8】:

          你可以声明static变量count

          count 将成为类的一部分,而不是任何单个对象的一部分。

          现在您只需要在每个方法调用中增加一个计数变量:

          public class Test {
                // Set count to zero initially.
              static int count = 0;
          
              public static void main (String[] args) {
          
                  Test test1 = new Test();
          
                  test1.doMethod();
          
              }
          
              public void doMethod ()  {
                  // Every time the method calls, increment count.
                  count++;
                  System.out.println(count);
              }
          }
          

          更新:

          您也可以在每次调用后而不是在 doMethod () 内打印计数

          您可以将static方法定义为类的一部分,以便在方法调用后获取静态变量count的值:

          class Test
          {   
              // Set count to zero initially.
              static int count = 0;
          
               public void doMethod ()  {
                  // Every time the method calls, increment count.
                  count++;
              }
          
              static int getCount(){
                  // get latest value of count after method calls
                  return count;
              }
          
              public static void main (String[] args) throws java.lang.Exception
                  {
                       Test test1 = new Test();
          
                       test1.doMethod();
          
                       test1.doMethod();
          
                       test1.doMethod();
          
                       System.out.println(Test.getCount());
                  }
          }
          

          【讨论】:

            【解决方案9】:
            public static int count;
            
            public int get(){
            count=count+1;
            return count;
            }
            

            【讨论】:

              【解决方案10】:

              这是每次运行程序时如何增加文件值的不同版本。

              public class FileCount {
                  int count=0;
              
                  public int ScanForValue() throws IOException {
                      if(! new File("C:\\Users\\name\\Desktop\\file.txt").exists())
                          return 0;
                      else{
                          FileReader fr = new FileReader("C:\\Users\\name\\Desktop\\file.txt");
                          Scanner scanFile = new Scanner(fr);
                          String n =scanFile.nextLine();
                          count = Integer.parseInt(n);
                          scanFile.close();
                      }
                      return count;
                  }
              
                  public void increment() throws IOException {
                      int newValue = ScanForValue();
                      newValue++;
                      System.out.println("counts: "+newValue);
                      writeIntoFile(newValue);
                  }
              
                  public void writeIntoFile(int countNumber) throws IOException {
                      FileWriter fw = new FileWriter("C:\\Users\\name\\Desktop\\file.txt");
                      String fin = String.valueOf(countNumber);
                      fw.write(fin);
                      fw.close();
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 2019-01-24
                • 1970-01-01
                • 2021-01-03
                • 1970-01-01
                • 1970-01-01
                • 2020-03-20
                • 1970-01-01
                • 2017-10-09
                • 1970-01-01
                相关资源
                最近更新 更多