2015-11-05 39 views
2

我正在製作日曆,我想將重要會議設置爲紅色,其他人設置爲白色。我怎樣才能做到這一點?當我爲最後一行設置紅色時,不重要的會議也是紅色的。我的代碼:設置「重要」 - 消息紅色,其他白色

string important; 
Console.Write("High priority? input yes or no: "); 
important = Console.ReadLine(); 

if (important == "yes" || important == "Yes") 
{ 
    important = "Important"; 
} 
else 
{ 
    important = "Normal"; 
} 

Console.Write("Priority: " + important); 
+0

對付這種「是」或「YES」,只是格式化字符串包含唯一的資本或者只有更低字母,然後比較其 – mikus

+0

@mikus:代替* reformating字符串*把它比作'String.Equals(「yes」,important,StringComparison.OrdinalIgnoreCase)' –

+0

好吧,你說得對,在C#中它是一個更好的選擇,我想到了一般規則:) – mikus

回答

2

如果更改ForeGroundColorRed,你必須將其重置爲Gray這是默認的顏色。您可以使用此代碼

Console.Write("High priority? input yes or no: "); 
string important = Console.ReadLine(); 

if (important.Equals("yes", StringComparison.InvariantCultureIgnoreCase)) 
{ 
    Console.Write("Priority: "); 
    Console.ForegroundColor = ConsoleColor.Red; 
    Console.Write("Important");   
} 
else 
{ 
    Console.ForegroundColor = ConsoleColor.White; 
    Console.Write("Priority: Normal"); 
} 
Console.ResetColor(); //default 
+0

檢查我的答案。這幾乎是一樣的,但我的工作沒有「重要的。平等」。爲什麼我需要這個? – user5462581

+2

@ user5462581主要區別在於*重置顏色*。 'important.Equals' with'StringComparison.InvariantCultureIgnoreCase'將在無論如何 - YES,yes,yEs等情況下處理「是」 –

+0

很高興知道。謝謝。 – user5462581

1

使用Console.ForegroundColor像這樣:

important = Console.ReadLine(); 

Console.Write("Priority: "); 

if (important == "yes" || important == "Yes") 
{ 
    Console.ForegroundColor = ConsoleColor.Red ; 
    important = "Important"; 
} 
else 
{ 
    Console.ForegroundColor = ConsoleColor.White; 
    important = "Normal"; 
} 
Console.Write(important); 
+0

當我這樣做時,消息最後一行中的「優先級:[......]」也變爲紅色。我只希望輸出「重要」紅色,輸出「正常」白色。這是線索。 – user5462581

+0

@ user5462581,所以設置顏色之前輸出你所需要的 - 如果你輸出''優先級:[...]「'logicaly所有這個字符串應用選定的顏色 – Grundy

+0

@ user5462581 ...檢查我更新的答案。 –

0

檢查Arghya C'S答案。

舊代碼:

string important; 

     Console.Write("\n\nIs the meeting high priority?\n Input \"Yes\" or \"No\": "); 

     important = Console.ReadLine(); 

if (important == "yes" || important == "Yes") 
     { 
     Console.Write("\nPriority: \t"); 
     Console.ForegroundColor = ConsoleColor.Red; 
     Console.Write("Important"); 
     } 
     else 
     { 
     Console.Write("\nPriority: \t"); 
     Console.ForegroundColor = ConsoleColor.White; 
     Console.Write("Normal"); 
     } 
+0

我真的沒有看到您的解決方案和我的答案之間的任何重要區別! –

+0

你現在看到了嗎?我不改變變量值。我用'Console.Write'寫出「重要」。您更改字符串值並輸出值本身。 – user5462581

+0

那麼爲什麼它應該是要麼改變變量的顏色或你的?你在'if'和'else'語句中兩次重複'Console.Write'。這不是一個好主意。 –

相關問題