2015-11-05 43 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'。这不是一个好主意。 –

相关问题