3 回答

TA貢獻1820條經驗 獲得超2個贊
string sentence = Console.ReadLine();
while (true)
{
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
}
else if (sentence.Split(' ').Length < 6)
{
Console.WriteLine("\r\nThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
}
else break;
sentence = Console.ReadLine();
}

TA貢獻1828條經驗 獲得超3個贊
sentence.Length返回字符串中的字符數。你必須把句子分成單詞。
string[] words = sentence.Split();
在空白字符處拆分。
因此,您可以將循環編寫為
while (String.IsNullOrEmpty(sentence) || sentence.Split().Length < 6)
{
...
}
這Length是拆分產生的字符串數組的長度。
請注意,如果句子是null,C# 的布爾表達式的短路求值將不會執行||.后面的子表達式。因此,您不會得到空引用異常。

TA貢獻1876條經驗 獲得超5個贊
// 首先嘗試改變 while 條件,如波紋管 ....然后嘗試波紋管代碼..
public static void Main(string[] args)
{
int count = 0;
inputSteream:
Console.WriteLine("Enter your sentence: ");
string sentence = Console.ReadLine();
while (!String.IsNullOrEmpty(sentence) && sentence.Length >= 6)
{
foreach (var item in sentence.Split(' '))
{
if (item.Length >= 6)
{
Console.WriteLine("The sentece is {0}", item);
count++;
break;
}
}
break;
}
if (count == 0)
{
goto inputSteream;
}
Console.ReadKey();
}
- 3 回答
- 0 關注
- 180 瀏覽
添加回答
舉報