c# - C#--为什么我必须输入两次才能提交 Console.Readline
问题描述
C#新手。尝试制作一个简单的成绩簿程序,其中用户:
- 输入学生姓名,直到输入“完成”
- 输入每个用户的成绩,然后计算平均值
第 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());
}
}
}
}
对此的任何帮助将不胜感激!
谢谢
解决方案
您正在调用 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 :)
推荐阅读
- java - Android Studio 不会运行我对 Selenium/Carina/Appium 的测试。单击运行按钮没有任何错误
- python-3.x - 是否可以使用自定义生成器来训练带有 keras tensorflow 2.0.0 的多输入架构?
- html-parsing - 为什么lxml在解析时会关闭这个“ol”标签?
- mysql - 如何在 SQL 中添加带有 LAG 的计算列?
- lazy-evaluation - 意外的非懒惰
- sql - * 可以用于 AWS 的 IoT 规则语法中的部分主题吗?
- python - 填写缺失的日期
- java - Maven 版本插件 - 在 mvn 构建安装期间跳过运行的 Maven 版本插件
- google-cloud-platform - GCP 云负载均衡器映射更新导致停机
- javascript - 如何在 bootstrap 5 网页中添加和实现 bootsrapVue 算法分页组件或插件