如何从用户那里获取任意数量的输入并将其放入 C# 中的 "params" 方法中?



所以我们可以给一个方法任意数量的参数,像这样:

static int sumPrices(params int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
int total = sumPrices(100, 50, 200, 350);
Console.WriteLine(total);
Console.ReadKey();
}

但是…如果我们想得到100 50 200 350呢?来自用户?在上面的例子中,它是给sumPrices方法的参数/参数的编码器。

我的意思是,这将是一个解决方案,只是传递一个数组的方法。

static int sumPrices(int[] prices) {
int sum = 0;
for (int i = 0; i < prices.Length; i++) {
sum += prices[i];
}
return sum;
}
static void Main(string[] args)
{
//get up to 9999 inputs and sum them using a method
bool whileLoop = true;
int[] inputs = new int[9999];
int index = 0;
while (whileLoop == true)
{
Console.WriteLine("entering price #" + index + ", type 'stop' to sum prices");
string check = Console.ReadLine();
if (check == "stop") {
whileLoop = false;
break;
}
inputs[index] = int.Parse(check);
index++;
}
int[] prices = new int[index];
for (int i = 0; i < index; i++)
{
prices[i] = inputs[i];
}
Console.WriteLine("-----------------");
Console.WriteLine(sumPrices(prices));
Console.ReadKey();

}

但是…长的代码…

我们的教授基本上想要第一个代码,然而,我不知道它是如何和在哪里如果我们不知道用户的输入,如果参数参数来自编码器(当然,除非编码器为了方便多次使用相同的函数),应该使用

我已经试着想了一个解决办法,但我不太确定该怎么做。但它基本上是这样的。我们可以从用户那里得到用逗号分隔的输入:

100200、50

,程序将其转换为参数:

sumPrices("100200年,50个");

但是你可以看到…它是一个字符串。我想知道是否有JSON.parse()之类的东西在js.

OP中的代码有一些不必要的代码以及9999等一些限制。

让我们检查下面的代码:

bool whileLoop = true;
while (whileLoop == true)
{
}

可以重写为:

while (true == true)
{
}

while (true)
{
}
接下来,让我们检查以下代码:
if (check == "stop") {
whileLoop = false;
break;
}

你已经设置了whileLoop = false;,这是不必要的,因为一旦break被执行,执行已经移动到循环之后。

由于输入数组的硬编码大小为9999,因此您将自己限制为9999个值。您可以考虑使用List或调整数组的大小。

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
namespace UserInputTest
{
internal class Program
{
static void Main(string[] args)
{
decimal price = 0;
List<decimal> _values = new List<decimal>();
if (args.Length == 0)
{
//prompts for user input
Console.WriteLine("The following program will sum the prices that are entered. To exit, type 'q'");
do
{
Console.Write("Please enter a price: ");
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q")
break; //exit loop
else if (Decimal.TryParse(userInput, out price))
_values.Add(price);  //if the user input can be converted to a decimal, add it to the list
else
Console.WriteLine($"Error: Invalid price ('{userInput}'). Please try again.");
} while (true);
}
else
{
//reads input from command-line arguments instead of prompting for user input
foreach (string arg in args)
{
if (Decimal.TryParse(arg, out price))
{
//if the user input can be converted to a decimal, add it to the list
_values.Add(price); //add
}
else
{
Console.WriteLine($"Error: Invalid price ('{arg}'). Exiting.");
Environment.Exit(-1);
}  
}
}

Console.WriteLine($"nThe sum is: {SumPrices(_values)}");
}
static decimal SumPrices(List<decimal> prices)
{ 
return prices.Sum(x => x);
}
static decimal SumPricesF(List<decimal> prices)
{
decimal sum = 0;
foreach (decimal price in prices)
sum += price;
return sum;
}
}
}

用法1:

UserInputTest.exe

使用2:

UserInputTest.exe 1 2 3 4 5

:

  • 内置类型(c#参考)
  • 浮点数值类型(c#引用)
  • 小数。TryParse
  • 迭代语句——for、foreach、do和while
  • 使用$
  • 进行字符串插值<<li>列表类/gh>
  • 可点数的。求和方法
  • c#类型的默认值(c#参考)
  • 环境。退出

关键在于用户的输入总是以字符串开头. 您必须将这些字符串解析为整数。我们可以用很短的代码来实现,像这样:

static int sumPrices(IEnumerable<int> prices) 
{
return prices.Sum();
}
static void Main(string[] args)
{
int total = sumPrices(args.Select(int.Parse));
Console.WriteLine(total);
Console.ReadKey();
}

请看这里(对沙箱环境进行了调整):

https://dotnetfiddle.net/Pv6B6e

注意,这里假设一个完美的打字员。如果提供的值不能解析,则不会进行错误检查。

但是我怀疑在早期的学校项目中使用linq操作是预期的,所以我们可以稍微扩展一下,只使用更熟悉的技术:

static int sumPrices(int[] prices) 
{
int total = 0;
foreach(int price in prices)
{
total += price;
}
return total;
}
static void Main(string[] args)
{
int[] prices = new int[args.Length];
for(int i = 0; i<args.Length; i++)
{
prices[i] = int.Parse(args[i]);
}
int total = sumPrices(prices);
Console.WriteLine(total);
Console.ReadKey();
}

如果你也不允许使用int.Parse()(这是坚果,但有时家庭作业有奇怪的限制),你会保持其他一切相同,但用你自己的ParseInt()方法替换int.Parse():

static int ParseInt(string input)
{
int exponent = 0;
int result = 0;
for(int i = input.Length -1; i>=0; i--)
{
result += ((int)(input[i]-'0') * (int)Math.Pow(10, exponent));    
exponent++;
}
return result;
}

再次说明:对于越界或非数字输入,这里没有错误检查,并且这个特殊的实现只适用于正整数。

最新更新