-4

我可以在主课上做这样的事情吗?

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?"

如果是,我可以再次显示消息但不影响来自另一个对象的变量,例如 o2?

4

1 回答 1

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;
    }
}
于 2013-03-12T06:32:46.593 回答