Error in IndexOutOfBoundsException using Loop from Database another class Java - java

I'm getting an java.lang.IndexOutOfBoundsException. This is my code:
Main.java:
for (int i = 0; i < ordersList.size(); i++) {
if (ordersList.get(i).getUser_id() == ordersList.get(i)
.getPersonsList().get(i).getId()) {
System.out.println("Order: "
+ ordersList.get(i).getId()
+ "Person"
+ ordersList.get(i).getPersonsList().get(i)
.getName());
}
}
Database.java:
MysqlPrepareStat = MysqlConn.prepareStatement(insertQueryStatement);
ResultSet result = MysqlPrepareStat.executeQuery();
while (result.next()) {
Orders orders = new Orders();
orders.setId(result.getInt("o.id"));
orders.setDate(result.getString("o.date_time"));
orders.setQuantity(result.getInt("o.quantity"));
Person persons = new Person();
orders.setUser_id(result.getInt("u.id"));
persons.setName(result.getString("u.name"));
persons.setSobrename(result.getString("u.sobrename"));
persons.setEmail(result.getString("u.email"));
persons.setId(result.getInt("u.id"));
persons.setCellphone(result.getInt("u.telefone"));
orders.addPerson(persons);
orderList.add(orders);
}
I want to get the Persons with the same id from Orders that i have declared inside orderList
public List<Person> getPersonsList() {
return personsList;
}
public void addPerson(Person person) {
personsList.add(person);
}

if (ordersList.get(i).getUser_id() == ordersList.get(i)
.getPersonsList().get(0).getId())
You are adding PersonList to each order and that PersonList has only one person for each order. So It is advised to do get(0) rather than get(i).

Please fix code inside your Main.java:
for (int i = 0; i < ordersList.size(); i++) {
if (ordersList.get(i).getUser_id() ==
ordersList.get(i).getPersonsList().get(0).getId()) {
System.out.println("Order: "+ ordersList.get(i).getId()+
"Person"+ ordersList.get(i).getPersonsList().get(0).getName());
}
}

Related

UCAExc:::3.0.7 row column count mismatch

