我试图编写一个包含两个类的Java程序:Dog和一个驱动程序类Kennel。
狗包含以下信息:
狗有以下方法:
我在尝试弄清楚如何为validName执行方法时遇到问题。谁能指出我正确的方向?我也可以这样说或不同的方法吗?代码附在下面。
package lab101;
public class Dog
{
public enum TailType
{
LONG, SHORT, NONE
}
private int age;
private float weight;
private String name;
private String bark;
private boolean hairLength;
private TailType tail;
//Default Constructor--> initializes an object (called once)every constructor
//must initialize all the classes attributes!!
public Dog()
{
age = 0;
weight = 0;
name = "";
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//Overloaded constructor (must have an argument)
public Dog(String theName)
{
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//If the name contains non-alphabetic characters
private boolean validName(String str)
{
str = str.toLowerCase();
if (str.length() <= 0)
{
}
return false;
}
//Computes the dog's age in human years.
public int humanAge()
{
int theAge = 7 * age;
return theAge;
}
//Returns the value of bark if true
public String(speak)
{
return bark;
}
//Method: <privacy: (private, public)> <return-type (data type or void)> <methodName>(<argument>){
// <body>
// return
// }
public String toString()
{
String str = "";
str += "Name: " + name;
str += "Weight: " + weight;
str += "Bark: " + bark;
str += "Hair Length: " + hairLength;
str += "Tail: " + tail;
str += "Age: " + age;
return str;
}
}
答案 0 :(得分:0)
我无法弄清楚如何为validName执行此方法。
假设您的validName方法通过检查是否只存在字母来检查是否给出了有效名称:
//Return true if name is valid
private boolean validName(String str)
{
if(str == null || str.length() == 0)
return false;
return str.toLowerCase().matches("[a-z]+"); //Name only has a-z(A-Z)
}
我也是以同样的方式说话吗?
好吧,我不知道你的意思是什么&#34;同样的方式&#34;。但你说话方法不正确。
根据您的描述,它应该是:
public String speak(){
return bark;
}
你没有问过什么,但可以做得更好:
您正在实施两次类构造函数。您可以像这样调用构造函数:
public Dog(){
this(""); //invoke Dog(String)
}
public Dog(String theName){
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
上述效果与您所做的相同,但这是首选。
答案 1 :(得分:0)
如果您不了解正则表达式,也可以这样做:
private boolean validName(String str)
{ char[] letters = str.toUpperCase().toCharArray();
for(int i = 0 ; i < letters.length; i++){
int oneLetter = (int) letters[i];
if( !(oneLetter > 64 && oneLetter < 91)) // letters as ASCII for A-Z
return false; // if anyone is not A-Z then return false
}
return true; // if every letter is valid then return true
}