所以我有一个程序来询问(输入(东西(变量整数字符串等(。然后这些元素传递给构造函数。但是,每次我输入新值时,以前的值都会被覆盖。如何让它创建一个新值而不是覆盖以前的值?我对Java很陌生,我有点困惑。这是我的代码:
Scanner scan1 = new Scanner(System.in); //user input the name
System.out.print("name: n");
String name = scan1.nextLine();
然后将其传递给构造函数:
Balloon aballoon = new Balloon(name);
我的构造函数看起来像
public Balloon(String name){
setName(name);
及其方法
public String thename
public void setName(String name){
if(name.matches("[a-zA-Z]+$")){
thename = name;
}
所以是的,我想知道如何构建多个对象(字符(覆盖前一个对象,以及如何存储它们(字符(。
谢谢
ArrayList<Balloon>
来存储多个Balloon
对象:
ArrayList<Balloon> baloons = new ArrayList<Balloon>;
//Read name
baloons.add(new Balloon(name));
//baloons now contains the baloon with the name name
有关如何使用 ArrayList
类的详细信息,请参阅 类 ArrayList<E>
。
我会使用类似于以下内容的循环来存储用户想要的所有气球:
List<Balloon> balloonList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String prompt="Name?(Enter 'done' to finish inputting names)";
System.out.println(prompt); //print the prompt
String userInput=input.nextLine(); //get user input
while(!userInput.equals("done")){ //as long as user input is not
//"done", adds a new balloon
//with name specified by user
balloonList.add(new Balloon(userInput));
System.out.println(prompt); //prompt user for more input
userInput=input.nextLine(); //get input
}
对于修改,我将假设您希望使用其名称(IE:如果有人想删除/修改名称为"bob"的气球,它将删除/修改 ArrayList 中名为"bob"的(第一个(气球。
对于删除,很简单 - 编写一个简单的方法来查找指定的气球(如果它在列表中(并将其删除。
public static boolean removeFirst(List<Balloon> balloons, String balloonName){
for(int index=0;index<balloons.size();index++){//go through every balloon
if(balloons.get(index).theName.equals(balloonName){//if this is the ballon you are looking for
balloons.remove(index);//remove it
return true;//line z
}
}
return false;
}
此方法将查找按名称指定的 Balloon 并删除它的第一个实例,如果它实际找到并删除了气球,则返回 true,否则将其删除。如果要删除该名称的所有气球,可以在方法的开头创建一个布尔值 b 并将其设置为 false。然后,您可以将 z 行更改为
b=true;
然后在方法的底部,返回 b。
现在,通过编辑,您可以表示两件事之一。如果你打算修改气球的实际名称,你可以使用一个循环,就像我上面做的那个,当你找到它时修改名称,你可以让它修改所有具有该名称的气球,或者只修改你找到的第一个气球。
或者,如果通过修改气球,您打算将 ArrayList 中的气球替换为具有不同名称的新气球,则需要使用以下方法:
balloons.remove(i);//remove balloon at index
balloons.add(i,newBalloon);//put the new balloon(with different data) at the index of the old one