class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.Clear();
do
{
//Print command
string print = Console.ReadLine();
if (print.ToLowerInvariant().StartsWith("print: "))
{
string p2 = print.Substring(print.IndexOf(' ') + 1);
Console.WriteLine(p2);
}
string var = Console.ReadLine();
if (var.ToLowerInvariant().StartsWith("var "))
{
string v2 = var.Substring(var.IndexOf(' ') + 1);
}
}
while (true);
}
}
我现在想要如何通过键入var然后将数字设置为字符串来创建var,并且能够打印数字或字符串
答案 0 :(得分:0)
var
是一个关键字。通过将var
重命名为variable
:
class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.Clear();
do
{
//Print command
string print = Console.ReadLine();
if (print.ToLowerInvariant().StartsWith("print: "))
{
string p2 = print.Substring(print.IndexOf(' ') + 1);
Console.WriteLine(p2);
}
string variable = Console.ReadLine();
if (variable.ToLowerInvariant().StartsWith("var "))
{
string v2 = variable.Substring(variable.IndexOf(' ') + 1);
}
}
while (true);
}
}
编辑:新要求,这是我提出的代码,但没有错误处理:
using System;
using System.Collections.Generic;
namespace Variables
{
class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.Clear();
var dict = new Dictionary<string, int>();
do
{
//Print command
string command = Console.ReadLine();
if (command.ToLowerInvariant().StartsWith("print: "))
{
string p2 = command.Substring(command.IndexOf(' ') + 1);
if (dict.ContainsKey(p2)) Console.WriteLine(dict[p2]);
else Console.WriteLine("Variable {0} undefined!");
}
if (command.ToLowerInvariant().StartsWith("var "))
{
string v2 = command.Substring(command.IndexOf(' ') + 1);
string[] parts = v2.Split(new char[]{'='}, 2, StringSplitOptions.RemoveEmptyEntries);
parts[0] = parts[0].Trim();
parts[1] = parts[1].Trim();
dict.Add(parts[0], int.Parse(parts[1]));
}
}
while (true);
}
}
}