java 在java中添加一个计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25983129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a counter in java
提问by Jamiex304
I am developing a simple Tower of Hanio java programme. I have it giving me all the steps for the amount of disks the user inputs.
我正在开发一个简单的哈尼奥塔 java 程序。我有它为我提供了用户输入的磁盘数量的所有步骤。
But Now I am stuck I want to put a counter at the end to give the user a clear number of steps rather than have them count them all
但是现在我卡住了,我想在最后放一个计数器,以便为用户提供明确的步数,而不是让他们计算所有步数
Here is my code, if you can help me,
这是我的代码,如果你能帮助我,
add a count that would be great.
添加一个很好的计数。
Any help would be great
任何帮助都会很棒
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');
}
}
采纳答案by Mehdi
The easy way is to use a static variable like this:
简单的方法是使用这样的静态变量:
import java.util.Scanner;
导入 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.
}
}
回答by Sbodd
Rather than introduce a static variable (which, among other concerns, isn't thread-safe), you could also return the count:
除了引入静态变量(除其他问题外,它不是线程安全的),您还可以返回计数:
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;
}