我正在创建一个程序来查明输入的字符串是否有奇数或偶数字符。我在跑步者课上遇到了麻烦,因为每当我输入一个字符串时,它就会将其打印回来并且不会执行我在主课程中使用的不同方法。我如何调用runner类中的方法?
主要课程:
import static java.lang.System.*;
import java.util.Scanner;
public class stringoddoreven
{
private String word;
public stringoddoreven()
{
setString("");
}
public stringoddoreven(String s)
{
setString(s);
}
public void setString(String s)
{
word = s;
}
public boolean isEven()
{
if (word.length() % 2 == 0)
return true;
return false;
}
public String toString()
{
if (isEven())
return word + " is even.";
return word + " is odd. ";
}
}
RUNNER CLASS:
import static java.lang.System.*;
import java.util.Scanner;
public class stringrunner
{
public static void main ( String[] args )
{
Scanner keyboard = new Scanner(in);
System.out.print("Enter a String :: ");
String word = keyboard.next();
System.out.println(word.toString());
}
}
答案 0 :(得分:2)
你没有实例化(或调用任何内容)你的stringoddoreven
类(应该是驼峰案例,如StringOddOrEven
)
System.out.println(new stringoddoreven(word)); // <-- will call toString on
// your instance