如何在 Java 上调用和打印来自另一个包的数组?

问题描述 投票:0回答:2
public void db_access() throws ClassNotFoundException, SQLException {
    // Declaring variables for used by :
    int id[] = new int[15];
    String[] title = new String[16];
    String genre[] = new String[16];
    BigDecimal price[] = new BigDecimal[16];
  }}

上面的代码来自类“db”上的包“db”。我如何(例如)在名为“main”的包和下面名为“start”的类上打印第二个“title”数组?

    public Start() {
    initComponents();
    db_connect();
}

我已经使用“import db.db;”导入了包

java arrays netbeans
2个回答
0
投票

你需要为此使用一个实例变量。可能你应该为变量提供一个“吸气剂”以便更好地封装。

package DB;

public class Db {

  private String[] title = new String[16];

  public String[] getTitles() {
    return title;
  }

  public void db_access() {
     title[0] = "ID";
     title[1] = "Name";
     // etc.
     // Note I do not re-declare "title" with "String []"
     // this uses the existing "title" already declared above
   }
}

0
投票

db_access() 是一个方法,你需要使用一个实例变量来调用这个

db db_v = new db();
db_v.db_access();

如果你只想打电话给“标题”

public String[] db_access() throws ClassNotFoundException, SQLException {
    // Declaring variables for used by :
    int id[] = new int[15];
    String[] title = new String[16];
    String genre[] = new String[16];
    BigDecimal price[] = new BigDecimal[16];
    return title;
  }

}

在主班

db db_v = new db();
String title[]  = db_v.db_access();
© www.soinside.com 2019 - 2024. All rights reserved.