[英]C# Console User Input
好吧,我想首先说我不是学生所以这个问题与家庭作业完全无关。 我正在努力学习C#,因为我想要工作的公司使用它。 我听说C#与java非常相似所以我正在使用我的java书来解决运动问题来练习c#。 这是我的问题,我正在尝试创建一个简单的程序,用户输入3个等级并将其存储在一个数组中,然后显示输入的三个等级。 问题是它没有存储成绩。 然而它显示一些随机数,如果我输入34,44和54它返回51.这是我的代码并感谢大家:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Practice1
{
class Program
{
static void Main(string[] args)
{
int[] test = new int[4];
int i = 1;
for (i = 1; i <= 3; i++)
{
Console.WriteLine("Please enter test " + i);
test[i] = Console.Read();
Console.ReadLine();
}
for (i = 1; i <=3; i++)
{
Console.WriteLine(test[i]);
Console.ReadLine();
}
}
}
}
你的问题在这里:
test[i] = Console.Read();
这是将一个字符(这是一个整数字符代码)放入您的测试数组中。
相反
test[i] = int.Parse(Console.ReadLine());
编辑:如果你不确定用户会输入一个可解析的整数,也许他们会键入“six”,例如你可能会考虑使用try / catch(如果你想知道为什么它不会解析)或int.TryParse,返回true表示成功,并将解析后的整数分配给变量,字段或数组索引:
if(int.TryParse(Console.ReadLine(), out test[1])
Console.WriteLine("Successfully parsed integer");
else
Console.WriteLine("Please enter an integer.");
Console.Read()返回输入密钥的ASCII值。 例如,如果键入“A”,则得到值65,即“A”的ASCII码。
您需要将字符串解析为整数:
for (i = 0; i < 4; i++)
{
Console.WriteLine("Please enter test " + i);
string input = Console.ReadLine();
int value;
bool success = int.TryParse(input, out value);
if (success)
{
test[i] = value
}
else
{
// Show an error message that the user must enter an integer.
}
Console.ReadLine();
}
另请注意,数组在C#中以0开头编号,而不是代码假定的1。
或者,您仍然可以使用Console.Read (),它返回输入字符的整数表示形式,确认该字符实际上是一个数字,并从ASCII代码转换为适当的数字。
从文档 Console.Read()
“读取标准输入流中的下一个字符。”
你想要下一个Integer,就像这样
bool cont = false;
int val = 0;
do
{
cont = int.TryParse(Console.ReadLine(), out val);
if(!cont){Console.WriteLine( "please enter a real number you fool" );}
} while (!cont);
应该管用。
int[] test = new int[3];
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Please enter test " + i + 1);
test[i] = Int.Parse(Console.ReadLine());
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(test[i]);
Console.ReadLine();
}
如您所见,数组从索引0开始,因此不需要定义int [4](比需要的更多一个int),并且需要从索引0循环到length-1
问题是你正在读这个角色。 因此,您看到的“51”是数字3的十进制(基数10)ASCII值。您需要做的是以下内容:
string result = Console.ReadLine();
int grade = 0;
int.TryParse(result, out grade)
test[i] = grade;
Console.Read()
返回一个字符。 您希望从控制台读取string
,将其转换为int
,然后将该值存储在数组中。
这是代码:
int [] test = new int [3];
for (int e = 0; e < 3; e++)
{
Console.WriteLine("Please enter test ");
test[e] = int.Parse(Console.ReadLine());
}
Console.WriteLine("000000000000000000000000000\n");
for (int e = 0; e < 3; e++)
{
Console.WriteLine(test[e]);
//Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.