所以我刚刚完成了一个小程序,当我运行它时一切正常。我确实有一个我不喜欢的小技术问题,如果你愿意,它是一个不均匀的“桌子”。简而言之,我想要它,所以我的输出在两边都是一致的。
原始输出: 应该生成多少个数字? 10 每次抽奖的价值是多少? 1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
代码:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}
答案 0 :(得分:1)
查看System.out.format(https://docs.oracle.com/javase/tutorial/essential/io/formatting.html),特别是width选项。这可能就是你想要的。
答案 1 :(得分:0)
有两种方法:
1)如前所述,请查看System.out.format目录。它具有广泛的方法来格式化输出
2)以手动方式更改间距,其间距取决于左侧数字中的字符数。