[英]Using a for loop to allow the user to put in an input from 1-100
只是從for循環開始,我對此問題有些困惑。 在下面的代碼中,我能夠創建一個大小為4的數組。我需要能夠允許用戶放入4個不同的整數(范圍為1-100)並將其存儲在數組中。
我還需要確保用戶輸入的任何內容都不小於0或大於100。在這種情況下,我正在考慮使用try-catch方法。 在for循環中可能嗎? 請指教:
const int SIZE = 4;
int[] array = new int[SIZE];
int numberOfTests = 4;
for (int count = 0; count < numberOfTests; count++) // Start the count from 0-4
{
int min = 0;
int max = 100;
Console.WriteLine("Please enter test score " + count);
}
我會根據我想您要執行的操作將其更改為:
const int SIZE = 4;
int[] array = new int[SIZE];
int numberOfTests = 4;
for (int count = 0; count < numberOfTests; count++) // Start the count from 0-4
{
int min = 0;
int max = 100;
int countf = count + 1;
Console.WriteLine("Please enter test score " + countf);
int a = Convert.ToInt32(Console.ReadLine());
if (a > 0 && a < 101)
{
array[count] = a;
}
}
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine(array[0]);
Console.WriteLine(array[1]);
Console.WriteLine(array[2]);
Console.WriteLine(array[3]);
Console.ReadLine();
Try and catch不是用於測試輸入條件的,即if語句適用的條件。 嘗試捕獲是否要測試該代碼是否可以運行以及是否無法提供替代方法。 因此,例如,如果用戶輸入了字符串,則try and catch語句將停止程序崩潰。 希望這可以幫助
const int numberOfTests = 4;
int[] array = new int[numberOfTests];
for (int count = 0; count < numberOfTests; count++)
{
Console.WriteLine("Please enter test score " + count);
try
{
int answer = Convert.ToInt32(Console.ReadLine());
if (answer > 0 && answer < 101)
array[count] = answer;
else Console.WriteLine("Please provide a value between 1-100");
}
catch
{
Console.WriteLine("Please provide an integer");
}
}
我假設您知道如何在“正確的情況”下使用try-catch。 在考慮使用try catch方法時,您似乎需要捕獲每個輸入異常。 在這種情況下,我建議為您定義一個新的整數類。 因為您想使用try-catch。 對於輸入數據超出范圍或期望的范圍,拋出異常。 代碼將如下所示:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class MyInt
{
public MyInt(int i)
{
Data = i;
}
private int _data;
public int Data
{
get => _data;
set
{
if(value<0||value>100)throw new ArgumentOutOfRangeException();
_data = value;
}
}
}
public static void Main()
{
MyInt[] array = new MyInt[4];
int min = 0;
int max = 100;
for (int count = 0; count < array.Length; count++) // Start the count from 0-4
{
Console.WriteLine("Please enter test score " + count);
try
{
array[count] = new MyInt(int.Parse(Console.ReadLine()));
}
catch (Exception exception)
{
Console.WriteLine($"Input exception :{exception}/n, Please input a valid number between {min} and {max}");
count--;
}
}
Console.WriteLine($"The array result here, eg. Sum of all :{array.Sum(i=>i.Data)}");
Console.ReadKey();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.