Create an ArrayList
Hi everyone, I am writing two classes :
A customer account class: with method to create and manage the client account.
(this is my constructor)
* Create a new customer.
* @param customerName
* enter the name of the new customer.
* @param bal
* enter the cash amount.
public CustomerAccount(String customerName, int bal) {
this.customerName = customerName;
balance = bal;
}A customer base class: the collection of the customers.
In this class I tried to create an ArrayList for my collection of customers, but it doesn't work.
import java.util.ArrayList;
public class CustomerBase {
private ArrayList<CustomerAccount> customerList;
public CustomerBase(){
customerList = new ArrayList<CustomerAccount>();
public void appendCustomer(String name, int bal) {
CustomerAccount cust = new CustomerAccount(name, bal);
customerList.add(cust);
public int getNumberOfCustomer() {
return customerList.size();
}my method append customer doesn't work and I don't understand why.
Can someone can help me ?
Thank you,
Henri
My failure trace is :
java.lang.NullPointerException
at shop.Stock.<init>(Stock.java:12)
at shop.CustomerAccount.<init>(CustomerAccount.java:16)
at shop.CustomerBase.appendCustomer(CustomerBase.java:17)
at shop.CustomerBaseTest.setUp(CustomerBaseTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:592)
at org.junit.internal.runners.BeforeAndAfterRunner.invokeMethod(BeforeAndAfterRunner.java:74)
at org.junit.internal.runners.BeforeAndAfterRunner.runBefores(BeforeAndAfterRunner.java:50)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:33)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)I will have to go to bed now ( almost 3 o'clock in the morning); kevinaworkman thanks a lot for your help.
Henri
Similar Messages
-
Creating an ArrayList as an attribute
Hello all,
I'm new to Java and hope to learn a lot about the language. I've lost much sleep over this last program I was assigned to complete. I've tried everything to try and get this program working properly. As a school assignment we are required to create 3 classes: a loan class, a payment class and a class which handles database and query execution. All we have to do is print the loan information along with the payment information. A loan has multiple payments along with other attributes. I've written all of the code and am struggling on one area, the ArrayList portion of the program. We are supposed to have an ArrayList which contains information about loan payments (retrieved from the database). How do I create an instance of ArrayList <Payments> inside of my loan constructor? I keep getting a null pointer exception when running the program. Maybe my code makes more sense. Thanks in advance for any assistance.
import java.util.ArrayList;
public class Loan {
private String loanID; //id no
private String startDate; //date
private double annualRate; //loan annual rate
private double loanAmt; //loan amount due
private int noYears; //years on loan
private ArrayList<Payment> payments;
/*public Loan (String l, String s, double ar, double la, int ny, ArrayList<Payment> p)
{ loanID = l;
startDate = s;
annualRate = ar;
loanAmt = la;
noYears = ny;
ArrayList<Payment> payments = new ArrayList<Payment>();
public Loan ()
{ this.loanID= loanID;
this.startDate = startDate;
this.annualRate= annualRate;
this.loanAmt = loanAmt;
this.noYears = noYears;
this.payments = payments;
}//end loan constructor
public void setloanID (String l)
loanID = l;
}//end setloanID
public String getloanID ()
return loanID;
}//end getloanID
public void setstartDate (String s)
startDate = s;
}//end setstartDate
public String getstartDate ()
return startDate;
}//end getstartDate
public void setannualRate (double ar)
annualRate = ar;
public double getannualRate (double ar)
return annualRate;
}//end getstartDate
public void setloanAmt (double la)
loanAmt = la;
public double getloanAmt (double la)
return loanAmt;
}//end getstartDate
public void setnoYears (int ny)
noYears = ny;
public int getnoYears (int ny)
return noYears;
}//end getstartDate
public ArrayList <Payment> getPayments ()
return payments;
}//end getPayments
}//end loan
import java.util.ArrayList;
public class Payment {
private String loanID;
private String datePaid;
private double amount;
private double principlePaid;
public Payment ()
this.loanID = loanID;
this.datePaid= datePaid;
this.amount = amount;
this.principlePaid = principlePaid;
}//end loan constructor
void setAmount (double amount){
this.amount = amount;
public double getAmount()
return amount;
void setdatePaid (String datePaid) {
this.datePaid = datePaid;
public String getdatePaid (){
return datePaid;
void setloanID (String loanID)
this.loanID = loanID;
public String getloandID ()
return loanID;
void setprinciplePaid (double principlePaid)
this.principlePaid = principlePaid;
public double getprinciplePaid ()
return principlePaid;
}//end payment class
import java.sql.*;
import java.util.ArrayList;
public class Hw6Dbase {
//Driver NAme and Database URL
static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String dbaseURL = "jdbc:odbc:homework5";
//ArrayList<Payment> payments = new ArrayList<Payment>();
public static void main (String args[])
Loan loan = new Loan ("", "", 0, 0, 0, null); //ArrayList<Payment> p);
Connection connection = null; //connection
Statement statement = null; //queries
try
{ Class.forName(driver);
connection = DriverManager.getConnection(dbaseURL, " ", " ");
statement = connection.createStatement();
//query
{ResultSet resultSet = statement.executeQuery("select * from loan where loanID= '0001'");
//process the results
//ResultSetMetaData dbMetaData = resultSet.getMetaData();
//ResultSetMetaData dbMetaData2 = resultSet2.getMetaData();
System.out.println("Loan Information");
while (resultSet.next())
loan.setloanID(resultSet.getString(1));
loan.setstartDate(resultSet.getString(2));
loan.setnoYears(resultSet.getInt(3));
loan.setannualRate(Double.parseDouble(resultSet.getString(4)));
loan.setloanAmt(Double.parseDouble(resultSet.getString(5)));
String loanid = loan.getloanID();
System.out.println ("Loan id:" + loanid);
String loanDate = loan.getstartDate();
double loanAmt = loan.getloanAmt(0.0);
double rate = loan.getannualRate(0.0);
int years = loan.getnoYears(0);
//ArrayList <Payment> p = loan.getPayments();
System.out.println("Start Date:" + loanDate);
System.out.printf("Amount:%.2f\n", loanAmt);
System.out.println("Annual Rate: "+ rate);
System.out.println("Loan Duration:" + years);
//System.out.println("TEST:" + p); //null
}//end while
System.out.println("\nPayments Received");
ResultSet resultSet2 = statement.executeQuery("select * from payments where loan_ID='0001'");
while (resultSet2.next())
Payment payment = new Payment();
payment.setAmount(Double.parseDouble(resultSet2.getString(4)));
payment.setdatePaid(resultSet2.getString(3));
payment.setloanID(resultSet2.getString(2));
payment.setprinciplePaid(Double.parseDouble(resultSet2.getString(5)));
//double amount = payment.getAmount();
//Test data
//String loanID = payment.getloandID();
//System.out.println("TEST:" + loanID);
//double pamount =payment.getAmount();
loan.getPayments().add(payment);
//loan.payments.add(payment);
int n = loan.getPayments().size();
for (int i= 1; i<= n; i++)
//System.out.println(i);
System.out.println (loan.getPayments().get(i).getAmount());
System.out.println (loan.getPayments().get(i).getdatePaid());
System.out.println (loan.getPayments().get(i).getloandID());
System.out.println (loan.getPayments().get(i).getprinciplePaid());
//System.out.println (n);
}//end try
catch (IndexOutOfBoundsException indexObException)
{indexObException.printStackTrace();
}//end catch
catch (SQLException sqlException)
{sqlException.printStackTrace();
System.out.println("Cannot get connection");
System.exit(1);
}//end catch
catch (ClassNotFoundException classNotFound)
classNotFound.printStackTrace();
System.out.println("Class not found");
System.exit(1);
finally
try {
statement.close();
connection.close();
}//end try
catch (Exception exception)
exception.printStackTrace();
System.exit(1);
}//end catch
}//end finally
}//end main
}//end Hw6Dbasewhen I query the database using my other program (just doing this to show you whats in the payment table) "select * from payments" I get this.
Admin_ID Loan_ID Payment_Date Payment_Amount Payment_To_Principle
0001 0001 2000-05-10 00:00:00 1000.0000 600.0000
0001 0001 2000-06-10 00:00:00 1000.0000 610.0000
0001 0002 2000-06-15 00:00:00 1500.0000 1000.0000
0100 0001 2000-07-10 00:00:00 1000.0000 620.0000
in this program we only want the payments for loan id '0001'. So in my code you can see that I query as follows:
ResultSet resultSet2 = statement.executeQuery("select * from payments where loan_ID='0001'");
Heres what I get in console when I test "n". (System.out.println(n);)
Payments Received
0
1
1
2
2
2
This is what prints out when I run the program...
Loan Information
Loan id:0001
Start Date:2000-05-05 00:00:00
Amount:10000.00
Annual Rate: 0.06
Loan Duration:5
Payments Received
Loan ID: 0001 //(n=0)
Loan Amount: 1000.0
Date Paid: 2000-05-10 00:00:00
Payment to Principle: 600.0
Balance:9400.0
Loan ID: 0001 //DUPLICATE
Loan Amount: 1000.0
Date Paid: 2000-05-10 00:00:00
Payment to Principle: 600.0
Balance:9400.0
Loan ID: 0001 //DUPLICATE
Loan Amount: 1000.0
Date Paid: 2000-06-10 00:00:00
Payment to Principle: 610.0
Balance:9390.0
Loan ID: 0001
Loan Amount: 1000.0
Date Paid: 2000-05-10 00:00:00
Payment to Principle: 600.0
Balance:9400.0
Loan ID: 0001
Loan Amount: 1000.0
Date Paid: 2000-06-10 00:00:00
Payment to Principle: 610.0
Balance:9390.0
Loan ID: 0001
Loan Amount: 1000.0
Date Paid: 2000-07-10 00:00:00
Payment to Principle: 620.0
Balance:9380.0
Strange order huh? I can't figure it out any ideas?.... here's my code again.
import java.sql.*;
import java.util.ArrayList;
public class Hw6Dbase {
//Driver NAme and Database URL
static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String dbaseURL = "jdbc:odbc:homework5";
public static void main (String args[])
Loan loan = new Loan();
Connection connection = null; //connection
Statement statement = null; //queries
try
{ Class.forName(driver);
connection = DriverManager.getConnection(dbaseURL, " ", " ");
statement = connection.createStatement();
//query
{ResultSet resultSet = statement.executeQuery("select * from loan where loanID= '0001'");
System.out.println("Loan Information");
while (resultSet.next())
loan.setloanID(resultSet.getString(1));
loan.setstartDate(resultSet.getString(2));
loan.setnoYears(resultSet.getInt(3));
loan.setannualRate(Double.parseDouble(resultSet.getString(4)));
loan.setloanAmt(Double.parseDouble(resultSet.getString(5)));
String loanid = loan.getloanID();
System.out.println ("Loan id:" + loanid);
String loanDate = loan.getstartDate();
double loanAmt = loan.getloanAmt();
double rate = loan.getannualRate();
int years = loan.getnoYears();
System.out.println("Start Date:" + loanDate);
System.out.printf("Amount:%.2f\n", loanAmt);
System.out.println("Annual Rate: "+ rate);
System.out.println("Loan Duration:" + years);
}//end while
System.out.println("\nPayments Received");
ResultSet resultSet2 = statement.executeQuery("select * from payments where loan_ID='0001'");
while (resultSet2.next())
Payment payment = new Payment();
//set payment attributes
payment.setloanID(resultSet2.getString(2));
payment.setAmount(Double.parseDouble(resultSet2.getString(4)));
payment.setdatePaid(resultSet2.getString(3));
payment.setprinciplePaid(Double.parseDouble(resultSet2.getString(5)));
int n = loan.getPayments().size();
loan.getPayments().add(payment);
for (int i= 0; i<= n; i++)
double balance = loan.getloanAmt()-loan.getPayments().get(i).getprinciplePaid();
//output
//System.out.println(n);//test count
System.out.println ("Loan ID: " +loan.getPayments().get(i).getloandID());
System.out.println ("Loan Amount: " +loan.getPayments().get(i).getAmount());
System.out.println ("Date Paid: " +loan.getPayments().get(i).getdatePaid());
System.out.println ("Payment to Principle: "+loan.getPayments().get(i).getprinciplePaid());
System.out.println ("Balance:" +balance);
System.out.println ("\n");
}//end for
}//end of while
}//end try
//catch (IndexOutOfBoundsException indexObException)
//{indexObException.printStackTrace();
}//end catch
catch (SQLException sqlException)
{sqlException.printStackTrace();
System.out.println("Cannot get connection");
System.exit(1);
}//end catch
catch (ClassNotFoundException classNotFound)
classNotFound.printStackTrace();
System.out.println("Class not found");
System.exit(1);
finally
try {
statement.close();
connection.close();
}//end try
catch (Exception exception)
exception.printStackTrace();
System.exit(1);
}//end catch
}//end finally
}//end main
}//end Hw6Dbase -
Quickie - How to create a ArrayList Array?
Hi,
I hope this has a quick answer. What I'm trying to do is create an Array of ArrayList objects to replace a ragged array I had for strings. Basically the length of each 'row' of the array can be variable and I want to take advantage of ArrayLists features. So I created ArrayList
as below:
ArrayList[] headerInfo = new ArrayList[3];
headerInfo[0] = new ArrayList<String>();
headerInfo[0].add("aString");If I iterate through each arrayList using a for each loop, will the order be preserved? Or is there a better way to achieve a 'variable length' ragged array?
Thanks.Also, if you end up having to keep a large number of empty spaces in your lists/arrays (so that the "x" and "y" line up with the object you are trying to represent), you can try a Map to reduce the overall memory needed (because you won't need to keep a space for "x,y" pairs that don't have a corresponding value). Your key can be a String generated as:
String key = x + "," + y;Then your map could be:
Map<String, String> myStrings = new HashMap<String, String>();The getString method would be:
return myStrings.get(x+","+y);or the key could be a simple class:
[For a HashMap, you need hashCode--maybe add the hashCode provided by Integer class for x to the hashCode provided by Integer class for y--I don't know a lot about implementing hashCodes, but that sounds possibly reasonable.]
class Pair {
private final int x;
private final int y;
Pair(int x, int y) {
// set values
// define "equals" (x == other.x, y == other.y)
// define "hashCode"
// define "toString" for debugging purposes
Map<Pair, String> myStrings = new HashMap<Pair, String>();The getString method would be:
return myStrings.get(new Pair(x, y));For mathematics, if the 2-d array was a numerical matrix, this HashMap would implement what is called a "sparse matrix".
The map doesn't change your other classes. The other classes would still call:
String myString = someClass.getString(2, 4); -
Is it a better practice to create an ArrayList at class level?
Hello forum members,
Of late one of my collegue suggested me to declare an ArrayList at class level and clearing the data for each method call as garbage collection is not guaranted in java and we may end-up with large pool of ArrayList objects on subsequent method calls!!!
FYI :There was a need of an ArrayList object for a single method only.Bad suggestion. Variables should be declared in the scope in which they are used.
Also bad reasoning. It needn't bother the programmer that garbage collection isn't guaranteed to run whenever a variable goes out of scope. It's sufficient that it is guaranteed to run before the program throws a OutOfMemoryError.
That said, parts of the JDK instantiate an object as a class field and set (and subsequently access) its attributes in various methods to reduce the overhead of object creation for enhancing performance. Much of this is legacy code from the days of slower computers and less efficient JVMs and probably wouldn't be written the same way today.
db -
Problems in creating a preorder tree node arraylist
Hi, i want to create an arraylist containing a preorder tree node's name, the program compiled well but every time it gives error when i press the "Output Preorder" button to create the arraylist, the following is the code, can someone help? Thanks a lot!!
JButton outputPreorderButton = new JButton("Output Preorder");
outputPreorderButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
for (Enumeration evev = tableTreeRootNode.preorderEnumeration() ; evev.hasMoreElements() ;) {
System.out.println(evev.nextElement());
String s = (String)evev.nextElement();
tableTreeNodesArray.add(s);Yeah, well, it will "give error" (as you so precisely and informatively say) if there's an odd number of nodes in your tree. Consider your code:System.out.println(evev.nextElement());
// Get element number 1 and print it.
String s = (String)evev.nextElement();
tableTreeNodesArray.add(s);
// Get element number 2 and add it to the list.So, the odd-numbered elements you print. The even-numbered elements you add to the list. If it happens there are 31 nodes, then an error will occur when you try to get node 32. -
I am trying to help a friend in school with a project and we need some help...
We need to write a program to estimate how much paint is needed to paint a house. Assuming we know the square feet that a gallon of paint covers, number of coats required, and the dimensions of the wall, window, door, or gable.
We are using a GUI to enter the data for the different regions.
We have the GUI created and the hierchy competed. I need some help creating the arraylist to run the program.
The user will enter a new region by selecting:
surface type
width
height
then you will be able to add or insert to include this region in the list.
You will also be able modify, delete, or navigate to existing regions in the list by selecting the appropriate navigigation buttons below:
( |< or < or > or >| )
Classes include:
PaintEstimatorView
PainEstimator Model
Regions:
Wall
Door
Gable
Window
And the Approriate Listners
Each region will have its own height and width which are set when the region is created
Each region will compute and return its area and the walls and gables will contribute to the surface; windows and doors will reduce the surface.
each region will calculate its area.
We need to include a View and Model
The view will manage the interface and the model will provide the necessary processing.
responsibilities of the view:
Instantiate and arrange the windowobjects
instantiate and initialize the model
handle user generated events such as button clicks and menu selections by sending message to the model
represent the model to the user.
Model:
Define and manage the applications data(coordinating the activities of several programmer defined classes)
respond to messages from the view
We have the GUI completed I just need some help getting the arraylist started to run the program.
We will need to keep a count and index of all the regions created by the user and you need to be able to shuffle throught them if you need to delete or modify them. You also need to insert windows and doors which will subtract from the total surface area but you have to go back to which ever wall or gable and create the window or door before or after that region.
If anybody could help it would be greatly appreciated.
Thanks in adavnce
RusSorry, I forgot to add my code last night.
This is what we have so far.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class TestSwingCommonFeatures extends JFrame {
private JRadioButton wall, window, gable, door;
private JButton computegal;
public TestSwingCommonFeatures() {
// Create a panel to group three buttons
JPanel p1 = new JPanel(new GridLayout(2, 2, 5, 5));
JTextField sqftpergal = new JTextField(8);
JTextField coats = new JTextField(8);
JTextField gallonsneeded = new JTextField(8);
gallonsneeded.setEditable(false);
p1.add(new JLabel("SQ ft / gallon"));
p1.add(sqftpergal);
p1.add(new JLabel("Number of gallons:"));
p1.add(coats);
p1.add(new JLabel("Gallons needed:"));
p1.add(gallonsneeded);
p1.add(computegal = new JButton("Compute gallons needed"));
//computegal;
p1.setBorder(new TitledBorder("Select gallons & coats"));
// Create a font and a line border
Font largeFont = new Font("TimesRoman", Font.BOLD, 20);
Border lineBorder = new LineBorder(Color.BLACK, 2);
// Create a panel to group two labels
// panel 2
JPanel p2 = new JPanel(new GridLayout(4, 2, 5, 5));
p2.add(wall = new JRadioButton("wall"));
p2.add(gable = new JRadioButton("gable"));
p2.add(new JButton("ADD"));
p2.add(window = new JRadioButton("window"));
p2.add(door = new JRadioButton("door"));
p2.add(new JButton("Remove"));
p2.add(new JLabel("Width"));
p2.add(new JTextField(12));
p2.add(new JButton("Insert"));
p2.add(new JLabel("Height"));
p2.add(new JTextField(12));
p2.add(new JButton("Delete"));
p2.setBorder(new TitledBorder("Controls"));
ButtonGroup radiogroup = new ButtonGroup();
radiogroup.add(wall);
radiogroup.add(gable);
radiogroup.add(window);
radiogroup.add(door);
//panel 3
JPanel p3 = new JPanel(new GridLayout(2, 1, 5, 5));
p3.setBorder(new TitledBorder("Section Selection"));
p3.add(new JButton("<|"));
p3.add(new JButton("<"));
p3.add(new JButton(">"));
p3.add(new JButton("|>"));
p3.add(new JLabel("Count"));
p3.add(new JTextField(4));
p3.add(new JLabel("Index"));
p3.add(new JTextField(4));
// Add two panels to the frame
setLayout(new GridLayout(3, 1, 5, 5));
add(p1);
add(p2);
add(p3);
public static void main(String[] args) {
// Create a frame and set its properties
JFrame frame = new TestSwingCommonFeatures();
frame.setTitle("TestSwingCommonFeatures");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
private class UpdateListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Update button was clicked");
private class NavListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Nav button was clicked");
// Create a list to store data
java.util.ArrayList paintList = new java.util.ArrayList();
This is the GUI for the project that we have come up with. I have to write the arraylist for inside the model.
I have tried a couple different things but have been unsuccessful getting it to work. All I am looking for is a start of the arraylist I will try to figure out the rest myself.
Thanks -
Creating arrayList without importing classes
Hi, im trying a cut down version of java and just wondering how i can create and arrayList without importing any classes, this is because i want to make this program as small as possible. P.S i dont want to use arrays[ ] either
Thanks in advancewhy don't you want to use arrays? they exist, whether you like them or not. you can't just pretend they're not there and get a "cut down" version of java
for the record, what you're proposing is nigh-on impossible. the only way to do this without using arrays would be to declare some massive number of Objects in your class, and store objects in them. sadly, you will be limited to 2147483648 objects
public class ReallyDumb {
int count;
private Object object1;
private Object object2;
// etc
private Object object2147483647;
public void add(Object object) {
switch(count++) {
case 0:
object1 = object;
break;
case 1:
object2 = object;
break;
// etc
case Integer.MAX_VALUE:
object2147483647 = object;
public Object get(int i) {
switch (i) {
case 0:
return object1;
case 1:
return object2;
// etc
case Integer.MAX_VALUE:
return object2147483647;
return null;
public void remove(Object obj) {
if ( object1 == obj ) {
object1 = object2;
// object2 = object3
// object3 = object4
// etc all the way to 2147483647
if ( object2 == obj) {
// object2 = object3
// object3 = object4
// etc all the way to 2147483647
if ( object2147483647 == obj) {
object2147483647 = null;
}good luck -
Huge headache, ArrayList from Txt File
I'm trying to generate an ArrayList from a text file. But the problem is I have no idea how to go about it properly. This is what I've gotten so far.
import java.io.*;
import java.util.*;
public class reader
try
FileReader input = new FileReader("quizscore.txt");
BufferedReader bufferInput = new BufferedReader(input);
String line;
while ((line = bufferInput.readLine ()) !=null )
String[] result = line.split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
catch (IOException e)
System.out.println("Error:" + e);
}That is my data reader which is reading a text file with a buncha numbers like this,
9893 034 009 077 078 020
1947 045 040 088 078 055
2877 055 050 099 078 080
3189 022 070 100 078 077
Now I want to create an ArrayList to put all that data into. I cannot seem to set it up correctly and it's driving me nuts.
class Student
public int idNum;
public int quiz1;
public int quiz2;
public int quiz3;
public int quiz4;
public int quiz5;
public Student(int id, int q1, int q2, int q3, int q4, int q5)
this.idNum = id;
this.quiz1 = q1;
this.quiz2 = q2;
this.quiz3 = q3;
this.quiz4 = q4;
this.quiz5 = q5;
}Now where would I put the
ArrayList StudentData = new ArrayList();
so that when I read the text file, it automatically writes into the ArrayList formated like the public Student object I have? I was orginally supposed to use the StringTokenizer but after reading the java documentation it suggested I code using the split function. So the question is, how do I get it to write every line's tokens into one array row and so on?Using turng's code as a sort of guideline, I have created this piece of code. There are some problems though. The array doesn't seem to be writing properly.
import java.io.*;
import java.util.*;
public class getData
public getData()
public void load(File file)
String[][] studentData = new String[40][6];
try
FileReader input = new FileReader(file);
BufferedReader bufferInput = new BufferedReader(input);
String line;
while ((line = bufferInput.readLine ()) !=null )
System.out.println(line);
//String[] result = line.split("\\s");
//for (int x=0; x<result.length; x++)
// System.out.println(result[x]);
for (int l = 0; l <40; l++)
for (int i = 0; i < 6; i++)
String[] tokens = line.split("\\s");
for (int x = 0; x<tokens.length; x++)
studentData[l] = tokens[x];
System.out.println("L is:" + l);
//System.out.print("I is:" + i);
System.out.println(studentData[l][i]);
catch (IOException e)
System.out.println("Error:" + e);
public static void main(String arg[])
(new getData()).load(new File("quizscore.txt"));
Basically what happens when I run through this, it prints this (This is the last portion, I'm assuming it goes from 0-39)
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:38
6999
L is:38
000
L is:38
098
L is:38
089
L is:38
078
L is:38
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020
L is:39
6999
L is:39
000
L is:39
098
L is:39
089
L is:39
078
L is:39
020The actual text file that is being read,
Stud Qu1 Qu2 Qu3 Qu4 Qu5
1234 052 007 100 078 034
2134 090 036 090 077 030
3124 100 045 020 090 070
4532 011 017 081 032 077
5678 020 012 045 078 034
6134 034 080 055 078 045
7874 060 100 056 078 078
8026 070 010 066 078 056
9893 034 009 077 078 020
1947 045 040 088 078 055
2877 055 050 099 078 080
3189 022 070 100 078 077
4602 089 050 091 078 060
5405 011 011 000 078 010
6999 000 098 089 078 020It's writing the very last line throughout the whole array. Why is this? I know my loop coding is probably the problem, and I'm trying to draw out the flow on a piece of paper, but it's confusing me more and more. And I do apologize in advance if the error that's causing this is some simple coding error I should have learned before but probably haven't.
Edited by: soulesschild on Nov 16, 2007 5:39 PM -
Getting unique values from an arraylist
Hi
I have an arraylist that contains stringbuffer objects. The arraylist has duplicate values of the objects. I have to create another arraylist with only the unique values from the first arraylist. I tried it many ways and using many functions, but no luck. Can someone provide me the code for this , as i need to do this urgently.
Thank U
Mansoor,> Sanity check: when are StringBuffers equal?
Same character sequence.
[EDIT] Or so I thought. Just tested, and found I was wrong. A quick glance at the API confirmed my error; StringBuffer doesn't override Object.equals().
~ -
How to create an order list??
Hi.
I'm using <h:selectManyListbox> to show data.
I do it using the next code:
I create the arrayList with values from datatable
ArrayList<SelectItem> arrayList = new ArrayList<SelectItem>();
while (result.next()) {
SelectItem item = new SelectItem();
item.setValue(result.getString("ID"));
item.setLabel(result.getString("Description"));
arrayList.add(item);
Then I translate to SelectItem[] myListItems using a function:
myListItems= arrayList2SelectItem(arrayList);
where I have defined:
public SelectItem[] arrayList2SelectItem(ArrayList<SelectItem> arrayList) {
SelectItem[] result = new SelectItem[arrayList.size()];
arrayList.toArray(result);
return result;
But what I want to do is create myListItems sorted.
I have tried differents ways with treeMap, treeSet, but I can be able to make the transformation like I do in arrayList2SelectItem
So, my idea is:
1.- Create a treeMap, so I have the values sorted.
2.- Translate to SelectItem[] myListItems; (here is where I stopped)
Does anybody knows how to achieve this??
ThanksHmmm, I think I have been confused on the subject. (I thought you could do as you say, failed and changed my mind) Now I find it works.. You are correct. 8-)
e.g.
Set set = new TreeSet(new Comparator() {
public int compare(Object o1, Object o2) {
return ((byte[]) o1)[0] - ((byte[]) o2)[0];
set.add(new byte[]{1});
set.add(new byte[]{2});
set.add(new byte[]{3}); -
How do I create a new image composed of a number of smaller images?
Hi,
I'm attempting to work with the assorted image APIs for the first time and am experiencing one main problem with what I'm trying to do. Here's the scenario;
I have an image file (currently a JPEG) which is 320*200 pixels in size, it contains a set of 20*20 images. I want to take such a file and convert it into a new JPG file containing all those 20*20 images but in a different grid, for example a single column.
I'm currently having no problem in working my way through the input file and have created an ArrayList containing one BufferedImage for each 20*20 image. My problem is that I just can't see how to create a new file containing all those images in new grid.
Any help would be much appreciated and FWIW I've included the code I've written so far.
package mkhan.image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
public class ImageTileConvertor {
// arg 1 = input file
// arg 2 = output file
// arg 3 = tile x dimension
// arg 4 = tile y dimension
// arg 5 = number of tiles in x dimension
// arg 6 = number of tiles in y dimension
public static void main(String[] args) throws IllegalArgumentException,
IOException {
if (args.length != 6) {
System.out.println("Invalid argument list, please supply the following information in the specified order:");
System.out.println(" - The input file name including full path");
System.out.println(" - The output file name including full path");
System.out.println(" - The size of the tile in the x dimension");
System.out.println(" - The size of the tile in the y dimension");
System.out.println(" - The number of tiles in the x dimension");
System.out.println(" - The number of tiles in the y dimension");
} else {
ImageTileConvertor imageConvertor = new ImageTileConvertor(args[0], args[1], args[2],
args[3], args[4], args[5]);
* Instance member vars
private File m_sourceFile = null;
private File m_outputFile = null;
private int m_tileSizeX = 0;
private int m_tileSizeY = 0;
private int m_numberOfXTiles = 0;
private int m_numberOfYTiles = 0;
* Ctor
public ImageTileConvertor(String sourceFile, String outputFile,
String tileSizeX, String tileSizeY,
String tilesX, String tilesY) throws IllegalArgumentException,
IOException {
try {
Integer tileSizeXInt = new Integer(tileSizeX);
Integer tileSizeYInt = new Integer(tileSizeY);
Integer tilesXInt = new Integer(tilesX);
Integer tilesYInt = new Integer(tilesY);
m_tileSizeX = tileSizeXInt.intValue();
m_tileSizeY = tileSizeYInt.intValue();
m_numberOfXTiles = tilesXInt.intValue() - 1;
m_numberOfYTiles = tilesYInt.intValue() - 1; // convert to zero base
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Tile Sizes must be integers");
m_sourceFile = new File(sourceFile);
m_outputFile = new File(outputFile);
if (!m_sourceFile.exists()) {
throw new IllegalArgumentException("Input file must exist and be a valid file");
try {
translateToTiles();
} catch (IOException e) {
throw e;
* Performs the translation from one format to the other
private void translateToTiles() throws IOException {
ImageInputStream imageIn = null;
BufferedImage bufferedWholeImage = null;
int imageHeight = 0;
int imageWidth = 0;
int currentX = 0;
int currentY = 0;
ArrayList imageList = new ArrayList();
try {
imageIn = ImageIO.createImageInputStream(m_sourceFile);
bufferedWholeImage = ImageIO.read(imageIn);
if (bufferedWholeImage != null) {
imageHeight = bufferedWholeImage.getHeight();
imageWidth = bufferedWholeImage.getWidth();
if (((m_tileSizeX * m_numberOfXTiles) > imageWidth) || ((m_tileSizeY * m_numberOfYTiles) > imageHeight)) {
throw new IOException("Specified Tile Size is larger then image");
} else {
// Process each tile, work in columns
for (int i=0; i <= m_numberOfXTiles; i++) {
for (int j=0; j <= m_numberOfYTiles; j++) {
currentX = i * m_tileSizeX;
currentY = j * m_tileSizeY;
createTiledImage(imageList, bufferedWholeImage, currentX, currentY);
createOutputTiles(imageList);
} else {
throw new IOException("Unable to identify source image format");
} catch (IOException e) {
throw e;
private void createTiledImage(ArrayList listOfImages, BufferedImage wholeImage,
int xPosition, int yPosition) {
BufferedImage bufferedTileImage = wholeImage.getSubimage(xPosition, yPosition, m_tileSizeX, m_tileSizeY);
listOfImages.add(bufferedTileImage);
private void createOutputTiles(ArrayList imageList) throws IOException {
ImageOutputStream out = ImageIO.createImageOutputStream(m_outputFile);
Iterator iterator = imageList.iterator();
// This doesn't work at the moment, it appears to output all the images but the end file only seems to contain the first small image
while (iterator.hasNext()) {
BufferedImage bi = (BufferedImage)iterator.next();
ImageIO.write(bi, "JPG", out);
System.out.println(out1.getStreamPosition());
out.close();
// This is another attempt in which I can see how to populate a Graphics object with a small sample of the images
// Although I'm not sure how to output this to anywhere in order to see if it works - can this approach output to a file?
BufferedImage singleTile = (BufferedImage)imageList.get(0);
// Now populate the image with the tiles
Graphics gr = singleTile.createGraphics();
gr.drawImage(singleTile, 0, 0, Color.BLACK, null);
singleTile = (BufferedImage)imageList.get(1);
gr.drawImage(singleTile, 0, 20, Color.BLACK, null);
}Thanks,
MattConstruct a new BufferedImage whose width is the width of a tile, and whose height is the height of a tile times the number of tiles.BufferedImage colImg = new BufferedImage(m_tileSizeX,
m_tileSizeY * m_numberOfXTiles * m_numberOfYTiles,
BufferedImage.TYPE_INT_ARGB);Now write the tiles onto it.Iterator it = imageList.iterator();
int columnYPos = 0;
Graphics g = colImg.getGraphics();
while (it.hasNext())
g.drawImage((Image)it.next(), 0, columnYPos, null);
columnYPos += m_tileSizeY;
}Now save your image.*******************************************************************************
Answer provided by Friends of the Water Cooler. Please inform forum admin via the
'Discuss the JDC Web Site' forum that off-topic threads should be supported. -
Overview
My program needs to store 11 different types of data (numbered 1 through 12, skipping 5, although I may find a way to fill this gap soon). Each type of data needs to have a bunch of entries of undeterminate size (ArrayList), but I know there will always be 11 different types of data. I figured instead of having 11 different ArrayList variables and 11 getters, 11 setters, and 11 removers, I could just store them all in an array of some sort, and then only have 1 getter/setter/remover/etc which takes an argument of what data type it is.
Problem
Problem is, I'm not exactly sure what to use to group these ArrayLists together. I tried an array, but it complains about the generic typing:
ArrayList<Resource> resList[] = new ArrayList<Resource>[13]();
or any combination/order of [13] and () and it always complains "Cannot create a generic array of ArrayList<Resource> or "Cannot convert from ArrayList<Resource> to ArrayList<Resource>[]"
Solution
Using basic google skills, I discovered I could use:
ArrayList resList[] = new ArrayList[12];
essentially just dropping the type...
and then loop through the 13 new ArrayList<Resource>();
Resulting Problem
Then when I go to add one of the datatypes to its respective data type ArrayList
resList[Resource.PATH].add(new Path());
it warns me: "...Type Safety... raw type ArrayList... should be Parameterized"
it also says the same thing, somewhat surprisingly, when I generalize the path data type back down to Resource:
resList[Resource.PATH].add((Resource)new Path());
since I did declare each arraylist of type <Resource>. Yet it makes the same complaint.
Conclusion
There's basically 4 possible outcomes to this that I can think up.
1) (Mostly desirable) There is a solution to my Type Safety warning.
2) (Undesirable) use @SuppressWarnings
3) An alternative to bunching them in arrays (I had a glance at Arrays.asList, but wasn't so sure about it)
4) (Undesirable) just leave them as 11 different ArrayList variables and make them public.
Thanks in advance,
-IsmAvatar@musicalscale, thanks, I think. Is this just creating
an ArrayList of ArrayLists? Because I don't think
that's appropriate here because the 11 data types are
unchanging (until I fill in the gap at 5, in which
case it's simply a matter of slight recoding which
I'm more than happy to do).Yes, it's an ArrayList of ArrayLists. It will get rid of the generics warnings. If you don't plan on changing the size of the outer ArrayList, then you don't have to change it. Only your one class that keeps the private ArrayList of ArrayLists will have direct access to the outer list (unless you code it otherwise). So, you don't have to worry that someone else will mess up the list.
Or, after you create the initial list of lists, store the private reference as an unmodifiable List:
private final List< List < Resource > > resList;// In your constructor (or another method):
// create tempResList with generics as described,
// then set the instance variable as
resList = Collections.unmodifiableList(tempResList);Then even your local class can't add or remove things from the outer list (they can still modify the inner lists).
As for HashMap, I guess it doesn't matter that the
order may change, since we have the key paired with
it. But is HashMap also dynamically resizable? Maybe
I'm just blind to the internal workings.Yes, a HashMap is dynamically resizable. Since you have a key, yes, the order doesn't matter (there is also a TreeMap that keeps the keys sorted, but you don't really need that for your stated purposes). You can make an unmodifiable Map similar to how you make an unmodifiable List. -
How to store the data of a file into an ArrayList?
Hi! everyone.
I want to know
if I have a File, and the data in the file are type int, type String...
And I have a ArrayList which is of type Question
How do I store the data of that file into the ArrayList
I tried to use the while loop(use the hasNextLine() to read the data line by line)
But I cannot add data which are not of type Question to the ArrayList.
Can you tell me what I should do, please?
I also wonder that
The data of the file are of many types, but when I try to read it with the nextLine(), the data all turn out to be of type String. Why?
Thank you.
Edited by: Terry001 on Apr 30, 2008 1:13 PMNo, a line in the file is just part of a question
The format of the file is like this:
*<question type code> : String*
*<question point value> : int*
*<question category> : String*
*<question difficulty level> : int*
*<question text> : String*
*<question correct answer> : String*
*<optional question-specific data> : String*
*<question terminator> : String*
And here is an example
TF //TrueFalseQuestion
5 //points value
None //category
3 //difficulty level
The capital of the United States is Washington, D.C. //question text
True // answer
*** //quetion terminator
I created an ArrayList in the Test class:
private ArrayList<Question> questions; // Create inside constructor
public Test (String name, String instr)
testName = name;
scoreEarned = 0;
scorePossible = 0;
instructions = instr;
questions = new ArrayList<Question>(); //[MAX_NUMBER_OF_QUESTIONS];
}And I tried to use the following method to store the data of the file to the ArrayList
// This method loads a set of questions from a plain text file
public void loadQuestionsFromFile(String fileName) throws FileNotFoundException
try
File fileReader = new File("input.txt");
Scanner sc = new Scanner(fileReader);
while (sc.hasNextLine())
// I don't know how to pass the data I got from the nextLine() method to the ArrayList because they are of different type
catch (FileNotFoundException a)
System.out.println(a);
} As all you said, I should create an Question object in the while loop
Question temp = new Question ();But I have no idea how to pass the int and String to the Question object.
Thank you -
Hi, I want to create an ArrayList property in an Infopath form. When I try to add values to the property I get "The name 'xxxxx' does not exist in the current context". Any help please? thanks
PROPERTY
private ArrayList Xxxxx
get
ERROR >>> return xxxxx;
set
ERROR >>> xxxxx = value;
public void FormEvents_Loading(object sender, LoadingEventArgs e)
try
ArrayList xxxxx = new ArrayList();
METHOD
public void drpChantier_Changed(object sender, XmlEventArgs e)
try
string qstrReferenceForm = FormState["_qstrReferenceForm"].ToString();
Xxxxx.Add(qstrReferenceForm);Hi,
According to the code you provided, it seems that the
xxxxx is not declared before using in the Xxxxx accessors.
Here is a documentation about Accessors
for your reference:
http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx
Best regards
Patrick Liang
TechNet Community Support -
Problems with sort, search and write objects o an ArrayList
Hi
Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that.
2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
it runs but it returns +"false"+ even if i create an object with the exact same properties.
3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(
Any ideas?
Thank you!
Antonlavalampan wrote:
Hi
Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that. Create a custom comparator.
>
2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
it runs but it returns +"false"+ even if i create an object with the exact same properties.Implement hashCode and equals.
>
3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(Depends on what your requirement is, but yes, Serialization might work for you. Your classes should in that case implement Serializable.
Kaj
Maybe you are looking for
-
Huge Problem with iCloud...
Hopefully someone can help me out here. I have an iPhone and an iPad. Ever since setting up iCloud I've had a ton of problems and I don't know if what I want is possible. How can I set a criteria for when my contacts sync? My phone synced to my comp
-
Audio and video out of sync after exporting sequence
I'm a FCP user since years, but not so common with HD footage. Therefore I have an issue with my finished edited movie after exporting: Video and Audio are out of sync. My sequence settings are: HDV1080i50, 25fps, 48kHz, 16bit, Stereo. I used File->
-
How do I rearrange the order of items in a reminder list?
How do I rearrange the order of items in a reminders list?
-
How can I create 3D visuals using existing artwork?
I have designed some packaging artwork using Illustrator which looks fine although I would like to see the artwork as it would look when made up. The artwork will be used for pouches, bags and boxes. Is there a way of creating a generic 3D pouch, bag
-
Support for 4.x sensor signatures
Just a short question: does anybody know how long will there be development of signatures for 4.x sensors ? Will they be for free or is there also subscription on the way ? THX