我试图掌握一个基本的Java概念,但无法弄清楚为什么我的方法未执行。我想从单词兔子中打印出substring
,如果它超过3个字符,否则打印出原始字符串。我的代码:
package com.company;
public class Main {
static String bunny = "bunny";
public static String subStringBunny(String bunny) {
if (bunny.length() > 3) {
bunny = bunny.substring(2, 4);
}
return bunny;
}
public static void main(String[] args) {
System.out.println("this is substring from bunny: " + bunny);
}
}
它仍然会打印原始字符串,因此我想
subStringBunny
方法不会得到执行。任何帮助将不胜感激!谢谢! 最佳答案
您不是从subStringBunny
方法调用main
方法。此代码应执行您要实现的目标:
package com.company;
public class Main {
static String bunny = "bunny";
public static String subStringBunny (String bunny) {
if (bunny.length() > 3) {
bunny = bunny.substring(2,4);
}
return bunny;
}
public static void main(String[] args) {
System.out.println("this is substring from bunny: " + Main.subStringBunny(bunny));
}
}
关于java - 方法未执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46226577/