I have some codes for doing my project. There is a access database that have some tables and records. I'm taking this records from access database and I'm creating MS Word document with them. My codes like this
public static void partoff(String SalesOrder)
{
try {
ResultSet deneme4,deneme5,deneme6,deneme,deneme0,deneme10,deneme11 = null;
deneme10=sorgu.executeQuery("SELECT GroupName,ID From TableRun Where LID IN (Select DISTINCT strLID from TableResult Where strSO='"+SalesOrder+"') ORDER BY ID");
ArrayList all_groups=new ArrayList();
while(deneme10.next()) {
all_groups.add(deneme10.getString("GroupName"));
//System.out.println(all_groups.size());
}
ArrayList LIDs=new ArrayList();
deneme11=sorgu.executeQuery("SELECT LID,ID FROM TableRun WHERE GroupName IN (SELECT GroupName,ID From TableRun Where LID IN (Select DISTINCT strLID from TableResult Where strSO='"+SalesOrder+"')) ORDER BY ID");
while(deneme11.next())
{
LIDs.add(deneme11.getString("LID"));
System.out.println(LIDs.size());
}
for(int qq=0; qq<all_groups.size(); qq++) {
deneme4=sorgu.executeQuery("SELECT * FROM TableResult WHERE strSO='" + SalesOrder + "' AND strLID='"+LIDs.get(sayac)+"'");
deneme5=sorgu.executeQuery("SELECT * FROM TablePARTON WHERE strSO='" + SalesOrder + "' AND strLID='"+LIDs.get(sayac)+"'");
deneme6=sorgu.executeQuery("SELECT * FROM TableIW59 WHERE strSO='" + SalesOrder + "' AND strLID='"+LIDs.get(sayac)+"'");
while(deneme4.next()) {
System.out.println(off[satir1][sayac2+8]=deneme4.getString("DefectDes"));
if(!off[satir1][sayac2+8].equalsIgnoreCase("Not Disassembled"))
{
off[satir1][sayac2]=deneme4.getString("strTASK");
off[satir1][sayac2+1]=deneme4.getString("strLID");
off[satir1][sayac2+2]=deneme4.getString("strPN");
off[satir1][sayac2+3]=deneme4.getString("intQPE");
off[satir1][sayac2+4]=deneme4.getString("intSV");
off[satir1][sayac2+5]=deneme4.getString("intIS");
off[satir1][sayac2+6]=deneme4.getString("intRS");
off[satir1][sayac2+7]=deneme4.getString("intREP");
off[satir1][sayac2+8]=deneme4.getString("DefectDes");
satir1++;
}
else {
//System.out.println(deneme.getString("GroupName"));
//satir1=0;
//deneme4.next();
}
}
while(deneme5.next())
{
onn[satir2][sayac2]=deneme5.getString("strPN");
onn[satir2][sayac2+1]=deneme5.getString("intNewOnQty");
onn[satir2][sayac2+2]=deneme5.getString("intRepOnQty");
onn[satir2][sayac2+3]=deneme5.getString("intSVOnQty");
onn[satir2][sayac2+4]=deneme5.getString("strRemark");
satir2++;
}
while(deneme6.next())
{
if(!deneme6.getString("strNotifType").equals("ER")) {
dispon[satir3][sayac2]=deneme6.getString("strNotifType");
dispon[satir3][sayac2+1]=deneme6.getString("strPN");
dispon[satir3][sayac2+2]=deneme6.getString("strQty");
dispon[satir3][sayac2+3]=deneme6.getString("strCodeText");
dispon[satir3][sayac2+4]=deneme6.getString("strGroupText");
dispon[satir3][sayac2+5]=deneme6.getString("strShortText");
dispon[satir3][sayac2+6]=deneme6.getString("strLongText");
satir3++;
}
}
if(satir3>0) {
int x=0;
int y=0;
int q=0;
for(int i=0; i<satir3; i++) {
j=i+1;
while(j<=satir3) {
if(dispon[i][1].equals(dispon[j][1]) && dispon[i][3].equals(dispon[j][3])&& dispon[i][4].equals(dispon[j][4])){
x = Integer.parseInt(dispon[i][2]);
y = Integer.parseInt(dispon[j][2]);
q = x+y;
dispon[i][2]=Integer.toString(q);
dispon[j][0]="boss";
}
j++;
}
}
}
disponsatir=0;
for(int i = 0; i < satir3; i++)
{
for(int j = 0; j<7 ;j++)
{
if(!dispon[i][0].equals("boss"))
{
dispon_new[disponsatir][j]=dispon[i][j];
if(j==6) disponsatir++;
}
}
}
sayac++;
if(!all_groups.get(qq).equals(all_groups.get(qq+1))) {
create_table1(satir1,all_groups.get(qq).toString());
sayac3=0;
sayac2=0;
satir1=0;
satir2=0;
satir3=0;
}
}
System.out.println("Success");
} catch (Exception e) {
// TODO: handle exception
System.out.println("NOT Successfully");
System.out.println(e.getLocalizedMessage());
}
}
It was working nicely yesterday. I changed something in codes but I don't remember what is it. After then I tried to run my codes, I'm getting this error.
UCAExc:::3.0.7 row column count mismatch
Why I'm getting this error?

Trying to print a linked array, A student may have none or many jobs. printStudentDetails prints each student plus x number of job objects

