Java parsing multiple files - java

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);
}

Related

How do I implement HashMap in my code, I am trying to use it as a memory?

So I am working on a PostFix calculator that is used in command line for a class project, and I am having a little trouble on developing a memory for it. I have been told to create a hashMap and I have researched it and understand the basics of it. I have the calculating method working, but what I am having trouble trying to implement a way for the user to declare variables. For example this what the user should be able to do:
> a = 3 5 + 1 -
7
> bee = a 3 *
21
> a bee +
28
> bee 3 %
0
> a = 4
4
> 57
57
> 2 c +
c not found
> mem
a: 4
bee: 21
> exit
As you can see the user can declare variables in the format " ="
My problem is, that I am not really sure how to Implement the hashMap, I have tried doing it by setting the variable name for the hashmap by getting it from an array list, and getting the integer value from it by getting the return value from my compute method, but all I get is this error:
>Exception in thread "main" java.lang.NumberFormatException: For input string: "
Error"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Program6.main(Program6.java:42)
Here is my code currently:
import java.util.*;
import java.io.*;
public class Program6
{
private static HashMap<String,Integer> memory = new HashMap<>();
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("RPN command line calculator");
Scanner scan = new Scanner(System.in);
System.out.print(">");
while(scan.hasNextLine())
{
System.out.print("> ");
String a = scan.nextLine();
String b = "quit";
String c = "mem";
String d = "clear";
if(a.equals(b))
{
System.exit(0);
}
else
{
System.out.println(compute(a));
}
System.out.print(">");
List<String> list = new ArrayList<String>();
if(!a.isEmpty())
{
StringTokenizer var = new StringTokenizer(a);
while(var.hasMoreTokens())
{
list.add(var.nextToken());
}
}
int pos = 0;
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
memory.put(list.get(list.size()-1),pos);
}
}
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error";
}
Stack<String> tempList = new Stack<String>();
Iterator<String> iter = processedList.iterator();
while (iter.hasNext())
{
String temp = iter.next();
if (temp.matches("[0-9]*"))
{
tempList.push(temp);
}
else if (temp.matches("[*-/+]"))
{
if (temp.equals("*"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls * rs;
tempList.push("" + result);
}
else if (temp.equals("-"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls - rs;
tempList.push("" + result);
}
else if (temp.equals("/"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls / rs;
tempList.push("" + result);
}
else if (temp.equals("+"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls + rs;
tempList.push("" + result);
}
}
else
{
return "Error";
}
}
return tempList.pop();
}
}
Does anyone know how i can make the hashMap memory on the post fix calculator work to where the user can assign variables and be able to call them back, or a better way to approach this?
Your problem is you are adding "Error" from you else clause in the compute method and then trying to parse it as a int.
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error"; //-->> problem
}
Parsing it as an int. This point compute(a) will not be null as it has "Error".
Next step you are trying to parse it as an int.
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
You can change your code as
if (compute(a) != null && !compute(a).equals("Error"))
{
pos = Integer.parseInt(compute(a));
}
Also you should try you put your Integer.parseInt() code in a try catch.
Your HashMap can be used to store the variable names and their values. The key for the map will be the variable name, and the value is the number assigned to it. You currently have Integer but you might want something that handles decimals if you're going to allow things like a = 10 3 /.
In your compute(..) method you expect the input to be of the form var = <calculation> so you should first parse out the variable name which will be the key used in the hashmap memory, and after computing the calculation, store that result with memory.put(var,result);.
When computing the <calculation> part, if a variable name is encountered, look it up to find its value using memory.get(var) and use that value in the computation. With a postfix calculator, you just have to get the 2 values, followed by the operation and perform the math. The result of that is the first value of the next pair to operate on, and so on until you run out of operations and finally assign the result to the variable.

Changing values of static class variables in a nested loop

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! =)

Saving Objects from an Iterated List

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!

Error when reading instances

I have been working on this sort of ATM (With a maximum of 50 customers), where I read a .txt file, and then create multiple instances, store them in an array, so that other classes can call on them.
When I read the file, only the last customer's information are inputted correctly - I can't ever get the first few customers to have their output correct.
There are multiple methods for each 'Set', just in case the field says 'none', so that I can leave it as a
Double.NaN or null, for example.
I have researched on a few websites, and there wasn't very much on storing instances in arrays, although on one website, it said that I should declare it just like a normal array.
private static String firstname = "";
private static String lastname = "";
private static int sin = 0;
private static int year = 0;
private static int month = 0;
private static int day = 0;
private static double sbalance = 0.0;
private static double cbalance = 0.0;
private static double cardbal = 0.0;
private static boolean confirm = false;
public int customernumber;
public static customer [] customerarray = new customer [50];
public static void readfile(){
String sb = "";
String cb = "";
String ca = "";
int counter = 0;
String thisLine;
try {
BufferedReader br = new BufferedReader(new FileReader("bankinfo.txt"));
while ((thisLine = br.readLine()) != null) {
customerarray[counter].setLastName(thisLine);
System.out.print (customerarray[counter].getLastName());
customerarray[counter].setFirstName(br.readLine());
System.out.print (customerarray[counter].getFirstName());
customerarray[counter].setSin(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getSin());
customerarray[counter].setYear(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getYear());
customerarray[counter].setMonth(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getMonth());
customerarray[counter].setDay(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getDay());
sb = br.readLine();
if (sb.equals("none")){
customerarray[counter].setSBalance("none") ;
System.out.print (customerarray[counter].getSBalance());
}
else {
customerarray[counter].setSBalance(Double.parseDouble(sb));
System.out.print (customerarray[counter].getSBalance());
}
cb = br.readLine();
if (cb.equals ("none")){
customerarray[counter].setCBalance ("none");
}
else if (cb != "none"){
customerarray[counter].setCBalance(Double.parseDouble(cb));
}
else{
System.out.print ("error CBalance");
}
ca = br.readLine();
if (ca.equals("none")){
customerarray[counter].setSBalance("none") ;
}
else {
customerarray[counter].setCardbal(Double.parseDouble(ca));
}
counter = counter + 1;
}
br.close();
}
catch (IOException e) {
System.err.println("Error: " + e);
}
}
The text file is fairly simple- it is composed of 9 fields for each customer.
If they do not have a certain account, it is listed as 'none', and when the reader reads them, it uses a variant method with a String input, and sets the double = Double.NaN();
The following is an example of the text file.
Each customer has 9 fields.
Tam
Christian
984635684
1996
6
12
none
10233.52
none
Yang
Wesley
324917400
1996
8
1
3233.36
none
none
Lin
Sophia
1984
1985
5
6
912.12
58.96
95.63
I don't see where you're instantiating each individual location of your customer[] with actual customer objects.
Add this line before after the start of your while loop:
customerarray[counter] = new customer();
When creating an object array, all of the elements in it default to null. You can't dereference null, so you're running into issues.

Calling Two Different Methods into One Method in Java

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?

Categories

Resources