我已经对编程产生了新的兴趣,但是我遇到了一些问题。我试图制作一个简单的程序,用户输入10个数字,如果数字为0则停止,然后将这些数字添加到列表中,然后在结尾打印列表。但是,我的程序在停止之前只询问4个数字,当输入0时它不会停止,并且每次循环时“开始输入数字消息”打印3次。
任何帮助将不胜感激
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args) {
// I want to make a list
// keep asking the user for values
// which will then add those values onto the list
// then print the list
// create a list
List<int> list = new List<int>();
int count = 0;
while (count < 10) {
Console.WriteLine("Enter a value to add to the list");
int number = Console.Read();
list.Add(number);
if (number == 0) {
break;
}
count++;
}
Console.WriteLine("The final list looks like this");
foreach (int number in list) {
Console.WriteLine(number);
Console.ReadLine();
}
}
}
}
答案 0 :(得分:3)
问题在于 Console.Read() - 它读取字节而不是在您的情况下应转换为int的字符串。
您正在寻找的是Console.ReadLine(),用int.Parse()包围。像这样:
int number = int.Parse(Console.ReadLine());