I'm having an issue with changing the values of a class variable within nested loops - I can't figure out why. I'm guessing it's because the variable is static. But it's a static method and because it's used for listing a User in a system from a file, it has to be static (I'm calling it from main method to read file to TreeMaps). Is it not possible to rewrite a static class variable from within a method? If it's possible - what the heck am I doing wrong?
public class Loan{
protected int noOfLoans;
protected int noOfReturns;
protected User user=new User();
protected static Book book= new Book();
protected Map <Integer, Book> currentLoans=new TreeMap <Integer, Book>();
protected Map <Integer, Book> returned=new TreeMap <Integer, Book>();
protected static Map<Integer, Loan> loanList=new TreeMap<Integer, Loan>();
public static void main(String[] args){
readLoans();
}
public static void readLoans(){
loanList.clear();
BufferedReader reader = null;
try {
reader=new BufferedReader(new FileReader("loans.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (line!=null) {
String[] splitOut=line.split("-");
String[] loan_User=splitOut[0].split(",");
String[] loan_CurrentLoans=splitOut[2].split(",");
String[] loan_Returned=splitOut[4].split(",");
Loan loan = new Loan();
loan.user.setFirstName(loan_User[0]);
loan.user.setSurname(loan_User[1]);
loan.user.setPersonalID(loan_User[2]);
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
book.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
book.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
book.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
book.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, book);
}
for (int i = 1; i <= Integer.parseInt(splitOut[3]); i++) {
book.setName(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)]);
book.setAuthorFirstname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+1]);
book.setAuthorSurname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+2]);
book.setISBN(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+3]);
loan.returned.put(i, book);
}
loan.setNoOfLoans(Integer.parseInt(splitOut[1]));
loan.setNoOfReturns(Integer.parseInt(splitOut[3]));
loanList.put(loanList.size()+1, loan);
try {
line=reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's an input line for reference:
John,Doe,8012311213-2-a book,Author,Authorson,1234567890123,another book,Author,Authorson,2345678901234-1-a returned book,Author,Authorson,3456789012345
What I'm hoping to get when printing above line:
Current Loans:
1. a book by Author Authorson (1234567890123)
2. another book by Author Authorson (2345678901234)
Returned Loans:
1. a returned book by Author Authorson (3456789012345)
What I'm currently getting:
Current Loans:
1. a book by Author Authorson (1234567890123)
2. a book by Author Authorson (1234567890123)
Returned Loans:
1. a book by Author Authorson (1234567890123)
And
readLoans();
System.out.println(loanList.get(2).currentLoans.get(1).toString());
System.out.println(loanList.get(2).currentLoans.get(2).toString());
returns
a returned book by Author Authorson (3456789012345)
a returned book by Author Authorson (3456789012345)
Which leads me to believe I actually cannot make instances of my static Book object, but have to make it non-static and try to create instances of the object within the method. If so - how do I do that?
From here, it's hard to understand how you can understand as much as you do, and yet be so confused, at the same time. I don't mean that to be insulting - just to say that I'm not at all sure I understand where you are.
Create instances by using new. So in your two loops, where you keep overwriting the one static book, instead you need a local variable that you assign a new book to and then set the fields on.
The problem isn't that your Book is static, the problem is more simply that it's the same object every time you change it during the loop. This does happen because you've declared it as a static field but you are on the wrong track thinking the way you are about it.
Let's simplify the problem and instead of a Book, use this to illustrate:
class AnObject {
int aValue;
}
And instead of IO, just loop some times and add it to a list:
class PersistenceOfChangesDemo {
static List<AnObject> theList = new ArrayList<AnObject>();
public static void main(String[] args) {
AnObject theObject = new AnObject();
for(int i = 1; i <= 3; i++) {
/* reassign the object's value */
theObject.aValue = i;
/* adds the same object each time */
theList.add(theObject);
}
/* theList is now of size 3
* but all its elements refer to the same object (theObject) */
for(AnObject anObject : theList) {
/* prints '3' every time
* because that was the last value assigned */
System.out.println(anObject.aValue);
/* prints 'true' every time */
System.out.println(anObject == theObject);
}
}
}
The solution is that you need to create a new object each time you want a new one:
class PersistenceOfChangesDemo {
static List<AnObject> theList = new ArrayList<AnObject>();
public static void main(String[] args) {
for(int i = 1; i <= 3; i++) {
/* make a new object each time */
AnObject anObject = new AnObject();
anObject.aValue = i;
theList.add(anObject);
}
/* theList now has references to 3 different objects */
for(AnObject anObject : theList) {
/* prints 1, 2, 3 */
System.out.println(anObject.aValue);
}
}
}
Per your comment, make sure you are creating the new instance for each time you put it in to the map:
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
Book newBook = new Book();
newBook.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
newBook.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
newBook.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
newBook.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, newBook);
}
it's just Reference problem. All three are referring to same object static book so represent the same details which are inserted last.
The change is only create new object of Book() instead of using same object for different detail.
try below code
Loan loan = new Loan();
loan.user.setFirstName(loan_User[0]);
loan.user.setSurname(loan_User[1]);
loan.user.setPersonalID(loan_User[2]);
for (int i = 1; i <= Integer.parseInt(splitOut[1]); i++) {
book = new Book(); // added this line
book.setName(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)]);
book.setAuthorFirstname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+1]);
book.setAuthorSurname(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+2]);
book.setISBN(loan_CurrentLoans[((Integer.parseInt
(splitOut[1])-1)*4)+3]);
loan.currentLoans.put(i, book);
}
for (int i = 1; i <= Integer.parseInt(splitOut[3]); i++) {
book = new Book(); // added this line
book.setName(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)]);
book.setAuthorFirstname(loan_Returned[((Integer.parseInt
(splitOut[3])-1)*4)+1]);
How I solved it;
public static void readLoans(){
// Reads the bookList and userList.
readBooks();
readUsers();
// Creates a new BufferedReader and tries to read "loans.txt"
BufferedReader reader = null;
try {
reader=new BufferedReader(new FileReader("loans.txt"));
}
// Catches exception if "books.txt" does not exist.
catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
// tries to read the first line and interpret it as a String.
try {
line = reader.readLine();
}
// Catches IOexception if any is thrown when trying to read line.
catch (IOException e) {
e.printStackTrace();
}
// Loop as long as "line" is not empty, i.e. as long as a Loan is read.
while (line!=null) {
// split the String "line" at every RegEx "-"
String[] splitOut=line.split("-");
// Create a String from the first index of the first split.
String user = splitOut[0];
/* Split the second and third index of the first split and create
* new Stringarrays from them.*/
String[] loans = splitOut[1].split(",");
String[] returns = splitOut[2].split(",");
User aUser = new User();
/* Find the user in the userList whose personal ID matches the
* String "user" that we created. This is the user that we want to
* create (a) loan/s and/or (a) returned loan/s for.*/
for (int i = 1; i < userList.size()+1; i++) {
if (userList.get(i).getPersonalID().equals(user)) {
/*Set the variables for the User.*/
aUser.setFirstname(userList.get(i).getFirstname());
aUser.setSurname(userList.get(i).getSurname());
aUser.setPersonalID(userList.get(i).getPersonalID());
aUser.setTelephone(userList.get(i).getTelephone());
aUser.setLoans(userList.get(i).getLoans());
aUser.setReturns(userList.get(i).getReturns());
// Create an ArrayList for Loans and Returns for every user
ArrayList<Loan> listOfloans = new ArrayList<Loan>();
ArrayList<Loan> listOfreturns = new ArrayList<Loan>();
// if the new user has any loans...
for (int j = 0; j < aUser.getLoans(); j++) {
for (int k = 1; k < bookList.size()+1; k++) {
/* ... find the "Book" object with the
* corresponding ISBN...*/
if (bookList.get(k).getIsbn().equals(loans[j*3])) {
// ...then create a new loan object for each...
Loan loan = new Loan();
// ...and set the variables of each loan...
loan.setTitle(bookList.get(k).getTitle());
loan.setAuthor_firstname(bookList.get(k).
getAuthor_firstname());
loan.setAuthor_surname(bookList.get(k).
getAuthor_surname());
try {
loan.setIsbn(bookList.get(k).getIsbn());
} catch (Exception e) {
e.printStackTrace();
}
loan.setMaxLoan(bookList.get(k).getMaxLoan());
loan.setOnLoan(bookList.get(k).getOnLoan());
loan.setAvailable(bookList.get(k).
getAvailable());
loan.setSignature(loans[j*3+1]);
loan.setTimestamp(loans[j*3+2]);
/* ...then add each one to the "listOfloans"
* ArrayList.*/
listOfloans.add(loan);
}
}
}
/* if the "listOfloans" ArrayList is not empty,
* add the loan to loanList with User as Key.*/
if (!listOfloans.isEmpty()) {
loanList.put(aUser, listOfloans);
}
// if the new user has any returned loans...
for (int j = 0; j < aUser.getReturns(); j++) {
for (int k = 1; k < bookList.size()+1; k++) {
/* ... find the "Book" object with the
* corresponding ISBN...*/
if(bookList.get(k).getIsbn().equals(returns[j*4])){
// ...then create a new loan object for each...
Loan loan = new Loan();
// ...and set the variables of each loan...
loan.setTitle(bookList.get(k).getTitle());
loan.setAuthor_firstname(bookList.get(k).
getAuthor_firstname());
loan.setAuthor_surname(bookList.get(k).
getAuthor_surname());
try {
loan.setIsbn(bookList.get(k).getIsbn());
} catch (Exception e) {
e.printStackTrace();
}
loan.setMaxLoan(bookList.get(k).getMaxLoan());
loan.setOnLoan(bookList.get(k).getOnLoan());
loan.setAvailable(bookList.get(k)
.getAvailable());
loan.setSignature(returns[j*4+1]);
loan.setTimestamp(returns[j*4+2]);
loan.setReturndate(returns[j*4+3]);
/* ...then add each one to the "listOfreturns"
* ArrayList.*/
listOfreturns.add(loan);
}
}
}
/* if the "listOfreturns" ArrayList is not empty,
* add the returned loan to returnList with User as Key.*/
if (!listOfreturns.isEmpty()) {
returnList.put(aUser, listOfreturns);
}
}
}
// tries to read the next line and interpret it as a String.
try {
line=reader.readLine();
}
// Catches IOexception if any is thrown when trying to read line.
catch (IOException e) {
e.printStackTrace();
}
}
// try to close the BufferedReader.
try {
reader.close();
}
// Catches IOexception if any is thrown when trying to close.
catch (IOException e) {
e.printStackTrace();
}
}
It was a problem with the instancing of the Book object and with objects and methods being static. I had to rewrite a few of the methods behind the scenes that were major problems. Thanks for all the help! =)
Related
I need to parse multiple files and get access to the object's methods outside of where they were initialized.
This is my code:
public static void main(String[] args) {
try {
File Attrationfile = new File("attractions.txt");
Scanner attractionscanner = null;
attractionscanner = new Scanner(Attrationfile);
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
String type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
RollerCoaster rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File Customerfile = new File("customers.txt");
Scanner Customerscanner = new Scanner(Customerfile);
while (Customerscanner.hasNext()) {
String nextline = Customerscanner.nextLine();
String[] Customercomponents = nextline.split("#");
int accountnumber =Integer.parseInt(Customercomponents[0]);
String name = Customercomponents[1];
int age = Integer.parseInt(Customercomponents[2]) ;
int balance = Integer.parseInt(Customercomponents[3]) ;
String discount = Customercomponents.length <= 4
? String.valueOf(0) : Customercomponents[4];
Customer customer= new Customer(accountnumber,name, age, balance, discount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
This works but I can't get access to the objects outside of their loops. I am not sure how the Сustomer class would get information about the roller coaster, such as the name and price. For example, if the customer and rollercoaster objects were in the same area, I would be able to update the customer balance by taking away rollercoaster.getprice from the customer.getbalance, and setting customer.setbalance to the value of the calculation. As you have probably already gathered, I am a beginner, so I am probably going about this in the wrong way - thanks.
You can change the scope for those variables by declaring them at the start of the main method.
public static void main(String[] args) {
Customer customer = null;
RollerCoaster rollerCoaster = null;
try {
File Attrationfile = new File("attractions.txt");
Scanner attractionscanner = null;
attractionscanner = new Scanner(Attrationfile);
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
String type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File Customerfile = new File("customers.txt");
Scanner Customerscanner = new Scanner(Customerfile);
while (Customerscanner.hasNext()) {
String nextline = Customerscanner.nextLine();
String[] Customercomponents = nextline.split("#");
int accountnumber =Integer.parseInt(Customercomponents[0]);
String name = Customercomponents[1];
int age = Integer.parseInt(Customercomponents[2]) ;
int balance = Integer.parseInt(Customercomponents[3]) ;
String discount = Customercomponents.length <= 4 ? String.valueOf(0) :
Customercomponents[4];
customer= new Customer(accountnumber,name , age , balance, discount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Welcome to SO! As Hovercraft pointed out, the objects are declared within the scope of the loop, meaning you can't access them outside of it as you noticed. Also, they are overwritten on every iteration, since you declare and initialize the object on every pass. Consider using an ArrayList like so (here just for the customers):
ArrayList<Customer> customerList = new ArrayList<>();
try {
while (customerScanner.hasNext()) {
// ...
customerList.add(new Customer(accountnumber,name, age, balance, discount));
}
} catch (...) {
// ...
}
Here's the doc for the ArrayList. <T> is a generic type, which for you means that you can have an ArrayList<Customer>, ArrayList<RollerCoaster>, ArrayList<String> ...
Sidenote: By convention, variable names start with a lowercase letter, like Scanner customerScanner instead of Scanner Customerscanner.
Is it a question of scope? Try to declare an object outside the body of the loop.
Because in Java, the brace is a scope. The more nested braces, the smaller the scope. You can try to declare the objects you need to call in the external scope in the same or larger scope
String type = null;
RollerCoaster rollerCoaster = null;
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
The LinkedList only shows the same output. I am trying to use the last while loop but it does not work. This is a "Duck Duck Goose" problem. I am not supposed to use Indexing.
19 names
http://collabedit.com/q248e
public class DuckDuckGoose {
public static void main(String[] args) {
LinkedList<String> linkedlist = new LinkedList<String>();
// add try catch to add list
try {
FileReader fr = new FileReader(...players.txt");
Scanner inFile = new Scanner(fr);
while (inFile.hasNextLine()) {
linkedlist.add(inFile.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Iterator<String> iterator = linkedlist.iterator();
// checks until the last list
while (!iterator.hasNext()) {
if (iterator.next().equals(getRandomBoolean())) {
iterator.remove();
}
}
System.out.println(linkedlist);
}
public static boolean getRandomBoolean() {
return Math.random() < 10 * 0.5;
}
}
if (iterator.next().equals(getRandomBoolean())) {
This is never true, because the iterator contains Strings, not Booleans, so you never execute the iterator.remove();.
Instead:
iterator.next(); // gets but ignores the next String.
if (getRandomBoolean()) {
Additionally, your loop never executes:
while (!iterator.hasNext()) {
because the iterator initially has a next element.
Remove the !.
Additionally, this:
Math.random() < 10 * 0.5
Is always true, because Math.random() is strictly less than 1, and 10 * 0.5 is 5.
Drop the 10 *, or pick a value on the RHS of the < which is between 0 and 1.
I am trying to read a CSV file with 20 columns which may or may not contain value but the problem is that I have to create 20 try catch in order to maintain the code flow in control manner. Like
String a = ""; loop
try{
a = list.get(0); // converted the csv to list of list and iterated in
}catch(NoSuchElementException e){}
and same for every other variable.The reason I have seperate try catch because In the below code
String a = "";
String b = "";
try{
a = list.get(0);
b = list.get(1);
}catch(NoSuchElementException e){}
If first line of try gave exception the second line will not execute.
So is there any alternate to these n number of try catch situation?
Thanks
You could create a helper method:
private String getField(List<String> list, int n) {
try {
return list.get(n);
} catch (NoSuchElementException e) {
return "";
}
}
String a = getField(list, 0);
String b = getField(list, 1);
EDIT:
Typically you wouldn't rely on exceptions if you do not have sufficient fields, the following achieves the same thing but subjectively feels cleaner:
private String getField(List<String> list, int n) {
if (n < list.size()) {
return list.get(n);
}
return "";
}
I'm currently workin' on a sales module using java+hibernate+oracle... I'm done with my order form in my jsp like this:
I'm getting my parameters doing this:
ArrayList<String> idMercaderias = new ArrayList<String>();
ArrayList<String> cantidades = new ArrayList<String>();
ArrayList<String> precios = new ArrayList<String>();
for (int k = 0; k < 10; k++) {
idMercaderias.add(request.getParameter("idMercaderia" + k));
cantidades.add(request.getParameter("cantidad" + k));
precios.add(request.getParameter("precio" + k));
}
I have 10 rows on my order detail, so I made the for, where my inputs are input1, input2, input3, etc. These are attributes of my object Mercaderia so i need to set them up, since they're on lists:
First I'm filtering the first list to avoid repeated articles:
Iterator itra = idMercaderias.listIterator();
ArrayList<String> sortedListIdMercaderias = new ArrayList<String>();
Object m;
while (itra.hasNext()) {
m = itra.next();
if (!sortedListIdMercaderias.contains(m)) {
sortedListIdMercaderias.add((String) m);
}
}
Now I create my object to set all the attributes:
DetallePedido detalle = new DetallePedido();
Now I'm doing a cycle 10 times (thinking of all rows in my form) and start to iterate each list to get my object attributes avoiding null or empty entries.
for (int x = 0; x < sortedListIdMercaderias.size(); x++) {
Iterator itr = idMercaderias.listIterator();
while (itr.hasNext()) {
String mercaderia = (String) itr.next();
if ((mercaderia != null) && (!mercaderia.equals(""))) {
Mercaderia mercaderiaSeleccionada = new MercaderiaDAO().findById(Integer.parseInt(mercaderia));
detalle.setMercaderia(mercaderiaSeleccionada);
}
}
Iterator itr2 = cantidades.listIterator();
while (itr2.hasNext()) {
String cantidad = (String) itr2.next();
if ((cantidad != null) && (!cantidad.equals(""))) {
int cantidadMercaderiaSeleccionada = Integer.parseInt(cantidad);
detalle.setCantidad(cantidadMercaderiaSeleccionada);
}
}
Iterator itr3 = precios.listIterator();
while (itr3.hasNext()) {
String precio = (String) itr3.next();
if ((precio != null) && (!precio.equals(""))) {
BigDecimal precioMercaderiaSeleccionada = new BigDecimal(precio);
detalle.setPrecioUnitario(precioMercaderiaSeleccionada);
}
}
Finally i just persist to my database:
Session session = new DetallePedidoDAO().getSession();
Transaction tx = session.beginTransaction();
try {
session.saveOrUpdate(detalle);
tx.commit();
session.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't know why in the database i only get 1 row inserted (the last one with valid data) instead of all of them.
Any help will be really apreciated, this is for my final test in university project.
You've only ever got one DetallePedido object. You're changing its field values over and over in the various loops, but it's still just one object. Lastly you're saving it. Just once. Naturally, you only get one row inserted in your database.
What you could try is, instead of iterating through your Mercaderia objects, your Cantidad objects and your Precio objects separately; have a single loop that WITHIN EACH ITERATION creates a new DetallePedido object, sets the Mercaderia, the Cantidada and the Precio, and then saves the DetallePedido.
So, following the clues by David Wallace I made some tweaks to the idea and created an object WrapperDetallePedido like this:
public class WrapperDetallePedido {
int idMercaderia;
int cantidad;
double precio;
public int getIdMercaderia() {
return idMercaderia;
}
public void setIdMercaderia(int idMercaderia) {
this.idMercaderia = idMercaderia;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
}
Then in my Controller I created a single ArrayList and set my DetallePedido attributes:
ArrayList<WrapperDetallePedido> listado = new ArrayList<WrapperDetallePedido>();
for (int k = 0; k < 10; k++) {
if (!request.getParameter("idMercaderia" + k).equals("")){
WrapperDetallePedido WDetallePedido = new WrapperDetallePedido();
WDetallePedido.setIdMercaderia(Integer.parseInt(request.getParameter("idMercaderia" + k)));
WDetallePedido.setCantidad(Integer.parseInt(request.getParameter("cantidad" + k)));
WDetallePedido.setPrecio(Double.parseDouble(request.getParameter("precio" + k)));
listado.add(WDetallePedido);
}
}
Finally used Iterator for the previous list and set all the items from listado and persist to the database:
for (Iterator iterador = listado.listIterator(); iterador.hasNext();) {
WrapperDetallePedido detalle = (WrapperDetallePedido) iterador.next();
Mercaderia mercaderiaSeleccionada = new MercaderiaDAO().findById(detalle.getIdMercaderia());
DetallePedido detallePedido = new DetallePedido();
detallePedido.setMercaderia(mercaderiaSeleccionada);
detallePedido.setCantidad(detalle.getCantidad());
detallePedido.setPrecioUnitario(new BigDecimal(detalle.getPrecio()));
detallePedido.setPedidos(pedidoGenerado);
Session session1 = new DetallePedidoDAO().getSession();
Transaction tx1 = session1.beginTransaction();
new DetallePedidoDAO().save(detallePedido);
try {
session1.saveOrUpdate(detallePedido);
tx1.commit();
session1.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Finally got all my rows inserted as i needed... Thank you!
I wish to:
Reading in two files
Split the files into individual strings
Compare the two string lists and retrieve strings that are unique to a file.
At the moment I am running in to the problem of finding a way to call the two methods used to call in the files (one for each file) to the same method in order to be compared.
Both methods use a try-catch-while statement and if I try to read all of the entries after the while statement only a single is shown and not the entire list.
Is there a way to send parts of both methods as parameter to a single new method?
Here is the code for the program. I know that there are problems with the way that I am doing the program, but I am only doing it the way that I was taught.
File mainEmails = new File("Testrun.txt");
Scanner inputScanner = null;
int counter = 1;
String fullName = null;
String position = null;
String companyName = null;
String telNumber = null;
String emailAddress = null;
try
{
inputScanner = new Scanner(mainEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner.hasNextLine())
{
String nextLine = inputScanner.nextLine();
String [] splitFile = nextLine.split(",");
for (int i = 0; i <splitFile.length;i++)
{
if(i==0)
{
fullName = splitFile[0];
}
else if(i==1)
{
position = splitFile[1];
}
else if(i==2)
{
companyName = splitFile[2];
}
else if(i==3)
{
telNumber = splitFile[3];
}
else if(i==4)
{
emailAddress = splitFile[4];
}
else if(splitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
public static void deletionList()
{
File deletionEmails = new File("Testrun1.txt");
Scanner inputScanner1 = null;
String deletionfullName = null;
String deletionposition = null;
String deletioncompanyName= null;
String deletiontelNumber = null;
String deletionemailAddress = null;
try
{
inputScanner1 = new Scanner(deletionEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner1.hasNextLine())
{
String deletionnextLine = inputScanner1.nextLine();
String [] deletionsplitFile = deletionnextLine.split(",");
for (int i = 0; i <deletionsplitFile.length;i++)
{
if(i==0)
{
deletionfullName = deletionsplitFile[0];
}
else if(i==1)
{
deletionposition = deletionsplitFile[1];
}
else if(i==2)
{
deletioncompanyName = deletionsplitFile[2];
}
else if(i==3)
{
deletiontelNumber = deletionsplitFile[3];
}
else if(i==4)
{
deletionemailAddress = deletionsplitFile[4];
}
else if(deletionsplitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
}
What I am trying to do is to take the fullName, emailAddress from the first split and deletionfullName and deletionemailAddress from the second split and compare the first and second of each, respectively. Each file will have a number of fields in it, and I am only interested in the fullName and emailAddress fields.
It is quite confusing to understand how you are trying to implement your solution, so may I suggest you look at a different way of doing the whole read-and-compare process. For example, I would suggest doing something like this... (in psuedocode)
public void compareFiles(String file1, String file2){
// Read the lines of each file into String[] arrays
String[] file1Lines = readAndSplitIntoLines(file1);
String[] file2Lines = readAndSplitIntoLines(file2);
// compare the lines
for (int x=0;x<file1Lines.length;x++){
for (int y=0;y<file2Lines.length;y++){
if (file1Lines[x].equals(file2Lines[y])){
// match. set it to null
file1Lines[x] = null;
file2Lines[y] = null;
// break out of the inner loop and start comparing the next line
break;
}
}
// remove the duplicates (which are now null values), creating a smaller array of uniques.
String[] newFile1 = shrinkArrayByRemovingNulls(file1Lines);
String[] newFile2 = shrinkArrayByRemovingNulls(file2Lines);
}
Besides the fact that your question is not very clear, you have at least one glaring problem:
DO NOT use exception handling for logic! Exception handling should be only for exceptions.
Secondly, think about what you are really looking to do. In pseudocode it would look something like this:
list1 = split(file(name1).read())
list2 = split(file(name2).read())
list3 = unique(list1, list2)
What does your code look like?