我可以在主类中做这样的事吗?
Scanner sc = new Scanner(System.in);
System.out.println("message 1");
int nbre1 = sc.nextInt();
sc.nextLine();
System.out.println("message 2");
int nbre2 = sc.nextInt();
sc.nextLine();
System.out.println("message 3");
int nbre3 = sc.nextInt();
sc.nextLine();
Obj o = new Obj(nbre1, nbre2, nbre3);
// print a message "do you want to create another object?"
如果是,我可以再次显示消息但不影响来自其他对象的变量,例如O 2→
答案 0 :(得分:0)
您可以在函数中编写上述代码并在循环中调用该函数。 像这样......
List<Obj> objects = new ArrayList<Obj>();
while(true){
Obj o = new Obj();
boolean continueBool = readInputs(o);
objects.add(o);
if(!continueBool){
break;
}
}
private boolean readInputs(Obj o){
// code to read inputs and create Obj object. If the user wants to create more objects, return TRUE else return FALSE
Scanner sc = new Scanner(System.in);
System.out.println("message 1");
int nbre1 = sc.nextInt();
sc.nextLine();
System.out.println("message 2");
int nbre2 = sc.nextInt();
sc.nextLine();
System.out.println("message 3");
int nbre3 = sc.nextInt();
// set values nbre1, nbre2 and nbre3 to 'o'
System.out.println("Do you want to repeat ?");
String inStr = sc.nextLine();
if(inStr.equalsIgnoreCase("yes")) {
return true;
} else {
return false;
}
}