我不知道如何在循环中读取用户输入(用Console.ReadLine)。我正在创建一个便条,它允许我存储用户输入的内容,如果他输入了exit,就退出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Note myNote = new Note();
Note otherNote = new Note();
myNote.addText("Hi there");
Console.WriteLine(myNote.display());
otherNote.addText(Console.ReadLine());
Console.WriteLine(otherNote.display());
if (otherNote = "exit")
{
}
}
}
}
class Note
{
private string text = "";
private DateTime timeStamp = DateTime.Now;
private DateTime modifiedStamp = DateTime.Now;
int maxLength = 10;
public void addText(string sometext)
{
if (text.Length + sometext.Length < maxLength)
{
text += sometext;
modifiedStamp = DateTime.Now;
}
}
public string display()
{
return "Created: " + timeStamp.ToString() + "\n" +
"Modified: " + modifiedStamp.ToString() + "\n" +
"Content: " + text;
}
}发布于 2015-09-02 21:58:24
您需要备注列表,以便添加任意数量的注释。此外,如果用户确实要求退出,则需要首先保存ReadLine输入检查,否则继续添加注释。
var myNotes = new List<Note>();
var firstNote = new Note();
firstNote.addText("Hi there");
Note note;
while (true)
{
var input = Console.ReadLine();
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
note = new Note();
note.addText(input);
myNotes.Add(note);
}发布于 2015-09-02 21:58:32
通常的格式是使用类似这样的东西(带中断条件的while循环):
// put code above while loop that only needs to be executed once
while (true) {
// get the user input for every iteration, allowing to exit at will
String line = Console.ReadLine();
if (line.Equals("exit")) {
// exit the method.
return; // use "break" if you just want to exit the loop
}
// this is what will happen in the loop body since we didn't exit
// put whatever note stuff you want to execute again and again in here
}您需要编辑这个循环正文中的内容,具体取决于您想要对便笺实例做什么。但是通常情况下,您会反复提示用户输入,直到满足某些条件,然后才退出循环。你可以决定这个条件(例如“输入10条音符”;“输入出口”等)。
发布于 2017-09-01 15:01:31
Per @n0rd的评论,下面是do...while循环的工作方式:
string input;
var myNotes = new List<Note>();
do{
input = Console.ReadLine();
if (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)){
var note = new Note();
note.addText(input);
myNotes.Add(note);
}
} while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase));https://stackoverflow.com/questions/32363719
复制相似问题