c# - 如何在 C# for 循环中使用 var?
问题描述
我试图学习编程并从基础开始,但无法弄清楚。我试图使用我的用户输入 var 数量并获取用户输入文本值并在 for 循环中使用它。
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("URL To ICMP: ");
var url = System.Console.ReadLine();
System.Console.WriteLine("How many times do you want to ping " + url + "?");
var amount = System.Console.ReadLine();
Ping myPing = new Ping();
PingReply reply = myPing.Send(url);
for (int i = 0; i < amount; i = i + 1)
{
System.Console.WriteLine();
if (i = amount)
{
break;
System.Console.WriteLine("\nFinished ICMP");
}
}
}
}
解决方案
您的代码有一些问题。不过,要首先回答您的问题,您需要将 ping 向下移动到循环中。其余的我会在评论中注明:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("URL To ICMP: ");
var url = System.Console.ReadLine();
// Use String.Format instead of concatenation.
System.Console.WriteLine(String.Format("How many times do you want to ping {0}?", url));
var amount = System.Console.ReadLine();
int count;
if(!int.TryParse(amount, out count)) // You should attempt to convert to integer.
{
// If invalid, notify user and return.
Console.WriteLine("Invalid number!");
return;
}
Ping myPing = new Ping();
for (int i = 0; i < count; i++) // use the `count` variable.
{
System.Console.WriteLine(String.Format("Pinging host: {0}...", url));
// You can use PingReply below to write the response
// If you do not plan to use that, I would omit the set here
// and just use `myPing.Send(url);`
PingReply reply = myPing.Send(url);
// This next section you do not need as the loop will automatically break
// after the set number of iterations.
// if (i = amount) // this should actually be `==` instead of `=`
// {
// break;
// System.Console.WriteLine("\nFinished ICMP");
// }
}
}
}
推荐阅读
- excel - 使用事件方式读取 xlsx 文件时如何评估公式单元格使用 ApachePOI
- iphone - 在核心位置框架中打开/关闭硬件模块
- javascript - DataTables - 如何从特定行获取单元格?
- amazon-web-services - 如何将 aws 设备场集成到 Java 代码中,例如 browserstack
- php - PHP PCRE2 没有更多内存
- java - 如何在java中获取泛型接口的类型
- rest - 我应该如何更改 Hazelcast 集群的生存时间属性?
- python - 如何在数字列表中找到最多的因子?
- sql - Impala/SQL 如何将所有其他字段放在 group by 语句中?
- python - 使用 python 保护套接字免受 DOS 和 DDOS