![](/img/trans.png)
[英]C# - Recreating Battleship within a console app. Where do I call a method in this situation?
[英]I need to output only the last int that is printed out in this console app. I'm using a foreach loop. C# console app
我正在嘗試對字符串中每個字符的 ASCII 值求和。 打印出來的最后一個數字是我唯一想要顯示的數字。 因此,如果我輸入“chris”,我將返回 99、203、317、422 和 537。537 是我想要顯示的正確值,如何僅打印出 537?
using System;
namespace BLConsoleApp
{
class Program
{
static void Main(string[] args)
{
bool executeLoop = true;
while (executeLoop)
{
Console.WriteLine("Please enter a word for the sum of it's ASCII value !!!");
Console.WriteLine("Type the word 'exit' at any time to escape ...");
string word = Console.ReadLine();
if (word != "EXIT" || word != "Exit" || word != "exit")
{
int sum = 0;
foreach (char c in word)
{
sum += c;
Console.WriteLine((int)sum);
}
}
if (word == "EXIT" || word == "Exit" || word == "exit")
{
executeLoop = false;
return;
}
}
}
}
}
您可以簡單地將WriteLine
放在循環之后,因此它只寫入最終和。 此外,您可以只使用true
作為循環的條件,因為return
會立即跳出循環。 此外,您可以使用string.Equals
方法進行不區分大小寫的比較:
while (true)
{
Console.WriteLine("Please enter a word for the sum of it's ASCII value !!!");
Console.WriteLine("Type the word 'exit' at any time to escape ...");
string word = Console.ReadLine();
if (word.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
return;
}
int sum = 0;
foreach (char c in word)
{
sum += c;
}
Console.WriteLine(sum);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.