我正在尝试掌握一个基本的Java概念,但我无法弄清楚为什么我的方法没有被执行。如果它有超过3个字符,我想从单词bunny打印出substring
,否则打印出原始字符串。我的代码:
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
方法不会被执行。任何帮助将不胜感激!谢谢!
答案 0 :(得分:3)
您没有从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));
}
}
答案 1 :(得分:1)
您没有调用该方法。你最多这样做:
System.out.println("this is substring from bunny: " + subStringBunny(bunny));