Like in a library a student can borrow n books. I want to print from two arrays 'students[]' and 'currentJobs[]' so the output is for each student - ID1, name, job1, job2. ID2, name, (no jobs). ID3, job1.
I have created a nested for loop but dont know how to code the link. The common field is studentID so i need the outer loop to getstudentID and compare each studentID on the inner loop(array) and print details for each match
public void displayStudentsReport()
{
System.out.println("***** Display Students Report *****");
System.out.println();
for (int i = 0; i < indexCount; i++)
{
students[i].printStudentDetails();
// print job details for each student
for (int j = 0; j < indexNo; j++)
{
currentJobs[j].printJobDetails();
}
}
}
public void printStudentDetails()
{
System.out.println("Printing from Student class");
System.out.printf("%-25s%-40s\n", "Student ID: ", studentID);
System.out.printf("%-25s%-40s\n", "Name: ", name);
System.out.println();
}
public void printJobDetails()
{
System.out.printf("%-25s%-40s\n", "Job: ", jobTitle);
System.out.printf("%-25s%-4.1f", "Current Working Hours: ", totalHours);
System.out.println("hrs");
System.out.printf("%-25s%-40s\n", "Employer: ", employer);
System.out.println();
}
Expected results explained
Just a little fix of what you did. In the second list you should check if it is the correct student from list one.
public void displayStudentsReport()
{
System.out.println("***** Display Students Report *****");
System.out.println();
for (int i = 0; i < students.length; i++)
{
String comp;
comp = students[i].getStudentID();
students[i].printStudentDetails();
// print job details for each student
boolean studentHasJob = false;
for (int j = 0; j < currentJobs.length; j++)
{
if(currentJobs[j].getStudentID().equalsIgnoreCase(comp)) {
studentHasJob = true;
currentJobs[j].printJobDetails();
}
}
if(!studentHasJob){
System.out.println("Student " + comp + " has no jobs");
}
}
}
And I added a small boolean if you want to print something specific if the student does not have a job.
Hope this is what you are looking for !
--- Edit
So I went over the code again because I thought there was a performance issue here. In fact in the code you pass over the currentJobs array many times. Exactly students.length * currentJobs.length times. Which is a lot. So here is a preview of what could be done better :
private void displayStudentsReport() {
System.out.println("***** Display Students Report *****");
System.out.println();
// build map of <StudentId : List of job for this student>
// perf is much better here because you pass on the job list only once
// whereas before you passed (students.length * currentJobs.length) times
Map<String, List<Job>> jobByStudent = new HashMap<>();
for(Job currentJob : currentJobs) {
if(jobByStudent.containsKey(currentJob.getStudentID())) {
jobByStudent.get(currentJob.getStudentID()).add(currentJob);
} else {
List<Job> jobs = new ArrayList<>();
jobs.add(currentJob);
jobByStudent.put(currentJob.getStudentID(), jobs);
}
}
for(Student student : students) {
String comp = student.getStudentID();
student.printStudentDetails();
if(jobByStudent.containsKey(comp)) {
for(Job job : jobByStudent.get(comp)) {
job.printJobDetails();
}
} else {
System.out.println("Student " + comp + " has no jobs");
}
}
}
public void displayStudentsReport()
{
System.out.println("***** Display Students Report *****");
System.out.println();
for (int i = 0; i < indexCount; i++)
{
String comp;
comp = students[i].getStudentID();
students[i].printStudentDetails();
// print job details for each student
for (int j = 0; j < indexNo; j++)
{
currentJobs[j].getStudentID().equalsIgnoreCase(comp);
currentJobs[j].printJobDetails();
}
}
}

Null pointer exception, taking data form lists and arrays

