因此,我正在进行在线编码挑战,遇到了困扰我的问题:
这是我的代码:
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'放在左侧(因为它的索引= 0,因此是偶数),而在字母'a'的右侧(奇数索引)。但是,当到达字母“ c”时,它没有经过第一个IF路径(偶数索引),而是跳过了它,转到了奇数索引路径,并将其放在右侧?
有趣的是,当我尝试使用“排名”一词时,它可以正常工作并显示正确的语句:“排名”,而其他单词则不能。
奇怪的是我得到了不同的结果。
我想念什么?
答案 0 :(得分:6)
word[j]
是您字符串中的字符; j
是您要检查其均匀度的索引。
答案 1 :(得分:3)
if (j%2)
应该提供正确的路径。您正在使用if( word[j] %2)
,它对字符而不是索引进行模运算。最有可能在ASCII值上使用模。希望这会有所帮助。
答案 2 :(得分:1)
您要检查索引是否为偶数,但要比较不是索引的word[j] % 2 == 0
。
您应该做什么:
if(j % 2 == 0){
}