将值读入Array

时间:2014-02-06 01:05:19

标签: c#

该程序询问用户数组大小,然后要求用户输入数组值。我遇到的问题是读取数组值的for循环无法正常工作。无论n的价值是多少,它都会要求更多的投入。

int n;

Console.WriteLine("Enter how many values you are entering in");
n = Convert.ToInt32(Console.Read());

int[] arr = new int[n];
Console.WriteLine("Enter your values in");

for (int i = 0; i < n; i++)
{
    arr[i] = Convert.ToInt32(Console.Read());
}

7 个答案:

答案 0 :(得分:3)

快速简便的修复:

使用int.Parse(Console.ReadLine())代替Convert.ToInt32(Console.Read())

<强>解释

您获得的ASCII值与您的方式相同。例如,如果您输入数字2,则n变量实际上已设置为50

答案 1 :(得分:0)

使用ReadLine()获取数字,然后在输入chararcters时使用ReadKey()而不是Read()或ReadLine()

int n;

Console.WriteLine("Enter how many values you are entering in");
n = Convert.ToInt32(Console.ReadLine());

int[] arr = new int[n];
Console.WriteLine("Enter your values in");

for (int i = 0; i < n; i++)
{
  char c = Console.ReadKey().KeyChar;
  arr[i] = Convert.ToInt32(c.ToString());
}

答案 2 :(得分:0)

使用Console.ReadLine()代替Console.Read()

如记录here,Console.Read()仅返回一个字符。您可能希望读取整行并解析整数值。

此代码应该按您的要求执行:

int n;

Console.WriteLine("Enter how many values you are entering in");
//n = Convert.ToInt32(Console.Read());
n = Int32.Parse(Console.ReadLine());

int[] arr = new int[n];
Console.WriteLine("Enter your values in");

for (int i = 0; i < n; i++)
{
    arr[i] = Int32.Parse(Console.ReadLine());
}

这也适用于n = 10的输入情况。

答案 3 :(得分:0)

这是一个具有更强大错误检查功能的版本。 注意:(直接输入,不运行,所以如果有轻微的语法错误,我道歉)

        int count;

        bool attemptedSetCount = false;
        do
        {
            if (attemptedSetCount)
            {
                Console.WriteLine("Please enter a valid integer");
            }
            Console.WriteLine("Enter how many values you are entering in");
            string countString = Console.ReadLine();
            attemptedSetCount = true;
        }
        while (!Int32.TryParse(countString, out count));

        int[] arr = new int[n];
        Console.WriteLine("Enter your values in");

        for (int i = 0; i < count; i++)
        {

            string valString = (Console.ReadLine());
            int val;
            if(!Int32.TryParse(valString, out val))
            {
                Console.WriteLine("Please enter a valid integer");
                i--;
            }
            else
            {
                arr[i] = val;
            }
        }

答案 4 :(得分:0)

for (int i = 0; i < n; i++)
{
     string value = Console.ReadLine();
     int result;
     if (int.TryParse(value, out result)) arr[i] = result;
     else
     {
         Console.WriteLine("Invalid value try again.");
         i--;
     }
}

答案 5 :(得分:0)

Console.Read函数读取输入的下一个单个字符,并将其作为int值返回。然后代码将其传递给Convert.ToInt32 API,它将基本上返回传入的确切值。这意味着像1这样具有字符值49的数字将被处理为{ {1}}。这就是你的代码读取如此多的值的原因

要正确阅读49中的数字,请使用返回Console的{​​{1}}方法。然后,可以将其传递给ReadLine并转换为String

Int32.Parse

或者更好的是,将其抽象为方法

int

答案 6 :(得分:0)

Have you read the documentation

  

Read方法在您输入输入字符时阻止其返回;   按Enter键时它会终止。按Enter键附加一个   依赖于平台的线路终端序列到您的输入(例如,   Windows附加一个回车换行序列)。 后续调用   Read方法一次检索输入一个字符。最后一个   检索到字符,Read再次阻止其返回并重复循环。

     

请注意,除非您执行其中一项,否则不会获得-1的属性值   以下操作:同时按下Control修饰键和Z控制台   键(Ctrl + Z),表示文件结束条件;按一个等效键   表示文件结束条件的信号,例如Windows中的F6功能键;   或者将输入流重定向到具有实际值的源(例如文本文件)   文件结束符。

     

ReadLine方法,或KeyAvailable属性和ReadKey方法   最好使用Read方法。

如果我执行此代码:

Console.Write("? ") ;
int input = Console.Read() ;
Console.WriteLine("You entered {0}.", input ) ;
Console.WriteLine( "{0} is the decimal code point for the character whose glyph is '{1}.'" , input , (char)input ) ;

如果我在?提示符下输入字符123,后跟return键:

? 123<return>

我会看到这个输出:

You entered 49.
49 is the decimal code point for the character whose glyph is '1'.

[请注意>在Windows中,您可以通过按住<ALT>键,在命令提示符处生成'1',输入'0049 and releasing the`键。

假设意图是让用户指定要输入的值的数量,然后提示他们输入那么多输入值,你想要的代码看起来像这样:

static void Main()
{
  int   n      = ReadIntegerFromConsole( "How many values do you want to enter?" ) ;
  int[] values = new int[n] ;

  for ( int i = 0 ; i < values.Length ; ++i )
  {
    string prompt = string.Format( "{0}/{1}?" , i , n ) ;

    values[i] = ReadIntegerFromConsole(prompt) ;

  }

  Console.WriteLine( "You entered: {0}" , string.Join(", ",values) ) ;
  return ;
}

static int ReadIntegerFromConsole( string prompt )
{
  int  value   ;
  bool isValid ;

  do
  {

    Console.Write( prompt) ;
    Console.Write( ' ' );

    string text = Console.ReadLine() ;

    isValid = int.TryParse(text, out value ) ;

    prompt = "That's not an integer. Try again:" ;
  } while (!isValid) ;

  return value ;
}
相关问题