I've checked everything several time, can't get where I am wrong..
Main class:
try
{
File productData = new File("productData.txt");
Product [] consideredRange = InputFileData
.readProductDataFile(productData);
ElectronicsEquipmentSupplier management =
new ElectronicsEquipmentSupplier(1, 12, consideredRange);
File customerData = new File("CustomerData.txt");
Scanner fileScan = new Scanner(customerData);
while(fileScan.hasNext())
management.addNewCustomer(InputFileData.
readCustomerData(fileScan));
management.addNewPurchaseOrder("21/01/12", "PSC-1235", "kD/9767", 50);
}
catch(Exception e)
{
System.out.println(e);
e.printStackTrace();
}
InputFileData class works perfectly. I have created an object of ElectronicsEquipmentSupplier with a consideredRange of products. Also added customers to a customersList.
Here is ElectronicsEquipmentSupplier class:
public class ElectronicsEquipmentSupplier
{
private int currentMonth;
private int currentYear;
private Product [] productRange;
private CustomerDetailsList customersList;
private PurchaseOrderList currentYearList;
private PurchaseOrderList lastYearList;
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear, Product [] range)
{
this.currentMonth = currentMonth;
this.currentYear = currentYear;
productRange = new Product[range.length];
customersList = new CustomerDetailsList();
currentYearList = new PurchaseOrderList();
lastYearList = new PurchaseOrderList();
}
public void addNewPurchaseOrder(String dateStr, String customerID,
String productCode, int qty) throws IncorrectPurchaseOrderException
{
// check for positive order quantity
if(qty < 1)
throw new IncorrectPurchaseOrderException("Order quantity must be"
+ " positive!");
// check for the product code in given range and get that product
Product foundProduct = null;
for(int i = 0; i < productRange.length; i++)
{
if(productRange[i].getProductCode().equals(productCode))
{
foundProduct = productRange[i];
break;
}
}
if(foundProduct == null)
throw new IncorrectPurchaseOrderException("Product code is not in"
+ " the product range!");
try
{
// creating OrderDate object and getting appropriate discount
OrderDate newDate = new OrderDate(dateStr);
int discount = customersList.findCustomer(customerID).
getDiscountRate();
// creating purchase order and adding it to a list
PurchaseOrder givenOrder = new PurchaseOrder(newDate, customerID,
foundProduct, qty, discount);
currentYearList.addPurchaseOrder(givenOrder);
// updating the record of purchasing customer
int priceValue = givenOrder.getFullPriceValue();
customersList.findCustomer(customerID)
.updateTotalOrdersValue(priceValue);
}
catch(Exception e)
{
throw new IncorrectPurchaseOrderException("The problem is with: "
+ "\n" + e);
}
}
It shows that I've got NullPointerException at: if(productRange[i].getProductCode().equals(productCode))
and in the main class at:
management.addNewPurchaseOrder("21/01/12", "PSC-1235", "kD/9767", 50);
Can't get why, as I have all required info..
Thank you!
Update 1:
Added this to the main method to solve first issue:
for(int i = 0; i < consideredRange.length; i++)
management.getProductRange()[i] = consideredRange[i];
But now the ID of a customer cannot be found...
That's the method in CustomerDetailsList class, which throws exception:
public CustomerDetails findCustomer(String givenID)
throws CustomerNotFoundException
{
int i = 0;
boolean match = false;
while(!match && i < listOfCustomerDetails.size())
{
match = listOfCustomerDetails.get(i).getCustomerID()
.equals(givenID);
i++;
}
if(!match)
throw new CustomerNotFoundException("The provided ID has not been"
+ " found");
else
return listOfCustomerDetails.get(i);
}
Update 2: updated .findCustomer() as SMA suggested
You are trying to initialize product in constructor like
productRange = new Product[range.length];
And then using it like:
if(productRange[i].getProductCode().equals(productCode))
Now you allocated space for your array but individual array elements i.e. products are not initialized and hence you get NullPointerException. To resolve the issue, you could do something like:
productRange[i] = new Product(..);//and then use it
Most likely because productRange[i] has not been initialized.
In your constructor you need to fully initialise the productRange array. Right now you are just creating an array of null references.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
productRange = new Product[range.length];
for (int i = 0; i < productRange.length; i++) {
productRange[i] = range[i];
}
customersList = new CustomerDetailsList();
currentYearList = new PurchaseOrderList();
lastYearList = new PurchaseOrderList();
}
The above solution build a new array which reference the same objects as the range array passed to the constructor.
You may just want to reference the array without any allocation, e.g.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
//...
productRange = range;
//...
}
Or do a deep copy of the range array, assuming you have either a Product#clone() method or a Product constructor that takes a Product parameter, e.g.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
//...
productRange = new Product[range.length];
for (int i = 0; i < productRange.length; i++) {
productRange[i] = new Product(range[i]);
}
//...
}
The choice between these different methods depends on how the ElectronicsEquipmentSupplier class is used.

Exhausted Resultset when calling a method inside the while(rset.next)

