[英]I'll write my if-statement into the switch-method…but how to write the boolean in the case line
首先感謝您的幫助!
我的問題是..如何將此if-codeblock寫入開關盒。 我只有布爾值有問題。
我的代碼塊
int Note = 0;
Console.WriteLine("What is your note?: ");
Note = Convert.ToInt32(Console.ReadLine());
if ((Note < 1) || (Note > 6))
{
Console.WriteLine("Your input is wrong!");
}
else
{
if (Note <= 4)
{
Console.WriteLine("Passed");
}
else
{
Console.WriteLine("Failed");
}
}
我試圖將其寫入切換方法
int Note = 0;
Console.WriteLine("What ist your note?: ");
Note = Convert.ToInt32(Console.ReadLine());
switch (Note)
{
case Note < 1 || Note > 6:
Console.WriteLine("Your input is wrong!");
break;
case Note <= 4:
Console.WriteLine("Passed");
break;
}
錯誤消息:我無法將字符串轉換為int。
再次感謝您的任何想法。
C#7 +支持基於范圍的切換:
switch (Note)
{
case int n when n< 1 || Note > 6:
Console.WriteLine("Your input is wrong!");
break;
case int n when n <= 4:
Console.WriteLine("Passed");
break;
}
如果您確實需要開關,可以這樣做
switch (Note)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("Passed");
break;
case 5:
case 6:
Console.WriteLine("Failed");
break;
default:
Console.WriteLine("Your input is wrong!");
break;
}
這不是switch
語句適用的地方。 您應該繼續使用if
。
我將按照您的要求使用switch
輕松地證明這一點:
switch (Note)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine("Passed");
break;
case 5:
case 6:
Console.WriteLine("Failed");
break;
default:
Console.WriteLine("Your input is wrong!");
break;
}
這太逐字了。 您不想寫下每個值。 if
更合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.