Java 数组、布尔值与逻辑思维
书中的问题: 这是一个经过充分研究的事实,在洗手间里的男人通常更喜欢通过占据最长的未占用位置序列的中间位置来最大化他们与已经占用的摊位之间的距离 例如,考虑十个摊位是空的情况。p>Java 数组、布尔值与逻辑思维,java,arrays,boolean,Java,Arrays,Boolean,书中的问题: 这是一个经过充分研究的事实,在洗手间里的男人通常更喜欢通过占据最长的未占用位置序列的中间位置来最大化他们与已经占用的摊位之间的距离 例如,考虑十个摊位是空的情况。p> _ _ _ _ _ _ _ _ _ _ The first visitor will occupy a middle position: _ _ _ _ _ _ X _ _ _ The next visitor will be in the middle of the empty area at the left
_ _ _ _ _ _ _ _ _ _
The first visitor will occupy a middle position:
_ _ _ _ _ _ X _ _ _
The next visitor will be in the middle of the empty area at the left.
_ _ X _ _ X _ _ _ _
编写一个程序,读取暂停的数量,然后在暂停填满时按上述格式打印图表,每次打印一个。提示:使用一个布尔值数组来指示是否已占用暂停
我在为这个问题编程时遇到了困难,我对如何应用布尔值以及如何解决这个问题感到困惑。我写了这段代码,但我觉得没有任何意义,
非常感谢您的帮助
import java.util.Random;
import java.util.Arrays;
public class Stall
{
public static void main(String[] args)
{
Random random = new Random();
String[] array = {"_"," _ "," _ "," _ "," _ "," _ "," _ "," _ "," _ "," _"};
boolean filled = true; // Checking to see if stalls are completely filled
while (filled = true)
{
for (int i = array.length - 1; i > 0 ; i--)
{
String number = array[i];
if (!(number.equals("X"))) // if filled,all stalls would be marked as X
{
filled = false;
}
}
}
boolean found = false; //checking if "X" is found
while (filled = false)
{
while (found = false) // if not found generate a new number for array and set it to "X";
{
int number1 = random.nextInt(10) + 1;
if (!(array[number1].equals("X")))
{
array[number1] = "X";
found = true;
}
}
while (found = true)
{
int number2 = random.nextInt(10) + 1;
for ( int i = 0; i < array.length; i++)
{
if (!(array[i].equals("X")))
{
array[number2] = "X";
found = false;
}
}
}
System.out.println(Arrays.toString(array));
}
}
}
import java.util.Random;
导入java.util.array;
公务舱摊位
{
公共静态void main(字符串[]args)
{
随机=新随机();
字符串[]数组={“”、“”、“”、“”、“”、“”、“”、“”、“”、“”};
boolean filled=true;//检查暂停是否已完全填满
while(filled=true)
{
对于(int i=array.length-1;i>0;i--)
{
字符串编号=数组[i];
if(!(number.equals(“X”))//如果已满,则所有档位都将标记为X
{
填充=假;
}
}
}
boolean found=false;//检查是否找到“X”
while(填充=假)
{
while(found=false)//如果找不到,则为数组生成一个新的数字,并将其设置为“X”;
{
int number1=random.nextInt(10)+1;
if(!(数组[number1].equals(“X”))
{
数组[number1]=“X”;
发现=真;
}
}
while(find=true)
{
int number2=random.nextInt(10)+1;
for(int i=0;i
您的代码有足够多的问题,如果不完全重写,很难纠正它
尽管有一些建议,
像老师建议的那样使用布尔数组来表示暂停,而不是像现在这样使用字符串数组
像这样的台词:
while (found = false)
没有按你想象的方式工作。请记住,一个等号(=)设置变量值,而两个(=)比较值。99%的时间里,您都希望在while循环中使用==
在开始之前,试着花点时间编写代码并仔细考虑您的方法。总是问自己,最直接的方法是什么 帮什么忙?学习使用调试器并遵循代码的操作。@Sotirios Delimanolis为什么这会让我成为家庭作业的一部分。。。。卡利斯佩拉@meewoK它确实来自一本书!那艾赛卡拉!提示建议将
\ux\uux\uuu
表示为[false,false,false,false,true,false,false]
.FYI,filled=true
正在使用赋值运算符,它不会执行您想要的操作。改为使用while(filled)
(以及while(!filled)
表示何时应为false)。实际上,你也应该使用布尔数组,而不是字符串数组——这会让你的生活更轻松。