Java:(boolean[头=真,尾为假])



条件1:如果输入大于等于10个正面,并且能够在输入中显示则返回"找到条纹">

条件2:如果输入少于10个直头像则返回"条纹被打破">

然而,我在条件1中有一个问题,它没有执行到输出。

代码:

import java.util.LinkedList;
import java.util.Iterator;
import java.util.Scanner;
public class LinkedListProgram2
{    
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println ("Welcome to the Program #2 ");
//ask for the boolean value. It can be head and tail or true and false.
System.out.print ("nEnter the boolean value (head=true, tail=false): ");

for (int i = 0; i<18; i++)
{
cointoss.add(input.next());        
}

Iterator<String> it = cointoss.iterator();
while (it.hasNext())
{
if(streakcount >= 10)
{
streak = true;
System.out.println ("Streak is found! ");
break;
}
else if(streakcount < 10)
{
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}
}
}

至少需要添加2个逻辑

  1. 当找到true时增加条纹计数

  2. 当发现false时重置计数器

您可以在while循环中设置外部if条件,以便为每个实例打印broken,或者让它在循环结束时打印

while (it.hasNext()) {
String val = it.next();
if (val.equals("true"))
streakcount++;
else
streakcount = 0;

if (streakcount >= 10) {
streak = true;
System.out.println("Streak is found! ");
break;
}
}
if (!streak) {
System.out.println("Streak is broken! ");
}

您的代码中遗漏了一些东西,您需要检查输入值,并增加streakcount,未经测试的示例代码:

while (it.hasNext()) {
String val = it.next();
if (val.equals("true")) {
streakcount++;
if (streakcount >= 10) {
streak = true;
System.out.println ("Streak is found! ");
break;
}
}
else if (val.equals("false")) {
streak = false;
System.out.println ("Streak is broken! ");
break;
}
}

有更多的动作要做,检查不同的输入值,或者你需要找到条纹,如果它不是从开始数组…

根据你的描述,这实际上是一个计算特定字符串的小程序,甚至不需要LinkedList我修改了你的代码,现在它应该满足你提出的两个条件

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedList<String> cointoss = new LinkedList<String>();
boolean head = true;
boolean tail = false;
boolean streak = true;
int streakcount = 0;
System.out.println("Welcome to the Program #2 ");
// ask for the boolean value. It can be head and tail or true and false.
System.out.println("Enter the boolean value (head=true, tail=false): ");
for (int i = 0; i < 18; i++) {
String next = input.next();
if (next.equals("true") || next.equals("head")) {
streakcount++;
}
cointoss.add(next);
}
if (streakcount >= 10) {
System.out.println("Streak is found! ");
} else {
System.out.println("Streak is broken! ");
}
}

相关内容

  • 没有找到相关文章

最新更新