将数字转换为星号

时间:2018-10-17 05:28:10

标签: java arrays

我是编程新手,我正在创建一个具有两个6面骰子的游戏,我想使用一个星号代表总掷骰的百分比,但我正在努力将数字转换为打印该数字星号。

import java.util.Scanner;
import java.util.Random;

public class DiceGame

{
   public static void main (String[] args) 
{
  Scanner in = new Scanner (System.in);
  Random r = new Random();

  int numGames = 0;
  int[] die = new int[13];
  int rollOne = 0;
  int rollTwo = 0;
  int numAsterisks = 0;

  //Game intro
  System.out.println("Welcome to the dice throwing simulator! How many dice rolls would you like to simulate?");
  numGames = in.nextInt(); 

  for (int i = 0; i <= numGames; i++)
  {

     rollOne = r.nextInt(6)+1;
     rollTwo = r.nextInt(6)+1;

     die[rollOne + rollTwo]++;

  }//end for

  for (int i = 2; i < die.length; i++)
  {
     numAsterisks = 100 * die[i] / numGames;

     System.out.println(i + ": ");

        for (int x = 0; x < numAsterisks; x++) 
        {
           System.out.print("*");
        }

  }//end for

}//end main

}//end DiceGame`

同样,当我运行此命令时,数字也会像这样显示在星号之后:

Welcome to the dice throwing simulator! How many dice rolls would you like to simulate? 1000 2: **3: *****4: **********5: ***********6: **************7: *****************8: *************9: **********10: ******11: *****12: **

是什么导致它这样做?

2 个答案:

答案 0 :(得分:0)

尝试一下:

 for (int i = 2; i < die.length; i++) {
     numAsterisks = 100 * die[i] / numGames;
     System.out.print(i + ": "); //Changed println to print
     for (int x = 0; x < numAsterisks; x++) {
         System.out.print("*");
     }
     System.out.println(); //Added println
 }

printprintln之间的区别在于,在后者的情况下添加了换行符。因此,在打印数字和冒号时不需要println,但是在打印所有星号之后就需要另外的println

答案 1 :(得分:0)

我对您的方法进行了一些更改,首先,您不需要初始化int值,因为它们已经被分配了;其次,我在System.out中添加了一个实例,并添加了要打印的代码内循环结束后的空行多亏了用户Andremoniy的评论。这是它的完整代码。

public class DiceGame {
    public static void main(String[] args) {
        /**
         * Remove Initialization from ints because they are already being assigned
         */
        int numGames;
        int rollOne;
        int rollTwo;
        int numAsterisks;
        int[] die = new int[13];

        Scanner in = new Scanner(System.in);

        //Direct call to System.out for making the code look cleaner
        PrintStream out = System.out;

        Random random = new Random();

        out.println("Welcome to the dice throwing simulator! How many dice rolls would you like to simulate?");

        numGames = in.nextInt();
        for (int i = 0; i <= numGames; i++) {
            rollOne = random.nextInt(6) + 1;
            rollTwo = random.nextInt(6) + 1;
            die[rollOne + rollTwo]++;
        }

        for (int i = 2; i < die.length; i++) {
            numAsterisks = 100 * die[i] / numGames;
            out.println(i + ": ");
            for (int x = 0; x < numAsterisks; x++) {
                out.print("*");
            }
            //Printing out an empty line once the loop has ended
            out.println();
        }
    }
}