2014-09-12 157 views
-2

我仍然与局部变量的范围相混淆 此代码不起作用,因为我在“i & n”未解析。我已经确定它作为循环int i = 0。这不够吗? (这是加上字符串的第n个字符)。局部变量的范围

public String everyNth(String str, int n) { 
    String result = ""; 

    for (int i = 0; i <= str.length(); i++); { 
     if (i%n == 0) { 
      result = result + str.charAt(i); 
     } 
     else { 
      result = result; 
     } 
    } 
    return result;   
} 
+3

那是什么'else'语句的意义呢? – Gary 2014-09-12 19:38:00

+12

在大括号之前,你在'for'“标题”末尾有一个分号。摆脱它。 – 2014-09-12 19:40:30

+0

他们回答你的问题吗? – Rika 2014-09-12 20:06:23

回答

1

要在乔恩斯基特的回答值得评论扩大,分号在for (int i = 0; i <= str.length(); i++);末结束的语句,而我是在范围上不再分号之后。

+0

“;”是我的代码中的重大错误。我明白了,这是一个很好的帮助! – 2014-09-12 20:15:40

1

你有几个误区:

  1. 可以删除其他{...}部分,因为你并不需要它。

  2. 您有额外的';'在for循环语句中。

  3. for循环的索引有错误。您需要执行'i小于'str.length(),而不是i < = str.length()。基本上你的for循环将尝试访问你的字符数组的全长索引,但实际上它超出了长度。例如,字符串'hello'的索引是0,1,2,3,4。但是“hello”.length()实际上是5.如果您尝试访问字符串的第5个索引,您将看到一个'java.lang.StringIndexOutOfBoundsException'异常。

此外,你想要的每一个第N个值,你想要做的(i-1)%n。这又是因为索引问题。尝试在你的逻辑中插入参数,并用铅笔写下结果,你就会明白为什么。

当然,当我== 0,你不想(0-1)%n发生。因此,通过添加'i!= 0'来跳过i == 0。

现在,以下是工作代码:

public static String everyNth(String str, int n) { 
    String result = ""; 
    for (int i = 0; i < str.length(); i++) { 
     if ((i-1)%n == 0 && i!=0) 
      result = result + str.charAt(i); 
    } 
    return result;   
} 
+0

这是一个很好的帮助!谢谢!!! – 2014-09-12 20:16:11