【发布时间】:2019-06-17 15:49:37
【问题描述】:
所以我正在做一个在线编码挑战,并遇到了这个让我难过的问题:
这是我的代码:
static void Main(String[] args)
{
int noOfRows = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < noOfRows; i++)
{
string odds = "";
string evens = "";
//get the input word from console
string word = Console.ReadLine();
for (int j = 0; j < word.Length; j++)
{
//if the string's current char is even-indexed...
if (word[j] % 2 == 0)
{
evens += word[j];
}
//if the string's current char is odd-indexed...
else if (word[j] % 2 != 0)
{
odds += word[j];
}
}
//print a line with the evens + odds
Console.WriteLine(evens + " " + odds);
}
}
本质上,问题是要我从控制台行获取字符串并在左侧打印偶数索引字符(从 index=0 开始),然后是空格,然后是奇数索引字符。
所以当我尝试使用“Hacker”这个词时,我应该会看到该行打印为“Hce akr”。当我调试它时,我看到代码成功地将字母'H'放在左边(因为它是index = 0,因此是偶数),并将字母'a'放在右边(奇数索引)。但是当它到达字母“c”时,它没有通过第一个 IF 路径(偶数索引),而是跳过它并进入奇数索引路径,并将其放在右侧?
有趣的是,当我尝试使用“Rank”这个词时,它可以正常工作并打印出正确的语句:“Rank”,而其他词却没有。
奇怪的是我得到了不同的结果。
我错过了什么?
【问题讨论】:
-
注意:
if (someCondition) { } else if (!someCondition) { }是多余的。您可以删除第二个if,但保留else,例如if (someCondition) { } else { } -
if(j % 2 == 0) evens += word[j]; else odds += word[j]; -
@Cid:谢谢,有道理——因为我正在试验,我只是修改了它以尝试不同的东西来使它工作
标签: c# for-loop if-statement