Java 避免覆盖构造函数内容
因此,我有一个程序,要求(输入)输入内容(变量int string等),然后这些元素被传递给构造函数。然而,每次我输入新值时,以前的值都被覆盖。我如何使它创建一个新值而不是覆盖以前的值?我对Java非常陌生,我有点困惑。下面是我的代码:Java 避免覆盖构造函数内容,java,methods,input,constructor,getter-setter,Java,Methods,Input,Constructor,Getter Setter,因此,我有一个程序,要求(输入)输入内容(变量int string等),然后这些元素被传递给构造函数。然而,每次我输入新值时,以前的值都被覆盖。我如何使它创建一个新值而不是覆盖以前的值?我对Java非常陌生,我有点困惑。下面是我的代码: Scanner scan1 = new Scanner(System.in); //user input the name System.out.print("name: \n"); String name = scan1.nextL
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> baloons = new ArrayList<Balloon>;
//Read name
baloons.add(new Balloon(name));
//baloons now contains the baloon with the name name
ArrayList baloons=新的ArrayList;
//读名字
baloons.add(新气球(名称));
//baloons现在包含名为的baloon
有关如何使用
ArrayList
类的更多信息,请参阅。我将使用类似于以下内容的循环来存储用户想要的所有引出序号:
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
}
然后在方法的底部,返回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
你可以使用阵列你能告诉我怎么做吗?就像我说的,我是一个初学者,但我以后需要能够检索/删除/编辑字符——数组是否只是在其中转储一堆数据?因为如果这样做了,我将无法检索特定元素?首先,我建议使用除Character以外的类名,因为这是一个java包装类(已经使用过),可能会导致混淆;事实上,当我第一次读到这篇文章时,我感到非常困惑。另外,当你编写程序时,你知道你需要生成多少个“字符”吗?或者它会根据不同的东西而改变吗?这不是真正的类名,我只是为了隐私而更改了它(后期编辑以便于阅读)。我必须能够输入我想要的任意多的“气球”,没有限制。我发布了一个答案,解释了如何创建和使用ArrayList,以及如何迭代该ArrayList来修改/删除数据。但正如我回复kirbyquerby时所说,我需要能够检索/修改/删除特定元素——数组是否允许这样做,或者只是一堆无序数据?是的,您可以检索,在
ArrayList
s中修改和删除对象。这都在文档中。还有一件事,为什么当我试图打印创建的对象(aballoon)时,它会打印类似于“Balloon@4554617c“?如何使它打印对象值而不是此(名称)您现在打印的只是abalon
对象,但我假设您要打印它的名称。要打印出abaloon
的名称,请调用System.out.println(abaloon.name)
.Oops,将字段命名为thename
。因此,请改用System.out.println(abaloon.thename)
;然而,我的情况可能会在这里引起问题;我要求一个阳台,但在我要求一个颜色和数字之后。所以颜色和数字需要分配给正确的气球;你能考虑一下这一点来编辑你的代码吗?Thanks将名称、颜色和数字存储在临时变量中,然后在完成所有变量的传入后,使用这些变量创建一个气球。我不会为你写所有的代码,但我可以告诉你怎么做。
b=true;
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