java 查找字符串长度是奇数还是偶数的程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27207889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Program to find if a string length is odd or even
提问by Certus
I am creating a program to find out if a string that is entered has an odd or even amount of characters. I am having trouble with the runner class, because whenever I enter a string, it just prints it back and doesn't carry out the different methods that I have in my main class. How do I call for the methods in the runner class?
我正在创建一个程序来确定输入的字符串是否包含奇数或偶数个字符。我在使用 runner 类时遇到了问题,因为每当我输入一个字符串时,它只会将其打印回来,并且不会执行我在主类中拥有的不同方法。如何调用 runner 类中的方法?
MAIN CLASS:
主要课程:
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());
}
}
回答by Elliott Frisch
You aren't instantiating (or calling anything in) your stringoddoreven
class (which should be camel case, like StringOddOrEven
)
你没有实例化(或调用任何东西)你的stringoddoreven
类(应该是驼峰式的,比如StringOddOrEven
)
System.out.println(new stringoddoreven(word)); // <-- will call toString on
// your instance