不确定该做什么,以及它是否包含在我的if语句中或我创建一个新语句。 必须只为HEADS获得最长时间的运行。
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 10;
public void run()
{
int headFlips = 0;
int tailFlips = 0;
int longestRun = 0;
int max = 0;
for (int i = 0; i < FLIPS; i++)
{
if(Randomizer.nextBoolean())
{
System.out.println("Heads");
headFlips++;
}
else
{
System.out.println("Tails");
tailFlips++;
}
if ()
{
longestRun++;
if(max < longestRun)
{
max = longestRun;
}
}
else
{
longestRun = 0;
}
}//end for loop
System.out.println("Longest streak of heads: " +longestRun);
}
}
请帮助我!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
答案 0 :(得分:1)
考虑这个简单的逻辑
longestRun = 0;
currentRun = 0;
for (int i = 0; i < FLIPS; i++)
{
if(Randomizer.nextBoolean())
{
System.out.println("Heads");
// headFlips++; - not used
currentRun ++;
}
else
{
System.out.println("Tails");
// tailFlips++; - not used
longestRun = Math.max (longestRun, currentRun);
currentRun = 0;
}
}
// need to do after the loop too
longestRun = Math.max (longestRun, currentRun);
System.out.println("Longest streak of heads: " +longestRun);
答案 1 :(得分:-1)
你可以这样做:
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 10;
public void run()
{
int longestRun = 0;
int max = 0;
Random r = new Random();
for (int i = 0; i < FLIPS; i++)
{
if(r.nextBoolean())
{
System.out.println("Heads");
//increment max
max++;
}
else
{
System.out.println("Tails");
//since the run is broken, compare the max & the longest run.
//if max is greater, then set longest run to max
if(max > longestRun)
{
longestRun = max;
}
//reset your counter
max = 0;
}
}//end for loop
//need to compare last run of flipping in case you end on heads
if(max > longestRun)
{
longestRun = max;
}
System.out.println("Longest streak of heads: " +longestRun);
}
}