使用构造函数作为方法参数

时间:2014-03-29 22:34:33

标签: java methods arraylist parameters constructor

我正在编写一个将构建SQL表create语句的类。我想做的是调用类似createTable(String tableName ColAndTypes... ct )的方法。当我编写方法时,我没有得到任何编译错误。当我调用它时,我在将值传递给方法时遇到了麻烦,我认为这是因为我的语法错误而且我不确定如何修复它。我想知道你是否可以查看我提供的示例,让我知道我需要做些什么来解决它。非常感谢你的帮助!

import java.util.*;
public class foo
{
public class bar{
    public String sBar1, sBar2;
    public bar(){
        sBar1 = "null";
        sBar2 = "null";
    }
    public bar(String sBar1, String sBar2){
    this.sBar1 = sBar1;
    this.sBar2 = sBar2;
    }
}

String sFoo;
List<bar> bi;

public foo(){
    sFoo = "null";
    bi = new bar();
}
public foo(Strinf sFoo, bar bi){
    this.sFoo = sFoo;
    this.bi = bi;
}

public void runFooBar(String sFoo, bar... barArgs)
{
    this.sFoo = sFoo;
    for(bar x:barArgs){System.out.Println(bi.get(x).sBar1   + ":" + bi.get(x).sBar2);}
}

public static void main(String[] args)  
{
    foo fi = new foo();
    fi.runFooBar("foo 1", ("1 sBar1","1 sBar2"),("2 sBar1 ","2 sBar2"))

}//end main

}//end class

1 个答案:

答案 0 :(得分:1)

我不完全确定你要做什么,但这会修复你的语法错误。

import java.util.ArrayList;
import java.util.List;

public class Foo {
    public static class Bar {
        public String sBar1, sBar2;

        public Bar(String sBar1, String sBar2) {
            this.sBar1 = sBar1;
            this.sBar2 = sBar2;
        }
    }

    String sFoo;
    List<Bar> bi;

    public Foo() {
        bi = new ArrayList<>();
    }

    public Foo(String sFoo, List<Bar> bi) {
        this.sFoo = sFoo;
        this.bi = bi;
    }

    public final void runFooBar(String sFoo, Bar... barArgs) {
        this.sFoo = sFoo;
        for (Bar x : barArgs) {
            System.out.println(x.sBar1 + ":" + x.sBar2);
        }
    }

    public static void main(String[] args) {
        Foo fi = new Foo();
        fi.runFooBar("foo 1", new Bar("1 sBar1", "1 sBar2"), new Bar("2 sBar1", "2 sBar2"));

    }//end main
}//end class