Populate a JComboBox with an ArrayList from a different class - java

I'm currently stuck in this part of a class project... I need to create an ArrayList from a text file; text file has account numbers that need to be populated in a JComboBox. This is what I have so far... only the first account number populates missing the rest not sure what my mistake is
// AccountUtility class that reads file and creates ArrayList named test
public class AccountUtility {
ArrayList<String> test = new ArrayList<String>();
String[] number;
String columns[], accountNumber, customerName, openDate, balance;
int size;
public AccountUtility(){
BufferedReader in = null;
try{ // assume products.txt already exists
in = new BufferedReader(new FileReader("accounts.txt"));
String line = in.readLine();
while(line != null) {
columns = line.split("<>");
accountNumber = columns[0];
customerName = columns[1];
openDate = columns[2];
balance = columns[3];
line = in.readLine();
}
in.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
public ArrayList <String> getAccountNumbers( ){
ArrayList <String> test = new ArrayList<String>();
test.add(accountNumber);
return test;
//class with JComboBox (GUI)
public class BankAccountApp extends javax.swing.JFrame {
public BankAccountApp() {
initComponents();
setLocationRelativeTo(null);
AccountUtility gc = new AccountUtility();
for( String numbers : gc.getAccountNumbers()){
accountNumberComboBox.addItem(numbers);
}
}

I would have thought that what you want is
while(line != null) {
columns = line.split("<>");
accountNumber = columns[0];
test.add(accountNumber);
....
}
and
public ArrayList getAccountNumbers( ){
return test;
}

Related

Separating Parsing Method

I'm creating a program which handles SKU's. I currently have two classes in my program, the SKU class is the main class and a Store class in which an ArrayList is initialised and SKU objects are stored in the array. I currently have a method in my SKU class which takes input from a file, parses the data and stores the data using a String tokenizer in the objects variables and adds the objects to the array in the Store class. The problem I'm facing is that I'm wanting to separate the parsing method in the SKU class so that it simply reads from a line, and then have a separate method which takes a file input for the parser and finally update my Store class so that it initialises the products with the parsed data. Please, can you help me in regards to this?
My parsing method in the SKU class is currently as follows:
public void parser() {
try {
// create a Buffered Reader object instance with a FileReader
BufferedReader br = new BufferedReader(new FileReader("products.txt"));
// read from first line from the text file
String fileRead = br.readLine();
// skip first line from sample file as it contains headings
int lineNumber = 0;
// loop until all lines are read
while (fileRead != null)
{
if(lineNumber == 0) {
lineNumber++;
continue;
}
lineNumber++;
// use string.split to load a string array with the values from each line of
// the file, using a tab as the delimiter
String[] tokenize = fileRead.split("\t");
// assume file is made correctly
// and make temporary variables for the three types of data
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
// create temporary instance of SKU object
// and load with three data values
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
// read next line before looping
// if end of file reached
fileRead = br.readLine();
}
// close file stream
br.close();
}
// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
My Store class is as follows:
public class Store {
public static ArrayList<SKU> mySkuArrayList = new ArrayList<SKU>();
public void addSKU(SKU sku) {
mySkuArrayList.add(sku);
}
Split your code to three separate classes. SkuFile class represents text file where sku codes is stored, this class knows how to every sku entry stored and able to parse it. Sku class contains data. Store class contains
list of Sku and accept SkuFile in it's constructor.
class SkuFile {
private String path;
SkuFile(String path) {
this.path = path;
}
List<Sku> readAllSku() {
ArrayList<Sku> result = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(new File(path).toPath());
for(String skuLine : lines) {
result.add(parseFrom(skuLine));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
private Sku parseFrom(String data){
String[] tokenize = data.split("\t");
productCode = tokenize[0];
description = tokenize[1];
price = new BigDecimal(tokenize[2]);
return new Sku(productCode, description, price);
}
}
class Sku {
private String code;
private String description;
private BigDecimal price;
Sku(String code, String description, BigDecimal price) {
this.code = code;
this.description = description;
this.price = price;
}
//getters setters methods
}
class Store {
private List<Sku> skus;
Store(SkuFile file) {
skus = file.readAllSku();
}
}
class Test {
public static void main(String[] args) {
Store store = new Store(new SkuFile("products.txt"));
}
}
One way to handle this is by making the parse method return a list of tokenizers(e.g. List tokenizeList) and a second method which takes that list as input and populates the SkuArrayList
Possible implementation of the parser method
public List<String[]> parser() {
List<String[]> tokenizeList = new ArrayList<>();
try {
... /*file opening logic*/
while (fileRead != null)
{
.../*line counting logic*/
String[] tokenize = fileRead.split("\t");
tokenizeList.add(tokenize);
fileRead = br.readLine();
}
// close file stream
br.close();
}// handle exceptions
catch (FileNotFoundException fnfe)
{
System.out.println("file not found");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return tokenizeList;
}
Possible implementation of the populate store method
public void populateStore(List<String[]> tokenizeList) {
for(String[] tokenize: tokenizeList) {
String tempProductCode = tokenize[0];
String tempDescription = tokenize[1];
BigDecimal tempPrice = new BigDecimal(tokenize[2]);
SKU tempObj = new SKU();
tempObj.setProductCode(tempProductCode);
tempObj.setDescription(tempDescription);
tempObj.setPrice(tempPrice);
// add to array list
Store.mySkuArrayList.add(tempObj);
}
}
And the main method from where you call these two methods
public void foo() {
populateStore(parser());
}

Returning an arraylist to be accessed from another class

I'm new to Stackoverflow, so here goes.
I'm currently working on an assignment that requires to read from a csv file and place it into some sort of data collection.
I've gone with an arraylist. But what I seem to be stuck with is that I'm attempting to use my ReadWriteFile class to read the csv file into an arraylist (which works). But I need to somehow access that array in my GUI class to fill my JTable with said data.
After looking through similar help requests, I haven't been able to find any success.
My current code from my ReadWriteFile class;
public static void Read() throws IOException {
String lines = "";
String unparsedFile = "";
String dataArray[];
String col[] = { "COUNTRY", "MILITARY", "CIVILIAN", "POWER" };
FileReader fr = new FileReader("C:/Users/Corbin/Desktop/IN610 - Assignment 1/Programming3_WWII_Deaths.csv");
BufferedReader br = new BufferedReader(fr);
while ((lines = br.readLine()) != null) {
unparsedFile = unparsedFile + lines;
}
br.close();
dataArray = unparsedFile.split(",");
for (String item : dataArray) {
System.out.println(item);
}
ArrayList<String> myArrayList = new ArrayList<String>();
for (int i = 0; i < dataArray.length; i++) {
myArrayList.add(dataArray[i]);
}
}
So what my question is; How can I create a method that returns the values from the array, so I can access that array in my GUI class and add each element to my JTable?
Thanks!
Here is some simple example of how to return array in the method and how to use it in GUI class:
public class Main {
public String[] readFromFile (String filePath) {
ArrayList<String> yourList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
// read file content to yourList
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return yourList.toArray(new String[yourList.size()]);
}
}
And the GUI class:
public class GUI extends JFrame {
private JTable jTable;
public GUI() {
jTable = new JTable(10, 10);
this.getContentPane().add(jTable);
this.setVisible(true);
this.pack();
}
public void passArrayToTable(Main mainClass) {
String[] array = mainClass.readFromFile("C:\\file.csv");
// for (String s : array) {
// add values to jTable with: jTable.setValueAt(s,row,column);
// }
}
public static void main(String[] args) {
new GUI().passArrayToTable(new Main());
}
}

ArrayOutofBoundsException - Attempting to read to/from file into Hash Map

I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)

Modify class to write exceptions to text file

I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

How to use String.split with a text file to add to a simple array

My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.
My code so far :
public class VersionChooser {
private Scanner scan;
private StockManager aManager = new StockManager("StockManager");
public VersionChooser() {
this.scan = new Scanner(System.in);
}
public void chooseVersion() {
this.readData();
this.runTextOption();
}
private void runTextOption() {
StockTUI tui = new StockTUI(this.aManager);
}
public StockManager readData() {
String fileName;
System.out.println("Enter the name of the file to be used");
fileName = this.scan.nextLine();
System.out.println(fileName);
try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
StandardCharsets.UTF_16)) {
for (String line; (line = br.readLine()) != null;) {
final String[] data = line.split(",");
StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
this.aManager.getStockList().add(record);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
StockRecord :
public class StockRecord {
private String date;
private double closingPrice;
public StockRecord(String date, double closingPrice) {
this.date = date;
this.closingPrice = closingPrice;
}
public String getDate() {
return this.date;
}
public double getClosingPrice() {
return this.closingPrice;
}
public String toString() {
return "On " + this.date + " this stock had a closing price of $"
+ this.closingPrice;
}
}
Step1 : Read the file line by line.
Step2: Split the line by ","
Step3 : Construct the String[] to StockRecord.
try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
StandardCharsets.UTF_8)) {
List<StockRecord> stocks = new ArrayList<StockRecord>();
br.readLine() ; // to avoid first line
for (String line; (line = br.readLine()) != null;) { // first step
final String[] data = line.split(","); // second step
StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
stocks.add(record); // third step
}
} catch (IOException e) {
e.printStackTrace();
}
Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly

Categories