首先是关于我的项目的一些信息,
我正在关注一个教程任务,主要目标是学习使用错误处理,
但我还没有到那个阶段,我正在努力建立主要类(class)。
这就是我需要一点帮助和指导的地方,(但错误应该会出现并被检测到
这样我以后可以学会修复它们,但这不是这里的主要问题,只是信息。)
这是我完成的 3 门类(class)。
具有两个私有(private)字段的学生:姓名和 CourseCollection 类(class)。
名称包含两个字段 String firstName 和 String surname。
CourseCollection 与 ArrayList 类(class)。
(信息:稍后,我将使用 UserDatabase 类来收集和加载学生的集合,
+ 表示错误的类 DatavaseFormatException,但我认为先完成上述 3 个类会更容易吗?纠正我,如果
我错了。)
问题:我需要一些关于类(class)名称的帮助,我认为我的工作不正确。
我的主要问题是字符串编码方法和构造函数名称(字符串编码身份)
我想返回名称的地方,用 ; 分隔。这就是我所拥有的
enter code here
public class Name
//instanciating the persons first and last name as Strings.
private String firstName;
private String surname;
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
firstName = this.firstName;
surname = this.surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
//Here, the name is supposed to be coded as a text value, with the first
//and last names split with a ;
this.encodedIdentity=encodedIdentity;
//I am getting my first error here
}
//这里的名字和姓氏的getter
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
//Could I use a split String here? If so how?
return firstName + ";" + surname;
}
}
我可以保证我的工作需要进一步的帮助。提前谢谢,我找到了
StackOverflow 上的人非常有帮助,因为我没有任何人(除了我的书)
寻求帮助。 (我知道你们不是免费的老师。但如果有人愿意在这之外帮助我,我将不胜感激。
(对不起,如果不允许要求!))
编辑:谢谢你们,我的课现在正在编译。我还不确定如何测试它,但这就是我现在所拥有的。它看起来正确吗?
public class Name
{
/**
* Constructor for objects of class Name- setting the text values for a name
*/
public Name(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
/**
* Constructor for objects of class Name- reconstructing the fields
* from a coded name
*/
public Name(String encodedIdentity)
{
String names = firstName + surname;
String[] fullname = names.split( "\\;");
if(fullname.length != 2 )
{
System.out.println(fullname);
}
}
/**
* Getting the firstname of the person
* @return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Getting the surname of the person
* @return surname
*/
public String getSurname()
{
return surname;
}
/**
* This method will return the name, with the first and last name split
* by a ;
*/
public String encode()
{
String encode = (firstName + ";" + surname);
return encode;
}
}
最佳答案
如果给您一个“编码的 id”,请将其拆分以获取名称:
public Name(String encodedIdentity){
String[] names = split( ";", encodedIdentity );
if( names.length != 2 ) throw new IllegalArgumentError("...");
firstName = names[0];
surname = names[1];
}
不存储可以指定对象属性的所有变体。因此,不应该有字段codedIdentity。
关于java - 如何在 Java 中使用拆分字符串重建名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377347/