如何编写随机放置

如何编写随机放置

本文介绍了如何编写随机放置“O”的代码。基于用户输入的数字和随机生成的数字的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个程序,创建一个球O在控制台中来回弹跳的幻觉,但然后要求用户输入(0.0和1.0)球向右移动而不是向左移动的概率。对于每次迭代,使用Random类选择介于0.0和1.0之间的数字,如果此数字大于用户的选择,则向左移动,否则向右移动。如果球不能沿那个方向移动(因为它在边缘),那么O向后朝向中心一个空间。我有代码,它创造了球O弹跳的幻觉,但不能让它做第二部分。如何比较生成的数字和用户输入的概率,并根据比较进行O移动?这就是我到目前为止......

I have to write a program that creates the illusion of a ball "O" bouncing back and forth in the console, but then ask the user to input a probability between (0.0 and 1.0) that the ball moves right instead of left. For each iteration, use the Random class to pick a number between 0.0 and 1.0 and if this number is greater than the user's choice move left, otherwise move right. If the ball cannot move in that direction (because it is at an edge) then "O" backwards toward the center one space. I have the code to where it creates the illusion of a ball "O" bouncing but cannot get it to do the second part. How can I go about comparing the generated number and the probability inputted by the user and making the "O" move based on the comparison? This is what I have so far...





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

public class HelpForMidterm1 {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		Random rand = new Random();
		int spaces;
		System.out.print("How many spaces wide should the ball bounce in? ");
		spaces = scan.nextInt();
		double probability;
		System.out.print("Pick a probability for the ball to move right? ");
		probability = scan.nextDouble();
		double number;
		number = rand.nextDouble();
				while (true){
		for (int row = 0; row < spaces; row++)
			{
				for (int col = 0; col <= row; col++)
				{
					if (row == col)
						System.out.print("O");
					if (rand.nextDouble() > probability)

					else
						System.out.print(" ");

				}
				System.out.println();
			}

		for (int row = spaces; row >= 0; row--)
			{
				for (int col = 0; col <= row; col++)
				{

					if (row == col)
						System.out.print("O");
					else
						System.out.print(" ");
				}
				System.out.println();
			}
		System.out.println();






        }

	}





我尝试了什么:



我试图像bounceLeft和bounceRight一样使用,以及包含但不完整的if语句如果(rand.nextDouble()>概率)那么我就被卡住了。



What I have tried:

I've tried to use like a bounceLeft and bounceRight, along with the if statement that is included but not complete if(rand.nextDouble() > probability) then I'm stuck.

推荐答案

for (int row = 0; row < spaces; row++)
{
  xpos += xspeed;
  if (xspeed == 1 && rand.nextDouble() > probability)
    xspeed = -1;
   for (int col = 0; col <= row; col++)
   {
     if (xpos == col)
        System.out.print("O");
     else
        System.out.print(" ");
   }
}





当然你必须明确处理(左边作为练习)角落的情况 xpos 变为负数或大于空格


这篇关于如何编写随机放置“O”的代码。基于用户输入的数字和随机生成的数字的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:03