c# - 存储来自用户输入的信息的数组
问题描述
C# - 我正在尝试编写一个数组来存储来自用户输入的信息。在我的代码中,我使用了一个我命名为朋友的字符串数组,然后我继续使用此方法https://stackoverflow.com/a/230463/14764548。最后,我希望控制台应用程序将存储的信息显示为数组。
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace arraysTut
{
class arraysTut
{
static void Main()
string[] friends = new string[2];
for(string i=0;i<friends.length;i++)
{
Console.WriteLine("First Friend: ");
friends[i] = Console.ReadLine();
Console.WriteLine("Second Friend: ");
friends[i] = Console.ReadLine();
Console.WriteLine(friends);
Console.ReadLine();
}
}
}
解决方案
Apart from a few minor issues, you were nearly there
var friends = new string[2];
for (var i = 0; i < friends.Length; i++)
{
Console.Write($"Enter friend ({i + 1}) : ");
friends[i] = Console.ReadLine();
}
Console.WriteLine();
Console.WriteLine("These are your friends");
foreach (var friend in friends)
Console.WriteLine(friend);
Console.WriteLine("Game Over!");
Output
Enter friend (1) : bob
Enter friend (2) : john
These are your friends
bob
john
Game Over!
It's worth noting, List<T>
are good a match for these types of situations, you don't have to worry about indexes, and can just expand and add to the list with List.Add(something)
推荐阅读
- android - 在我的 Android 应用中播放没有播放器视图的 HLS 广播
- android - 应用程序被 logcat 中的此消息冻结“超时等待 IME 在 2500 毫秒后处理输入事件”
- java - JavaFX - 如何在按钮单击时禁用 TreeTableView 列或单元格子节点
- r - 同一地块中四组的密度图
- postgresql - 为什么在 PostgreSQL 中使用窗口函数时可以嵌套聚合函数?
- postgresql - 在 AWS 上的 Ubuntu18 上安装 postgres
- sql - 在 Oracle SQL developer 中使用触发器
- graphql - 使用 graphql/nexus/prisma/yoga 时避免大量嵌套 SQL 查询
- node.js - Do I have to add await when I call async function?
- bash - 如何将环境变量设置为包含 bash 空格的部分路径