我在創建允許用戶輸入數字的 while 回圈時遇到了困難,該數字決定了回圈將執行多少次。我需要創建此方法并讓它在 Main() 中執行,感覺迷茫并且不確定為什么我當前的代碼無法正常作業。
public static int InputValue(int min, int max)
{
//determine number of search times
int val;
Console.WriteLine("Enter a number between 1-30:");
val = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < val; i )
while (val > max || val < min)
{
Console.WriteLine("Please enter number within the range...");
break;
}
return val;
}
uj5u.com熱心網友回復:
您的while回圈看起來旨在確保輸入數字在范圍內。
那應該在你的for回圈之前發生,并且開始的行val = ...應該在那個回圈內。當滿足范圍內的條件時,您想跳出該“輸入驗證”。我認為使用do...while回圈讀起來更自然,因為輸入步驟至少會發生一次。
最后,你的for回圈應該有用。
這就是所有可能的樣子:
public static int InputValue(int min, int max)
{
//determine number of search times
int val;
Console.WriteLine($"Enter a number between {min}-{max}:");
do
{
val = Convert.ToInt32(Console.ReadLine());
if (val > max || val < min)
Console.WriteLine("Please enter number within the range...");
}
while (val > max || val < min);
for (int i = 1; i <= val; i )
Console.WriteLine($"Iteration {i} of {val}");
return val;
}
uj5u.com熱心網友回復:
您必須事先檢查輸入是否有效。不太清楚您希望代碼做什么,我認為這可以滿足您的要求。還有你的for回圈是為了什么?
public static int InputValue(int min, int max) {
//goes until until input is valid
while (true) {
int val = Convert.ToInt32(Console.ReadLine());
if (val > max || val < min) {
Console.WriteLine($"Please enter a number between {min} and {max}");
}
else {
/* does whatever once input is valid,,
I'm not sure what you're trying to do
with the for loop but do it in here */
return val;
}
}
}
uj5u.com熱心網友回復:
您問題中的代碼有效地完成了您的要求。
這是您的代碼的稍微清理過的版本,它可以滿足您的要求:
Console.WriteLine("Enter a number between 1-30:");
int val = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < val; i )
{
/* this runs `val` times. */
}
因此,您的代碼可以按照您的要求正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537544.html
標籤:C#循环while循环
