我必须增加变量count并返回001,002 ...,099 ....,999 update()返回计数值,reset()将重置静态变量 我用过它的代码。
public class getCount {
static String count="0";
//resets the value to 0
public static void reset() {
// TODO Auto-generated method stub
count="0";
}
//updates the value
public static String update() {
String temp=count;
DecimalFormat df1 = new DecimalFormat("000");
String T=String.valueOf(df1.format(Integer.parseInt(temp)));
if( temp=="1000")
{
count="1";
return count;
}
return T;
}
//main() is used for testing
public static void main(String[] a) {
String c1=update();
System.out.println(c1);
String c2=update();
System.out.println(c2);
String c3=update();
System.out.println(c3);
String c4=update();
System.out.println(c4);
String c5=update();
System.out.println(c5);
reset();
String c6=update();
System.out.println(c6);
String c7=update();
System.out.println(c7);
String c8=update();
System.out.println(c8);
}
我得到的输出是001,001 ....
答案 0 :(得分:0)
稍微简单一些:
public class Count {
private static int count = 0;
// resets the value to 0
public static void reset() {
count = 0;
}
// updates the value
public static String update() {
count++;
if(count == 1000) count = 1;
return String.format("%03d", count);
}
// main() is used for testing
public static void main(String[] a) {
for(int i=0; i< 1001; i++){
String c1 = update();
System.out.println(c1);
}
reset();
String c2 = update();
System.out.println(c2);
String c3 = update();
System.out.println(c3);
}
}
顺便说一下,您的班级名称getCount
应该是GetCount
,甚至更好(在我看来),没有动词:Count