[英]Java: linked list - (boolean [head=true, tail false])
條件一:如果你輸入了多於或等於10個直頭並且能夠在輸入中顯示,那么返回是“Streak is found”
條件 2:如果您輸入的直頭少於 10 個,則返回“Streak is broken”
但是,我遇到了條件 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個邏輯。
找到 true 時增加連續計數
發現假時重置計數器
您可以在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! ");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.