[英]Multiple strings at one index of an array list
我這里有兩個字符串的構造函數:
public class person
{
String first;
String last;
public person (String first, String last)
{
this.first = first;
this.last = last;
}
public String toString()
{
String result = first + "\n";
result += last + "\n";
return result;
}
}
還有一個用於創建構造函數的兩個對象的main方法:
import java.util.ArrayList;
public class k
{
public static void main (String[] args)
{
ArrayList<person> list = new ArrayList<person>();
person ken = new person ("Ken", "Smith");
person ben = new person ("Ben", "Smith");
list.add (ken);
list.add (ben);
System.out.println (list.get(0));
}
}
現在,該代碼顯示了Ken Smith。 我的問題是:我怎樣才能只打印Ken而不是Ken Smith?
按照約定,Java類名稱以大寫字母開頭。 接下來,覆蓋toString()
以同時打印兩個名稱。 對於名字,您將添加一個吸氣劑(在本示例中,我也為姓氏添加了一個吸氣劑)
public class Person {
String first;
String last;
public Person(String first, String last) {
this.first = first;
this.last = last;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String toString() {
String result = first + "\n";
result += last + "\n";
return result;
}
}
然后,您可以通過以下方式(在main
)致電
System.out.println (list.get(0).getFirst());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.