Java计数连续翻转头部,如何突出显示条纹事件
好的,我的代码适用于手头的任务。赋值是翻转从单独的Coin类(此处未显示)实例化的Coin对象。我已经正确地编写了代码,以便计算出以头部为输出的连续翻转的最大条纹。我想知道我怎么可能突出显示这个条纹,所以当我在控制台中查看输出时,条纹是可见的,因为在100次翻转的列表中很难注意到条纹 这是我的密码:Java计数连续翻转头部,如何突出显示条纹事件,java,if-statement,nested-if,Java,If Statement,Nested If,好的,我的代码适用于手头的任务。赋值是翻转从单独的Coin类(此处未显示)实例化的Coin对象。我已经正确地编写了代码,以便计算出以头部为输出的连续翻转的最大条纹。我想知道我怎么可能突出显示这个条纹,所以当我在控制台中查看输出时,条纹是可见的,因为在100次翻转的列表中很难注意到条纹 这是我的密码: public class Runs { public static void main (String[] args) { final int FLIPS = 100; // number of c
public class Runs
{
public static void main (String[] args)
{
final int FLIPS = 100; // number of coin flips
int currentRun =0; // length of the current run of HEADS
int maxRun =0; // length of the maximum run so far
// Create a coin objecti
Coin coin = new Coin();
// Flip the coin FLIPS times
for (int i = 0; i < FLIPS; i++)
{
// Flip the coin & print the result
coin.flip();
int flipCount = i + 1;
System.out.println("Flip " + flipCount +":"+ " " + coin.toString());
// Update the run information
if (coin.isHeads()==true)
{
if (maxRun<currentRun)
{
maxRun=currentRun;
}
currentRun+=1;
}
else
{
currentRun = 0;
}
}
// Print the results
System.out.println("Maximum run of heads in a row! : " + maxRun);
}
}
公共类运行
{
公共静态void main(字符串[]args)
{
最终整数翻转=100;//硬币翻转次数
int currentRun=0;//磁头当前运行的长度
int maxRun=0;//到目前为止的最大运行长度
//创建一个硬币对象
硬币=新硬币();
//掷硬币掷几次
对于(int i=0;i if(maxRun我不能100%确定你所说的“突出显示”是什么意思。如果你只是想让数字更明显,你可以在数字前面打印几个*s。如果你使用Eclipse,实际更改文本颜色的最简单方法是打印出你想用System.err.println(OutputOhighlight)突出显示的代码
。它将以红色打印出来。这是错误消息通常打印到控制台的方式。但这只适用于Eclipse
也许解决问题的更好方法是少打印投币量!而不是“突出显示”输出(可能是特定于设备/操作系统的),输出一个关于投币发生地点和投币时间的迷你报告
下面是代码的外观(我也为您简化了它-请参见代码中的注释):
int-maxRun=0;
int currentRun=0;
int runStart=0;
对于(int i=0;i
你说的“hightlight”是什么意思?你想让文本或背景变成不同的颜色吗?是的,文本或文本背景在头部最大条纹的位置是不同的颜色。改变文本的颜色是独立于平台的,在Java中很难做到(如果不是不可能的话)。呃…我的意思是“依赖于平台”,但你明白了。是的,这是一个好主意,我将在Eclipse中继续使用它进行调试。因为这是Java类的一个硬件分配,所以我必须将翻转次数保留为100。不过,感谢OutputOhighlight函数,它看起来确实很有用。@User215884干杯!如果你要使用它,请记住它是是“.err”而不是“.out”在你的print语句中就是这样做的。我刚刚把outputOhighlight变量编成了将被打印成红色的变量。好的,很高兴知道!我认为这是某种函数,感谢你澄清了这一点。因此,本质上system.err.println突出显示了你输入的任何内容,作为这个函数的参数,好像它是那是一个错误吗?@kinghenry14是的!它会像打印错误一样打印出你的参数。在Eclipse中,默认情况下,错误会以红色打印出来。谢谢。查看其他人的编辑总是有帮助的。我知道当你执行println()时其中的任何内容都会自动转换为字符串,但我想出于习惯,我在那里使用了toString方法。感谢您指出了与常量的布尔比较,我认为它可以在不输入==true的情况下工作,但没有重复检查我所拥有的内容。我也喜欢runStart实现,这使它成为一个bi这不容易理解。
int maxRun = 0;
int currentRun = 0;
int runStart = 0;
for (int i = 0; i < FLIPS; i++) {
coin.flip();
System.out.println("Flip " + (i+1) +": " + coin); // toString() is redundant
if (coin.isHeads()) { // never compare a boolean with a boolean constant, just use it
currentRun++; // use ++ in preference to +=1, and this should be before maxRun test
if (maxRun < currentRun) {
maxRun = currentRun;
runStart = currentRun - i; // this will produce a 1-based position
}
} else {
currentRun = 0;
}
}
System.out.println("Largest run was " + maxRun + " long, starting at " + runStart);