I'm getting an Exhausted resultset form the following code.
I've tried a few different things now and can't find a solution,
if I don't call the songs method it works, but the songs method works when it's called, can't get my head around it, hoping I'm missing something simple.
public void refreshList() {
rset = po.getProduct();
if (plist.size() > 0) {
for (int i = plist.size() - 1; i >= 0; i--) {
plist.remove(i);
}
}
try {
while (rset.next()) {
songs(rset.getString(1));
CD c = new CD(alist);
Product p = new Product(rset.getString(1),
rset.getString(2),
rset.getString(3),
rset.getDouble(4),
rset.getDouble(5),
rset.getInt(6),
rset.getString(7),
rset.getString(8),
rset.getString(9),
rset.getDouble(10), c);
plist.add(p);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
public void songs(String ID)
{
rset = po.getSongs();
alist = new ArrayList<Song>();
try {
while (rset.next()){
Song s = new Song(rset.getString(1),
rset.getString(2),
rset.getString(3));
slist.add(s);
}
}
catch (Exception ea) {
System.out.println(ea);
}
for(int i = 0; i < slist.size(); i++)
{
if(slist.get(i).getSong_id().equals(ID))
{
alist.add(slist.get(i));
}
}
}
Inside refreshList you have while (rset.next()) loop, on each iteration of it you have songs(rset.getString(1));, which itself has while(rset.next(). This leads to result set exhaustion, because when you return from songs() you try to take some more data from the current position of result set, while in songs() you got out of while (rset.next()) loop, i.e. retrieved all its rows. Consider refactoring your code to avoid nested loops based on result set.

To add an element to arraylist [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class Person {
private String name;
private boolean adopted;
private String parent;
private List<String> children;
public Person(String Aname) {
name = Aname;
children = new ArrayList<String>();
adopted = false;
}
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(name)
&& children.size() <= 10) {
person.parent = name;
// System.out.println(parent);
// children=person.name;
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
// System.out.println(children);
adopted = true;
}
}
public void setName(String name) {
this.name = name;
}
public void disown(Person person) {
}
public String toString() {
if (children.size() == 0 && parent == null) {
return name + " Parent: No parent. Children: No children ";
} else if (children.size() == 0) {
return name + " Parent: " + parent + " Children: No children";
} else if (parent == null) {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: No Parent " + "Children: " + list;
} else {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
}
}
}
In this I am trying to add person.name to arraylist children but I am not able to add. I am initialyzing the list then adding a name to the list.I am using adopt method to add children to the list. Please tell what am I doing wrong here.
The properties are private, please put setters and getters and then try to access to the getName() property.
The following code is incorrect:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
Each time you call Adopt(person) you add that child instead of all the children in the list.
Try using:
children.add(person.name);
EDIT:
Ok, the above is correct, but cristobal de Leon's answer is the explanation to what you're experiencing.
I'm pretty sure the problem is that after you create the new ArrayList(); you never assign any value to the list, so when you iterate based on children.size(), you will always iterate from 0 to 0 and never add any children in the next snippet:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
As per #summerbulb suggestion: person.name should be adopted by the current this so you should just do
children.add(person.name)
Also, at the end of the adopt method, I think you want to mark person (the parameter) as adopted and not this (the person adopting), so you may change
person.adopted=true;
instead of just adopted=true;
The number of items in you arraylist "children" is 0.
Look at this part code:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
for every object in children you will set the same name.
So you will set the name 0 times. That means there also won't be any output.
I think you need an array with al the persons you create in you main.
Change the adopt code to this:
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(this.name)) {
person.parent = name;
children.add(person.name);
person.adopted = true;
}
}
Make getters for your atributes or make them public like this:
public String name;
In your main:
Person[] persons = new Person[5];
persons[0] = new Person("Dude");
persons[1] = new Person("Dude's child");
persons[0].adopt(persons[1]);
Check your toString method. I am not sure if all children are printed. E.g. look at the case in which parent is not NULL and children.size() > 0
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
Here you are iterating over all children, take the name of the last children in the list and return it together with the parents name.
Besides: please check if children can also be of class Person

Categories