我对编程和编码很陌生,而我最近刚刚开始参加一周前的计算机科学工程课程。出于某种原因,我继续在int32.parse行中获得系统格式异常。我不明白我做错了什么。如果可以的话请帮忙。我的任务是:
我的代码如下:
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Please enter your name: ");
string name;
name = Console.ReadLine ();
Console.WriteLine ("Hello, " + name);
int score;
Console.Write ("What are your last three test scores: ");
score = Int32.Parse(Console.ReadLine ());
Console.WriteLine("Your test scores are" + score + "90,92,95");}
}
答案 0 :(得分:0)
Console.Readline()
返回一个字符串。在您的情况下,此字符串可能类似于"96,92,99"
。
string inputs = Console.ReadLine();
第一步是使用逗号作为分隔符将字符串拆分为三个字符串,如"96"
,"92"
,"99"
string[] parts = input.Split(',');
现在每个字符串需要逐个转换为整数
// Create array of integers with the same size as the array of parts
int[] grades = new int[parts.Length];
// Loop through the input parts and convert them into integers
for(i=0; i<parts.Length; i++)
{
// Use `TryParse()` as it wont throw an Exception if the inputs are invalid
int.TryParse(parts[i], out grades[i]);
}
现在你可以做一些事情来计算平均值。我更喜欢使用内置函数,例如.Average()
或.Sum()
Console.WriteLine("The average grade is " + grades.Average().ToString("F1"));
您可以使用string.Join()
函数将值数组合并到逗号分隔的字符串中。
Console.WriteLine("I parsed these values: " + string.Join(",", grades));
因此,例如,如果输入无效,您将看到0
代替无效值。这是一个示例控制台输出。
Enter grades separated by commas: 92,A,96,94 I parsed these values: 92,0,96,94 The average grade is 70.5
要使用一个语句将字符串数组转换为整数数组,请使用LINQ
。
int[] grades = parts.Select((part) => int.Parse(part)).ToArray();
这将是一个无效输入的例外。使上述内容与TryParse()
一起使用非常棘手,但可行。
答案 1 :(得分:0)
检查用户输入以避免因无效输入而导致的异常非常重要。以下是我将如何做到这一点:
class MainClass
{
public static void Main(string[] args)
{
//Variable Declarations
string response,
name;
string[] scores;
int sumOfAllScores,
scoreCount;
bool validResponse;
System.Text.RegularExpressions.Regex onlyDigits;
//We need to assign response an initial value or else Visual Studio will complain
//since it only receives its real value within a while loop (which as far as the parser is concerned
//may or may not ever iterate.
response = string.Empty;
//Booleans are automatically assigned an intial value of 'false' but I like to intialize them anyway
validResponse = false;
//Initialize the score sum and score counter variables.
sumOfAllScores = 0;
scoreCount = 0;
//This Regex pattern will allow us to inspect a string to ensure that it contains only digits.
onlyDigits = new System.Text.RegularExpressions.Regex(@"^\d+$");
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
//This loop will iterate until the user provides valid input (comma-separated integers).
while (!validResponse)
{
//When we enter the while loop, set validResponse to true.
//If we encounter any invalid input from the user we will set this to false so that
//the while loop will iterate again.
validResponse = true;
Console.Write("What are your last three test scores (comma-separated list, please): ");
response = Console.ReadLine();
//Split response into an array of strings on the comma characters
scores = response.Split(',');
//Inspect each element of the string array scores and take action:
foreach (string scoreEntry in scores)
{
//If the current array member being inspected consists of any characters that are not integers,
//Complain to the user and break out of the foreach loop. This will cause the while loop to iterate
//again since validResponse is still false.
if (!onlyDigits.IsMatch(scoreEntry))
{
//Complain
Console.WriteLine("Invalid response. Please enter a comma-separated list of test scores");
Console.WriteLine(Environment.NewLine);
//Re-initialize the score sum and score count variables since we're starting over
sumOfAllScores = 0;
scoreCount = 0;
//Set validResponse to false and break out of the foreach loop
validResponse = false;
break;
}
//Otherwise, we have valid input, so we'll update our integer values
else
{
//Iterate the number of scores that have been entered and validated
scoreCount++;
//Use the static Convert class to convert scoreEntry to an Integer
//and add it to the score sum
sumOfAllScores += Convert.ToInt32(scoreEntry);
}
}
}
//Report the results to the user:
Console.WriteLine("Your test scores are: " + response);
Console.WriteLine("Your average score is " + sumOfAllScores / scoreCount);
}
}