首页 > 解决方案 > C#--为什么我必须输入两次才能提交 Console.Readline

问题描述

C#新手。尝试制作一个简单的成绩簿程序,其中用户:

  1. 输入学生姓名,直到输入“完成”
  2. 输入每个用户的成绩,然后计算平均值

第 2 部分有效,但我的问题在于第 1 部分——您必须按两次 Enter 才能将名称提交到列表中。例如,如果我输入 Bob、Lisa、Kevin、Jane——只有 Bob 和 Kevin 会进入——第二行(即使你输入了一些内容)充当了 console.read 提交到列表的行。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Csharp
{

    class MainClass
    {
        static List<string> mylist = new List<string> { };
        public static void Main(string[] args)
        {

            UserInput();
            GradeEnter();
        }
        public static void UserInput()
        {
            Console.WriteLine("Enter Some names (type 'done' when finished)");
            do
            {
                mylist.Add(Console.ReadLine());
            } while (!Console.ReadLine().Equals("done"));


        }
        public static void GradeEnter()
        {

            foreach (var x in mylist)
            {
                List<int> myInts = new List<int>();
                Console.WriteLine("\nEnter grades for {0}, (enter any letter when done)", x);
                while (Int32.TryParse(Console.ReadLine(), out int number))
                {
                    myInts.Add(number);
                }
                Console.Write("Average is ");
                Console.Write(myInts.Average());

            }
        }

    }
}

对此的任何帮助将不胜感激!

谢谢

标签: c#

解决方案


您正在调用 ReadLine 两次。你可以试试这个:

public static void UserInput()
{
    Console.WriteLine("Enter Some names (type done to exit)");
    string name = Console.ReadLine();
    while (!name.Equals("done"));
    {
        mylist.Add(name);
        name = Console.ReadLine();
    } 
}

另一种做同样的方法

public static void UserInput()
{
    Console.WriteLine("Enter Some names (type done to exit)");
    while (true);
    {
        string name = Console.ReadLine();
        if (name == "done")
        {
            // This will stop the while-loop
            break;
        } 
        mylist.Add(name);
    } 
}

现在让我们分析一下你的代码在做什么

        do
        {
            // Read line and add it to the list. Even if the user writes "done" 
            mylist.Add(Console.ReadLine());

        // Read the console again, if the user enters done, exit. But if the user enters other name, you are discarding it, you are not adding it to the list
        } while (!Console.ReadLine().Equals("done"));

使用您的代码的一些测试用例:

1. Peter <- gets added to the list
2. Lucas <- does not get added to the list, just checks if it is done
3. Mario <- gets added to the list
4. Juan  <- again, just checking if it is done, so not added to the list
5. done  <- It is treated like a name, so it will be added to the list
6. done  <- now it will finish :) 

推荐阅读