如何在具有用户输入的数组中添加? [英] How do I add at an array with user input?

查看:40
本文介绍了如何在具有用户输入的数组中添加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的小程序,将数组添加到数组然后打印所有字符串。事实证明,这很简单,因为我甚至无法将字符串添加到数组中!每当我尝试这个时它会编译但是在我给出任何输入的那一刻就会崩溃。



我尝试过的事情:



I am trying to make a simple little program that adds strings to an array then print all the strings. Turns out to be anything but simple because I can't even seem to add the strings to the array! Every time I try this it compiles but crashes the moment I give any input.

What I have tried:

using System;
public class Practice
{

    static void Main()
    {
        int x=0; //num of words
        string[] str = new string[x];
        string ec = "not q"; //exit clause
        for(x=0; ec != "q"; x++)
        {
            str[x] = Console.ReadLine();
            ec = Console.ReadLine();

        }
    }

    

}

推荐答案

在C#中声明一个数组时,你必须指定大小;在上面的代码中,你必须将数组初始化为某个大小。



In C# when you declare an array , you have to specify the size; In the above code you have to initialize your array to some size .

string[] str = new string[10];





当你初始化一个大小为零的数组时,它会创建一个空的数组对象。



这里我初始化数组大小为10。在for循环中,可能是你可以检查数组长度,并根据检查你可以声明一个所需大小的新数组并复制内容将原始数组放入新数组。



再次有像Array.Resize这样的方法构建。

Array.Resize(T)方法(T [],Int32)(系统) [ ^ ]


Quote:

我正在尝试使用控制台输入向数组添加字符串。我还没有打印到阵列中。

I am trying at add strings to an array using console input. I haven't gotten to the print out of the array yet.



参考这个简单的例子




refer this simple example

System.Console.WriteLine("Enter 5 words");
       string[] array = new string[5];
       for (int i = 0; i < 5; i++)
       {
           array[i] = System.Console.ReadLine(); // read the line and stores in array
       }
       System.Console.WriteLine("press any key to print words");
       System.Console.ReadLine();
       foreach (string item in array)
       {
           System.Console.WriteLine(item);  // print each item from the array
       }
       System.Console.ReadLine();


为什么不使用 List

例如

Why don't you use a List, instead?
E.g.
public static void Main()
{
  List<string> strlist = new List<string>();
  string str;
  while (true)
  {
    Console.WriteLine("please enter a string ('q' to exit");
    str = Console.ReadLine();
    if (str == "q") break;
    strlist.Add(str);
  }

  Console.WriteLine("Entered string count = {0}", strlist.Count);
  foreach (string s in strlist)
  {
    Console.WriteLine(s);
  }
}


这篇关于如何在具有用户输入的数组中添加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