【发布时间】:2016-03-03 09:01:36
【问题描述】:
我需要循环我的班级RandomMath中的每个方法
我正在尝试实现一种算法:
- 生成一个 4 位数字。
- 将数字重新排列成最大的排列,创建一个称为更大的新值。
- 做同样的事情,但在最小的排列中创建一个新的值,称为更小。
- 从大中减去小,得到一个新的 4 位数字,称为 new4Digit
- 使用上面获得的 new4Digit 将步骤 2 中的过程循环十次,而不是生成一个新数字。
我已经完成了步骤 1-4 并实现了一个语句,该语句使该过程在第一次运行后用 new4Digit 替换生成的数字。现在我需要基本上循环整个类,它就会完成。有人知道怎么做吗?
我的代码:
import java.util.Random;
public class RandomMath {
private static int generated = generator();
//first set of values for the bigger, smaller and new 4 digit numbers
final private static int bigger = bigger();
final private static int smaller = smaller();
final private static int new4Digit = subtraction();
public static void main(String[] args) {
System.out.println(bigger);
System.out.println(smaller);
System.out.println(new4Digit);
}
//create method for generating random numbers
public static int generator(){
int n = 0;
//new4Digit is initialised to zero. So after the first loop instead...
//...of generating a new number the value of n is taken as new4Digit
if(new4Digit != 0){
n = new4Digit;
}
else{
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
}
return n;
}
//method for denoting the bigger number
public static int bigger(){
int[] times = new int[10];
while (generated != 0) {
int digit = generated % 10;
times[digit]++;
generated /= 10;
}
int big = 0;
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
big = big * 10 + i;
}
}
//code below accounts for ints with leading zeroes
//if the numer has three leading zeroes (<10) times by 1000
if (big < 10){
big = big * 1000;
}
//if the number has two leading zeroes (<100) times by 100
else if(big < 100){
big = big * 100;
}
//if the number has one leading zero (<1000) times by 10
else if(big < 1000){
big = big * 10;
}
return big;
}
//denoting the smaller number by simply reversing the bigger
public static int smaller(){
int d1 = bigger %10;
int r1 = bigger /10;
int d2 = r1 % 10;
int r2 = r1 / 10;
int d3 = r2 % 10;
int r3 = r2 / 10;
int d4 = r3 % 10;
int small = d1 * 1000 + d2 * 100 + d3 * 10 + d4;
return small;
}
//method for subtracting the smaller number from the bigger
public static int subtraction(){
int newNumber = bigger - smaller;
return newNumber;
}
}
【问题讨论】:
-
为什么不能按正确的顺序调用方法?
-
我不太清楚你的意思,但这不会涉及必须重复代码 10 次,这将是非常低效的。
-
翻译,你不能打电话
step1然后for (int i = 0; i < 10; ++i) { step2; step3; step4; }吗?
标签: java loops object for-loop while-loop