到目前为止,这是我的代码 包chapter3Codes;
public class TwoDice {
public static void main(String[] args) {
Dice a = new Dice();
Dice b = new Dice();
int sum = 0;
int is2=0; int is3=0; int is4=0; int is5=0; int is6=0;
int is7=0; int is8=0; int is9=0; int is10=0; int is11=0; int is12=0;
for (int i=1; i<= 100000; i++){
a.roll();
a.getFaceValue();
b.roll();
b.getFaceValue();
sum = (a.getFaceValue()+ b.getFaceValue());
if(sum == 2){
is2++;
}else{
if(sum == 3){
is3++;
}else{
if(sum == 4){
is4++;
}else{
if(sum == 5){
is5++;
}else{
if(sum == 6){
is6++;
}else{
if(sum == 7){
is7++;
}else{
if(sum == 8){
is8++;
}else{
if(sum == 9){
is9++;
}else{
if(sum == 10){
is10++;
}else{
if(sum == 11){
is11++;
}else{
if(sum == 12){
is12++;
}
}
}
}
}
}
}
}
}
}
}
}
System.out.println("The sum is 2 "+ is2 + " many times");
System.out.println("The sum is 3 "+ is3 + " many times");
System.out.println("The sum is 4 "+ is4 + " many times");
System.out.println("The sum is 5 "+ is5 + " many times");
System.out.println("The sum is 6 "+ is6 + " many times");
System.out.println("The sum is 7 "+ is7 + " many times");
System.out.println("The sum is 8 "+ is8 + " many times");
System.out.println("The sum is 9 "+ is9 + " many times");
System.out.println("The sum is 10 "+ is10 + " many times");
System.out.println("The sum is 11 "+ is11 + " many times");
System.out.println("The sum is 12 "+ is12 + " many times");
for(int i = 0; i <= is2;i++){
System.out.println("*");
}
for(int i = 0; i <= is3;i++){
System.out.println("*");
}
for(int i = 0; i <= is4;i++){
System.out.println("*");
}
for(int i = 0; i <= is6;i++){
System.out.println("*");
}
for(int i = 0; i <= is7;i++){
System.out.println("*");
}
for(int i = 0; i <= is8;i++){
System.out.println("*");
}
for(int i = 0; i <= is9;i++){
System.out.println("*");
}
for(int i = 0; i <= is10;i++){
System.out.println("*");
}
for(int i = 0; i <= is11;i++){
System.out.println("*");
}
for(int i = 0; i <= is12;i++){
System.out.println("*");
}
}
}
如何修复我的代码,以便每次is2
递增时都会打印星号。
例如,如果is2
增加了3倍而is3
增加了4倍,则会显示为
***
****
答案 0 :(得分:1)
由于您尚未学习数组,我将向您展示如何在一行上为unserialize()
打印*
s。您需要two
多次,但只需要一个System.out.print
来完成该行。像,
System.out.println
答案 1 :(得分:0)
如果您使用hashmap,可能会对事情进行过多压缩,如下所示:
公共课TwoDice {
public static void main(String[] args) {
Dice a = new Dice();
Dice b = new Dice();
Map<Integer,Integer> sumMap = new Hashmap<Integer,Integer>();
int sum = 0;
for (int i=1; i<= 100000; i++){
a.roll();
a.getFaceValue();
b.roll();
b.getFaceValue();
//
sum = (a.getFaceValue()+
b.getFaceValue());
if(sumMap.get(sum)==null){
sumMap.put(sum,1);
}else{
sumMap.put(sum,sumMap.get(sum)+1);
}
}
for(int i=1; i<=12; i++)
{
int size = sumMap.get(i)==null? 0 : sumMap.get(i);
System.out.println("The sum is "+i+" "+ size +
" many times");
}
for(int i=1; i<=12; i++)
{
int size = sumMap.get(i)==null? 0 : sumMap.get(i);
for(int j=1; j<=size; j++){
System.out.print("*");
}
System.out.println("");
}
}
}