Parsing text file in java - Error - java

I am trying to remove errors in the following code.
package in.citydoor.imports.catalog.tools;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class Main {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String file_name="C:/aman/textfile.txt";
try {
CatFeedWriterToMemory obj = new CatFeedWriterToMemory(file_name);
String[] arryLines = obj.ReadFile();
/*
* int i;
* for(i=0;i<arryLines.length;i++){
* System.out.println(arryLines[i]);
* }
*/
} catch(IOException e) {
System.out.println(e.getMessage());
System.out.println("Keep file on specified path");
}
}
}
package in.citydoor.imports.catalog.tools;
import java.util.ArrayList;
public class CatFeedBean {
ArrayList<ProductVo> parsedList = new ArrayList<ProductVo>();
ArrayList<PriceVo> priceList = new ArrayList<PriceVo>();
ArrayList<SkuVo> SkuList = new ArrayList<SkuVo>();
**String[] columns = arryLines.split("/");**
String productid = columns[0];
String productname = columns[1];
String skuid = columns[2];
String price = columns[3];
ProductVo productObj = new ProductVo(productid,productname);
**parsedList.add(productObj);**
SkuVo skuObj = new SkuVo(skuid);
// SkuList.add(skuObj);
PriceVo priceObj = new PriceVo(price);
// priceList.add(priceObj);
}
package in.citydoor.imports.catalog.tools;
public class ProductVo {
private String product_id;
private String product_name;
public ProductVo(String i, String n) {
product_id = i;
product_name = n;
}
public String getProductId() {
return this.product_id;
}
public void setProductId(String product_id) {
this.product_id = product_id;
}
public String getProductName() {
return this.product_name;
}
public void setProductname(String product_name){
this.product_name = product_name;
}
}
1) For the line String[] columns = arryLines.split("/"); in main class,
I am getting error "arryLines cannot be resolved".
2). For line parsedList.add(productObj);" in CatFeedBean class,
I am getting error "Syntax error on token"productObj",VariableDeclaratorId expected after this token".

Yes,
The arryLines is a local variable in your Main class.
The code is not in a method, it is in the declaration part of the
class.

You should call the add-method inside of a method or constructor.
like:
public CatFeedBean() {
parsedList.add(productObj);
}
see stackoverflow.com/questions/17499455

Related

null output in multiple choice array

