2015-01-20 75 views
0

为什么下面的代码不适用于这里的问题? http://codingbat.com/prob/p101475初学者字符串操作

public String frontTimes(String str, int n) { 
    if (str.length() < 3) { 
    String front = str; 
    } else { 
    String front = str.substring(0, 3); 
    } 
    String copies = ""; 

    while (n > 0) { 
    copies = copies + front; 
    n = n - 1; 
    } 

    return copies; 


} 

我真的不明白“前不能得到解决”的错误我得到

+0

因为你定义了'if'内'字符串前...'声明,Java会在它离开该代码块时立即销毁它。所有你需要做的就是把'String front =“”;'放在'if'之前的一行。 – Jon 2015-01-20 18:44:51

回答

3

您的变量的作用域front是只在if/else块。您可能需要尝试在if之前声明变量front,然后在if之内进行分配。

0

您声明front作为您的if块的局部变量,然后作为else子句的(另一个)局部变量。您必须在方法块的范围内声明它。

public String frontTimes(String str, int n) { 
    String front; 
    if (str.length() < 3) 
     front = str; 
    else 
     front = str.substring(0,3); 
    // or shorter, with a ternary 
    // String front = str.length() < 3 ? str : str.substring(0, 3); 

    String copies = ""; 
    while (n > 0) { 
    copies = copies + front; 
    n = n - 1; 
    } 
    return copies; 
} 
1

Java中变量的scope仅限于声明变量的花括号集。

如果您声明一个变量是这样的:

if (str.length() < 3) { 
    String front = str; 
} 

然后front只有if块的花括号内的存在。

当你这样做:

else { 
    String front = str.substring(0, 3); 
} 

然后另一个变量,也称为front,你else块的花括号内的存在。

但是,如果在if块之前声明变量:

String front; 
if (str.length() < 3) { 
    front = str; 
} else { 
    front = str.substring(0, 3); 
} 

那么它是在范围为整个方法(因为这是大括号的周围集)。

或者,你可以使用ternary operator简化您的变量初始化:

String front = (str.length() < 3 ? str : str.substring(0, 3)); 
0

问题是作用域规则。类似String front的字段仅在{ }内部可见。

我建议你先试着在IDE中编译代码,因为这会帮助你解决这些错误。

您可能会觉得这个解决方案很有趣。它迭代O(log N)次而不是O(N)次。 (我怀疑这是不是更好,而是以不同的方式瓜分的问题)

public String frontTimes(String str, int n) { 
    if (str.length() > 3) str = str.substring(0, 3); 
    StringBuilder sb = new StringBuilder(); 
    StringBuilder sb2 = new StringBuilder(str); 
    while (n > 0) { 
    if ((n & 1) == 1) 
     sb.append(sb2); 
    n /= 2; 
    sb2.append(sb2); 
    } 
    return sb.toString(); 
} 
0

试试这个:

public String frontTimes(String str, int n) { 

    String front; 

    if (str.length() < 3) { 
    front = str; 
    } 

    else { 
    front = str.substring(0, 3); 
    } 

    String copies = ""; 

    for (int i = 0; i < n; i++) { 
    copies += front; 
    } 

    return copies; 

}