I'm trying to pass a string array from one class to another in my java code. By using code such as
Class instanceofclass = new Class();
String text1 = instanceofclass.variablename;
and then displaying it out on screen worked fine!
However I'm trying to get the array of a string. So in my first class I have
JButton [] FilmTime = new JButton[5];
JButton [] FilmNames = new JButton[8];
String [] films = new String [8];
DbConnector dataBase = new DbConnector();
for (int i =0; i <= 7; i++)
{
films[i] = dataBase.FilmTitle[i];
}
for (int i =0; i<= 7; i++)
{
FilmNames[i] = new JButton (films[i] + " ("+age+")");
FilmNames[i].setPreferredSize(new Dimension(563,50));
grid.add(FilmNames[i]);
}
I know I can use one for loop but I was just checking issues at the momment.
In my second class used named dbconnector i have:
public String FilmTitle [];
for (int i =0; i<=7; i++)
{
String query = "SELECT * FROM films WHERE ID =" + i;
Rs = St.executeQuery(query);
while (Rs.next())
{
FilmTitle[i] = Rs.getString("FilmName");
}
}
Eclipse gives the error as:
Error is: java.lang.NullPointerException
java.lang.NullPointerException
at main.init(main.java:46)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Line 46 is the statement in the first for loop...
testingme[i] = instanceofclass.variablename[i];
You have to initialize string array.
String[] testingme = new String[8];
Related
This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}
My array has an unfixed size as it depends on the user input for the number of modules entered so I really don't know what to do when I run this code and got this error: ArrayIndexOutOfBoundsException: 0
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
//Method for input of number of modules
moduleno = Student.modno();
for (int i = 0; i < moduleno; i++) {
modulename = Student.MakingModName(i);
grade = Student.readGrade(i);
cu = Student.readCredits(i);
value = Student.GradeValue(grade);
score = Student.calculateScore(value, cu);
totalScore += score;
totalCu += cu;
GPA = Student.calculateGPA(totalCu, totalScore);
//Error occurs here.
**array[i] = new Module(modulename,grade,cu);**
a[i] = array[i].getModulename();
b[i] = array[i].getGrade();
c[i] = array[i].getCu();
Output[i] = a[i] + " " +b[i]+" " +c[i]+" ";
endoutput = endoutput + Output[i] + "\n";
}
This sequence of statements:
Module[] array = new Module[moduleno];
moduleno = Student.modno();
does not magically resize the array that has been allocated previously. You need to do it the other way round:
moduleno = Student.modno();
Module[] array = new Module[moduleno];
Move the statement
moduleno = Student.modno(); // this should be the value while you initialize the array
before you initialize your arrays.
//Add This line before initialize your array
**moduleno = Student.modno();**
Module[] array = new Module[moduleno];
String[] a = new String[moduleno];
String[] b = new String[moduleno];
int[] c = new int[moduleno];
String[] Output = new String[moduleno];
String endoutput="";
Reason :
By default your moduleno variable contains 0(Zero) size so your all arrays size is also 0(Zero).
And you try to add 1 element in array but size of array is zero so it gives ArrayIndexOutBoundsException.
I have an ArrayList as shown below
import java.util.ArrayList;
public class Mann {
public static void main(String args[]) {
ArrayList<String> billOrderList = new ArrayList<String>();
list.add("VAT");
list.add("Discount");
list.add("SERVICE CHARGE");
StringBuilder select_query = new StringBuilder();
select_query.append("Select ");
for (int i = 0; i < billOrderList.size(); i++) {
if (i != billOrderList.size() - 1) {
select_query.append("" + billOrderList.get(i) + " , ");
} else {
select_query.append("" + billOrderList.get(i) + "");
}
}
select_query.append(" From VENDOR_ITEMS WHERE vendor_items_id = "
+ vendor_item + "");
VendorItems_Pstmt = dbConnection.prepareStatement(select_query
.toString());
VendorItems_RSet = VendorItems_Pstmt.executeQuery();
while (VendorItems_RSet.next()) {
String tax_name = VendorItems_RSet.getString();
}
}
}
How can i give the column name which is dynamic in this case in line VendorItems_RSet.getString();??
You need as ResultSetMetaData to get the column name associated with your query result.
You can get ResultSetMetaData from ResultSet by using ResultSet.getMetaDate, you can iterate it and get column all column name.
ResultSetMetaData VendorItems_RSet_metaData = VendorItems_RSet.getMetaData();
int numberOfColumns = VendorItems_RSet_metaData .getColumnCount();
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
}
I think you need all column data for that you can iterate your loop like
while (VendorItems_RSet.next())
{
for(int i=1;i<=numberOfColumns;i++)
{
String columnName = VendorItems_RSet_metaData.getColumnName(i);
String tax_name = VendorItems_RSet.getString(columnName);
System.out.println(tax_name);
}
}
ResultSetMetaData resultSetMetaData = VendorItems_RSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String type = resultSetMetaData.getColumnTypeName(i); // Get Column type
String name= resultSetMetaData.getColumnName(i); //Column name
}
}
SELECT * and then
ResultSetMetaData metaData = VendorItems_RSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; ++i) {
System.out.println(metaData.getColumnName(1));
}
For the line data[] = {nam, addres, adminStaf, phoneNumbe, typ}; NetBeans gives me this error
"; Expected Not a statement"
I don't know why this is not working, help will be appreciated.
public Object[] getObjects() {
Object[] data = {};
for (int i = 0; i < Storage.getAgencies().size(); i++)
{
String nam = Storage.getAgencies().get(i).getName();
String addres = Storage.getAgencies().get(i).getAddress();
String adminStaf = Storage.getAgencies().get(i).getAdminstaff();
String phoneNumbe = Storage.getAgencies().get(i).getPhonenumber();
String typ = Storage.getAgencies().get(i).getType();
data[] = {nam, addres, adminStaf, phoneNumbe, typ};
}
return data;
}
The syntax you're using is only allowed when initializing an array. You should do the following instead:
data = new String[] {nam, addres, adminStaf, phoneNumbe, typ};
is there any way to convert array list to json store input data using jsp and java for extjs.
means i need to get data for json store from jsp page and java arraylis
Here you go hope this helps you... Here im getting state values from db..
String response = "id,State#";
List stateList = new ArrayList<>();
//DB call
for (int i = 0; i < stateList.size(); i++) {
response += stateList.get(i).gets_code() + ",";
response += stateList.get(i).getS_name() + "#";
}
StringTokenizer st = new StringTokenizer(response , "|");
String finalMsg = null;
String str1 = null;
while (st.hasMoreElements()) {
String token = st.nextToken();
finalMsg = token;
}
JSONObject object = new JSONObject();
stbuffer.append("{\"root\":[");
String[] data = finalMsg.split("#");
int len = data.length;
String[] headings = data[0].split(",");
for (int x = 1; x < len; x++) {
String[] data1 = data[x].split(",");
int len1 = data1.length;
for (int y = 0; y < len1; y++) {
object.put(headings[y], data1[y]);
}
stbuffer.append(object);
stbuffer.append(",");
}
stbuffer.append("]}");
String result = stbuffer.toString();
result = result.replace(",]", "]");