my output of my java application is running null values for the output of Q4 and 5, tried fixing it but had no luck swapping out the null values for the actual string question needed to be shown just before the user input
MultipleChoiceQuestions.java
import java.util.Arrays;
import java.util.Scanner;
public class MultipleChoiceQuestion extends Question{
private int count = 0 ;
private String cho1, cho2, cho3, cho4 ;
private boolean bool1, bool2, bool3, bool4 ;
private final String[] newchoice = new String[4];
public MultipleChoiceQuestion(String text, String cho1, boolean bool1,
String cho2, boolean bool2,
String cho3, boolean bool3,
String cho4, boolean bool4) {
super(text);
this.cho1 = cho1; this.cho2 = cho2;
this.cho3 = cho3; this.cho4 = cho4;
this.bool1 = bool1; this.bool2 = bool2;
this.bool3 = bool3; this.bool4 = bool4;
}
public void addChoice(String Choices, boolean isCorrect){
this.newchoice[count]= Choices;
if(isCorrect) {
super.setCorrectResponse(Choices);
}
count++ ;
}
public void initQuestion(){
addChoices(cho1, bool1);
addChoices(cho2, bool2);
addChoices(cho3, bool3);
addChoices(cho4, bool4);
}
#Override
public String toString(){
StringBuilder sbf = new StringBuilder(super.toString());
sbf.append(Arrays.toString(newchoice));
return sbf.toString();
}
private void addChoices(String cho1, boolean bool1) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
FillInTheBlankQuestion.java
import java.util.Scanner;
public class FillInTheBlankQuestion extends Question{
public FillInTheBlankQuestion(String text){
super(text);
}
public void extractQA(){
Scanner scan = new Scanner(super.getQuestionText());
scan.useDelimiter("_");
super.setQuestionText(scan.next());
super.setCorrectResponse(scan.next());
}
public String toString(){
return super.toString() + "______________";
}
}
Question.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* #author --
*/
public class Question {
private String questionText;
private String correctResponse;
//Creates a question with an empty question and answer
public Question(){
this.setQuestionText("");
this.setCorrectResponse("");
}
public Question(String text){
this.setQuestionText(text);
}
public Question(String text, String answer){
this.setQuestionText(text);
this.setCorrectResponse(answer);
}
//sets the text of this question
public void setQuestionText(String text){
this.questionText = text;
}
//sets the answer for this question
public void setCorrectResponse(String answer){
this.correctResponse = answer;
}
public String getQuestionText(){
return this.questionText;
}
public String getCorrectResponse(){
return this.correctResponse;
}
/*
checks the response/answer given for correctness
#param givenResponse The response to check
return true if the response is correct, false otherwise
*/
public boolean verifyAnswer(String givenResponse){
//it does not take into account upper/lower case characters.
return givenResponse.equalsIgnoreCase(this.getCorrectResponse());
}
//allows user to type the answer
public void inputAnswer(Scanner scan){
System.out.print("Type your answer:");
System.out.println(this.verifyAnswer(scan.nextLine()));
}
//display the question
#Override
public String toString(){
return this.getQuestionText();
}
}
QuestionTester.java
import java.util.Scanner;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
/**
*
* #author ---
*/
public class QuizTester {
public QuizTester(){
Scanner in = new Scanner(System.in);
//declare an array quiz that can hold a mixture of Question and Fill in blank type
Question[] quiz = new Question[6];
quiz[0] = new Question("Which class is used to get user input?", "Scanner");
quiz[1] = new Question("How many primitive data types are there in Java? Enter in words.", "eight");
quiz[2] = new FillInTheBlankQuestion("The inventor of Java was _James Gosling_");
quiz[3] = new FillInTheBlankQuestion("Every class in Java inherits from _Object_");
quiz[4] = new MultipleChoiceQuestion("What represents the collection of related data?",
"String", false,"Array", true, "Integer", false,
"Iterator", false);
quiz[5] = new MultipleChoiceQuestion("Which method does not belong to Scanner class?",
"nextInt()", false,
"next()", false,
"nextboolean()", false,
"nextChar()", true);
for(int i = 0; i < quiz.length; i++){
if(quiz[i] instanceof FillInTheBlankQuestion){
((FillInTheBlankQuestion)quiz[i]).extractQA();
}
System.out.println("Q" + (i + 1) + ": " + quiz[i].toString());
quiz[i].inputAnswer(in);
}
}
public static void main(String[] args) {
new QuizTester();
}
}
I thank you so much in advance

getting null values when trying to pass values to xml response in web service from model class

/**
* ConnectDB2.java , i'm fetching data from database and setting values to model class.
*/
package org.com.repair.spotify.repair.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.ws.rs.Path;
import org.com.repair.spotify.repair.model.RepairDetails;
/**
* #author www.javaworkspace.com
*
*/
#Path("/connectDB2")
public class ConnectDB2 {
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
String deviceName;
String deviceModel;
String ticketId;
String issue;
String deviceType;
public ConnectDB2() {
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection(
"jdbc:db2://localhost:50000/HELLO", "db2admin", "admin");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM DEVICE ");
while (resultSet.next()) {
System.out.println("DEVICE BRAND:" + resultSet.getString(1)
+ " || ISSUE: " + resultSet.getString(2) + " ||MODEL:"
+ resultSet.getString(3) + "||TYPE:"
+ resultSet.getString(4));
RepairDetails Rd = new RepairDetails();
Rd.setDeviceModel(resultSet.getString(1));
Rd.setIssue(resultSet.getString(2));
Rd.setDeviceType(resultSet.getString(3));
Rd.setDeviceType(resultSet.getString(4));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/RepairDetails.java==> my Model class/
package org.com.repair.spotify.repair.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class RepairDetails {
String deviceName;
String deviceModel;
String ticketId;
String issue;
String deviceType;
public RepairDetails() {
}
public RepairDetails(String deviceName, String deviceModel,
String ticketId, String issue, String deviceType) {
super();
this.deviceName = deviceName;
this.deviceModel = deviceModel;
this.ticketId = ticketId;
this.issue = issue;
this.deviceType = deviceType;
}
public String getDeviceName() {
System.out.println("getter" + deviceName);
return deviceName;
}
public void setDeviceName(String deviceName) {
System.out.println("setter" + deviceName);
this.deviceName = deviceName;
}
public String getDeviceModel() {
return deviceModel;
}
public void setDeviceModel(String deviceModel) {
System.out.println("setter" + deviceModel);
this.deviceModel = deviceModel;
}
public String getTicketId() {
return ticketId;
}
public void setTicketId(String ticketId) {
this.ticketId = ticketId;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
System.out.println("setter" + issue);
this.issue = issue;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
System.out.println("setter" + deviceType);
this.deviceType = deviceType;
}
}
//the service class from where i'm trying get values from model, but i'm fetching null value which is further passed on getRepairdetails()
package org.com.repair.spotify.repair.service;
import java.util.ArrayList;
import java.util.List;
import org.com.repair.spotify.repair.db.ConnectDB2;
import org.com.repair.spotify.repair.model.*;
public class RepairService {
public RepairService() {
ConnectDB2 db = new ConnectDB2();
}
public List<RepairDetails> getRepairService()
{
System.out.println("getRepairDetails-->2");
RepairDetails Rd = new RepairDetails();
System.out.println("hey im firing");
RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
"Mobile");
List<RepairDetails> list = new ArrayList<RepairDetails>();
list.add(RD1);
return list;
}
}
Kindly help me why null values are returned by getter ???
Let's start with examining the RepairDetails class. This one implements a POJO (Plain old Java object) and contains two constructors.
public RepairDetails()
public RepairDetails(String, String, String, String, String)
So when you create the object with the first constructor, that means you are not setting anything to the fields, that means that the values are initialized to null.
Now let's examine the RepairService class. There you have this code in the getRepairService() method.
RepairDetails Rd = new RepairDetails();
RepairDetails RD1 = new RepairDetails(Rd.getDeviceName(),
Rd.getDeviceModel(), Rd.getIssue(), Rd.getDeviceType(),
"Mobile");
List<RepairDetails> list = new ArrayList<RepairDetails>();
list.add(RD1);
Here we have the following observations:
Rd is an object created with the first constructor, so effectively the values in Rd will be null.
You are constructing RD1 with values got from Rd meaning that they will be null too.
I hope you get it now.

JAVA: JUNIT testing of class type with string

So I have a test which is to test the addNewCustomer method which does so by reading in from a text file
#Test
public void testAddNewCustomer() {
System.out.println("addNewCustomer");
try {
File nFile = new File("ProductData.txt");
File file = new File("CustomerData.txt");
Scanner scan = new Scanner(file);
ElectronicsEquipmentSupplier ees = new ElectronicsEquipmentSupplier(1, 1, InputFileData.readProductDataFile(nFile));
ees.addNewCustomer(InputFileData.readCustomerData(scan));
CustomerDetailsList expResult = ees.getDetails();
CustomerDetailsList result = ees.getDetails();
assertEquals(expResult, result);
} catch (IllegalCustomerIDException | IOException | IllegalProductCodeException e) {
fail(e.getMessage());
}
}
The problem that I'm having is to what to have as the expected result? I tried putting a string with the values that I thought would be entered but it then said I can't compare type string with type CustomerDetailsList. Any ideas?
public class CustomerDetailsList {
private final ArrayList<CustomerDetails> customerCollection;
public CustomerDetailsList() {
customerCollection = new ArrayList<>();
}
public void addCustomer(CustomerDetails newCustomer) {
customerCollection.add(newCustomer);
}
public int numberOfCustomers() {
return customerCollection.size();
}
public void clearArray() {
this.customerCollection.clear();
}
/**
*
* #param givenID the ID of a customer
* #return the customer’s details if found, exception thrown otherwise.
* #throws supplierproject.CustomerNotFoundException
*/
public CustomerDetails findCustomer(String givenID) throws CustomerNotFoundException {
CustomerNotFoundException notFoundMessage
= new CustomerNotFoundException("Customer was not found");
int size = customerCollection.size();
int i = 0;
boolean customerFound = false;
while (!customerFound && i < size) {
customerFound = customerCollection.get(i).getCustomerID().equals(givenID);
i++;
}
if (customerFound) {
return customerCollection.get(i - 1);
} else {
throw notFoundMessage;
}
}
#Override
public String toString() {
StringBuilder customerDets = new StringBuilder();
for (int i = 0; i < numberOfCustomers(); i++) {
customerDets.append(customerCollection.get(i).toString()).append("\n");
}
return customerDets.toString();
}
}
The list itself
Generally, you should test if the new customer is in the list. However, the expResult and result from your test are just the same, because at that point the ees already contains the new customer. Therefore the assertion does not make sense.
However, you can test if the Customer List contains the customer with given email (or some unique property of that customer).

Spring mvc, making a menu data object

I'm really a newbie to JAVA, spring mvc.
And my understanding for "code" is so poor that I can't even think of how I'm going to get through with upcoming errors.
So this question will sound like " Do this for me!". ( It will do, actually )
Anyway, I'm trying to make a two-depth menu. Its structure looks like this below.
TopMenu
::: menuNo
::: menuName
::: memberType
::: url
::: sort
::: subMenus
::: menuNo
::: menuName
::: memberType
::: url
::: sort
TopMenu2
::: menuNo2
::: menuName2
::: memberType2
::: url2
.
.
.
.
So I made a bean class for this.
public class MenuInfoBean {
private String menuNo;
private String menuName;
private String memberType;
private String url;
private int sort;
List<MenuInfoBean> subMenus;
public MenuInfoBean() {
}
public String getMenuNo() {
return menuNo;
}
public void setMenuNo(String menuNo) {
this.menuNo = menuNo;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getMemberType() {
return memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public List<MenuInfoBean> getSubMenus() {
return subMenus;
}
public void setSubMenus(MenuInfoBean subMenus) {
subMenus.menuName = subMenus.menuName;
subMenus.memberType = subMenus.memberType;
subMenus.url = subMenus.url;
subMenus.sort = subMenus.sort;
}
}
Which database will be used is not decided yet, so I'm temporarily using properties for menu data.
#TopMenu List
topmenu = M1000,M9000
#SubMenu List
M1000.submenu =
M9000.submenu = M9001,M9002,M9003,M9004
#TopMenu Info
#M1000 APPLICATION
M1000.menuName=APPLICATION
M1000.url=
M1000.memberType=00,10
M1000.sort=1
#M9000 ADMIN
M9000.menuName=ADMIN
M9000.url=/SYS01/memberList.mon
M9000.memberType=00,10
M9000.sort=1
#SubMenu Info
#M9000 ADMIN's
M9001.menuName=Member mgmt
M9001.url=/SYS01/memberList.mon
M9001.memberType=00,10
M9001.sort=1
M9002.menuName=menu2
M9002.url=/SYS01/memberList.mon
M9002.memberType=00,10
M9002.sort=1
M9003.menuName=menu3
M9003.url=/SYS01/memberList.mon
M9003.memberType=00,10
M9003.sort=1
M9004.menuName=menu4
M9004.url=/SYS01/memberList.mon
M9004.memberType=00,10
M9004.sort=1
And here I fetch the data and try to put them into a List.
public class MenuManager {
public List<MenuInfoBean> getMenus(String permissionCode) {
LabelProperties msgResource = LabelProperties.getInstance();
MenuInfoBean menuInfo = new MenuInfoBean();
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
String topMenu = msgResource.getProperty("topmenu");
String[] topMenuItems = topMenu.split(",");
for (int i = 0; topMenuItems.length > i; i++ ) {
String subMenuName = msgResource.getProperty(topMenuItems[i] + ".submenu");
if ( subMenuName.isEmpty() == false ) {
menuInfo.setMenuName(msgResource.getProperty(subMenuName + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(subMenuName + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(subMenuName + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(subMenuName + ".sort")));
menuInfo.setSubMenus(menuInfo);
} else {
menuInfo.setMenuName("");
menuInfo.setSubMenus(menuInfo);
}
menuInfo.setMenuNo("");
menuInfo.setMenuName(msgResource.getProperty(topMenuItems[i] + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(topMenuItems[i] + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(topMenuItems[i] + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(topMenuItems[i] + ".sort")));
menuList.add(menuInfo);
}
return menuList;
}
}
getProperty method works great. It gets the properties value correctly.
But as you may noticed, there's some null data is being made.
to ignore this NullPointerException, I made
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
So the exception has been successfully avoided. But another error comes up which isn't important in this post....
Anyway, while trying to solve the new error, I looked into the menuInfo data and found out something wrong was going on.
The subMenus was holding the topMenu's data!
Here's the question, How can I make this menu with MenuInfoBean like the structure I mentioned on the top of this post?
And why subMenus data was holding topMenu's properties?
I set subMenus data first, and topMenu data later! why this happens?
First of all I am updating the domain object by adding a additional method add(Meun)
import java.util.ArrayList;
import java.util.List;
public class MenuInfoBean
{
private String menuNo;
private String menuName;
private String memberType;
private String url;
private int sort;
List<MenuInfoBean> subMenus;
public MenuInfoBean()
{
}
public String getMenuNo()
{
return menuNo;
}
public void setMenuNo(String menuNo)
{
this.menuNo = menuNo;
}
public String getMenuName()
{
return menuName;
}
public void setMenuName(String menuName)
{
this.menuName = menuName;
}
public String getMemberType()
{
return memberType;
}
public void setMemberType(String memberType)
{
this.memberType = memberType;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public int getSort()
{
return sort;
}
public void setSort(int sort)
{
this.sort = sort;
}
public List<MenuInfoBean> getSubMenus()
{
return subMenus;
}
// This is new method added to the bean
public void addSubMenuItem(MenuInfoBean menuInfoBean)
{
if (subMenus == null)
subMenus = new ArrayList<MenuInfoBean>();
subMenus.add(menuInfoBean);
}
}
Here is the class that generate the menu and return (look at the get menu method):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class MenuExtractionComponent
{
public List<MenuInfoBean> getMenus(String permissionCode)
{
LabelProperties msgResource = LabelProperties.getInstance();
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
String topMenu = msgResource.getProperty("topmenu");
List<String> topMenuItems = new ArrayList<String>();
// Checking is top menu empty
if (StringUtils.isNotBlank(topMenu))
{
topMenuItems.addAll(Arrays.asList(topMenu.split(",")));
}
for (String topMenuItem : topMenuItems)
{
// Setting top menu details
MenuInfoBean menuInfo = new MenuInfoBean();
menuInfo.setMenuNo("");
menuInfo.setMenuName(msgResource.getProperty(topMenuItem + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(topMenuItem + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(topMenuItem + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(topMenuItem + ".sort")));
String subMenu = msgResource.getProperty(topMenuItem + ".submenu");
List<String> subMenuItems = new ArrayList<String>();
// Checking is sub menu empty
if (StringUtils.isNotBlank(subMenu))
{
subMenuItems.addAll(Arrays.asList(subMenu.split(",")));
}
for (String subMenuItem : subMenuItems)
{
MenuInfoBean subMenuInfo = new MenuInfoBean();
subMenuInfo.setMenuName(msgResource.getProperty(subMenuItem + ".menuName"));
subMenuInfo.setMemberType(msgResource.getProperty(subMenuItem + ".memberType"));
subMenuInfo.setUrl(msgResource.getProperty(subMenuItem + ".url"));
subMenuInfo.setSort(Integer.parseInt(msgResource.getProperty(subMenuItem + ".sort")));
menuInfo.addSubMenuItem(subMenuInfo);
}
menuList.add(menuInfo);
}
return menuList;
}
}

using a multi-dimensional array returned from method that pulls from sql database

I am trying use a from a multi-dimensional array that I create in another classes method. Below is my main method:
public class main {
public static void main(String[] args) throws Exception {
sql test = new sql();
String[][] test2 = test.getDb();
System.out.print(test2[0][0]);
}
Now here is the class that returns an multi-dimensional array.
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import com.mysql.jdbc.Statement;
public class sql {
java.sql.Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:8889/deliveryEarn";
String user = "root";
String password = "root";
ArrayList<String> sqlCol1 = new ArrayList<String>();
ArrayList<String> sqlCol2 = new ArrayList<String>();
ArrayList<String> sqlCol3 = new ArrayList<String>();
ArrayList<String> sqlCol4 = new ArrayList<String>();
ArrayList<String> sqlCol5 = new ArrayList<String>();
ArrayList<String> sqlCol6 = new ArrayList<String>();
ArrayList<String> sqlCol7 = new ArrayList<String>();
String sqlArray[][] = new String[7][7];
public sql() {
}
public String[][] getDb() {
try {
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("select * from incomeCalc");
rs = pst.executeQuery();
while (rs.next()) {
sqlCol1.add(rs.getString(1));
int i1=0;
for(String s: sqlCol1){
sqlArray[i1++][0] = s;
}
sqlCol2.add(rs.getString(2));
int i2=0;
for(String s: sqlCol2){
sqlArray[i2++][1] = s;
}
sqlCol3.add(rs.getString(3));
int i3=0;
for(String s: sqlCol3){
sqlArray[i3++][2] = s;
}
sqlCol4.add(rs.getString(4));
int i4=0;
for(String s: sqlCol4){
sqlArray[i4++][3] = s;
}
sqlCol5.add(rs.getString(5));
int i5=0;
for(String s: sqlCol5){
sqlArray[i5++][4] = s;
}
sqlCol6.add(rs.getString(6));
int i6=0;
for(String s: sqlCol6){
sqlArray[i6++][5] = s;
}
sqlCol7.add(rs.getString(7));
int i7=0;
for(String s: sqlCol7){
sqlArray[i7++][6] = s;
}
}
}
catch( Exception E ) {
System.out.println( E.getMessage() );
}
return sqlArray;
}
}
Here is the screenshot of the MySQL database.
Edit: It appears I wasn't clear with my question. I apologize. I am getting a runtime error at this line:
System.out.print(test2[0][0]);
What am I doing wrong? Also, for correct OOP, is it better to use a constructor or a method to pull from or input to a database? THis is my first program so sorry if it seems trivial.
Edit2: Here is the error:
Exception in thread "main" java.lang.NullPointerException
at main.main(main.java:17)
As to why you've got an error, it would be nicer to know the error, however...
Personally, I'd drop the contents of the result set into a "Data Object"...
public class Income {
// Column decelerations...
private long id;
private int tips;
private int hours;
private int gas;
private double hourly;
private double other;
private double other2;
public int getGas() {
return gas;
}
public double getHourly() {
return hourly;
}
public int getHours() {
return hours;
}
public long getId() {
return id;
}
public double getOther() {
return other;
}
public double getOther2() {
return other2;
}
public int getTips() {
return tips;
}
public void setGas(int gas) {
this.gas = gas;
}
public void setHourly(double hourly) {
this.hourly = hourly;
}
public void setHours(int hours) {
this.hours = hours;
}
public void setId(long id) {
this.id = id;
}
public void setOther(double other) {
this.other = other;
}
public void setOther2(double other2) {
this.other2 = other2;
}
public void setTips(int tips) {
this.tips = tips;
}
}
Then when you load it you could do something like...
public Income[] getIncome() {
// Call database...
List<Income> data = new ArrayList<Income>(25);
while (rs.next()) {
Income income = new Income();
income.setID(rs.getInt(1)));
income.setTips(rs.getInt(2)));
income.setHours(rs.getInt(3)));
income.setGas(rs.getInt(4)));
income.setHourly(rs.getDouble(5)));
income.setOther(rs.getDouble(6)));
income.setOther2(rs.getDouble(7)));
data.add(income);
}
return data.toArray(new Income[data.size()]);
}
The you could do things like this...
sql test = new sql();
Income[] incomes = test.getIncome();
System.out.println(incomes[0].getID());
Isn't that easier to read :P
Your attempt to use a Factory is probably the best idea. It comes down to a matter of management as to weather you maintain a single instance (Singlton) or allow multiple instances of this Factory to be created. Personally, I prefer to use Singltons in this case where I can, it allows a centralised place to perform operations (saving changes, creating new objects, listing, deleting) and helps manage the resources involved. IMHO

Categories