【问题标题】:Adding a counter in java在java中添加一个计数器
【发布时间】:2014-09-22 21:08:09
【问题描述】:

我正在开发一个简单的 Hanio 塔 java 程序。 我有它为我提供了用户输入磁盘数量的所有步骤。

但是现在我被困住了,我想在最后放置一个计数器,以便为用户提供明确的步数,而不是让他们全部计数

这是我的代码,如果你能帮助我,

添加一个很棒的计数。

任何帮助都会很棒

import java.util.Scanner;

public class Hanoi{

    public static void Han(int m, char a, char b, char c){
        if(m>0){
            Han(m-1,a,c,b);
            System.out.println("Move disc from "+a+" to "+b);
            Han(m-1,b,a,c);
        }
    }

    public static void main(String[]args){
        Scanner h = new Scanner(System.in);
        System.out.println("How many discs : ");
        int n = h.nextInt();
        Han(n, 'A', 'B', 'C');
    }
}

【问题讨论】:

  • 你可以做一个static int counter = 0; 并且每当你在Han(...) 中做System.out.println("Move disc from "+a+" to "+b); 时,你可以在下面添加counter++;
  • @Compass 你能告诉我你会把它放在我上面的代码中的什么地方吗,我花了一段时间才让它工作宁愿不再破坏它
  • Counter for Towers Of Hanoi 的可能重复项

标签: java class count towers-of-hanoi


【解决方案1】:

简单的方法是使用这样的静态变量:

导入 java.util.Scanner;

public class Hanoi{

static int stepsCounter = 0; // new Code here.

public static void Han(int m, char a, char b, char c){
if(m>0){
stepsCounter++; // new Code here.
Han(m-1,a,c,b);
System.out.println("Move disc from "+a+" to "+b);
Han(m-1,b,a,c);
}
}

public static void main(String[]args){
Scanner h = new Scanner(System.in);
int n;
System.out.println("How many discs : ");
n = h.nextInt();
Han(n, 'A', 'B', 'C');
System.out.println("Steps : " + stepsCounter); // new Code here.
}
}

【讨论】:

    【解决方案2】:

    除了引入静态变量(除其他问题外,它不是线程安全的),您还可以返回计数:

    public static int Han(int m, char a, char b, char c){
      int count = 0;
      if(m>0){
        count += Han(m-1,a,c,b);
        System.out.println("Move disc from "+a+" to "+b);
        count++;
        count += Han(m-1,b,a,c);
      }
      return count;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2018-05-25
      • 2019-10-12
      相关资源
      最近更新 更多