How do I print out my Hashmap in Java - java

Okay so I have a hashmap of the class Stock, which basically has data about different stocks from yahoo that a user can enter. Each time they enter a new stock, I add that Stock class to the hashmap, and I don't know how to print out the whole hashmap and display everything entered so far
public class AS4stocks {
static Map<String, Stock> mappin = new HashMap<String, Stock>();
public static void main(String[] args) throws IOException {
int menuchoice;
do {
Scanner in1 = new Scanner(System.in);
System.out
.println("What would you like to do \n1) Print table\n2) Add a stock\n3) Do something else");
menuchoice = in1.nextInt();
switch (menuchoice) {
case 1:
System.out.println(mappin);
break;
case 2:
System.out.print("Enter the stock's ticker symbol\n");
String ticker = in1.next();
addstock(ticker);
break;
case 3:
break;
}
} while (menuchoice != 0);
}
private static void Printtable(Map<String, Stock> mappin) {
fo
}
private static void addstock(String ticker) throws IOException {
URL url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s="
+ ticker + "&f=snd1ohgpvwm3m4&e=.csv");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
Object[] otable = new String[11];
int counter = 0;
while ((line = br.readLine()) != null) {
String str = line;
StringTokenizer st = new StringTokenizer(str, ",\"");
while (st.hasMoreTokens()) {
String adder = st.nextToken();
otable[counter] = adder;
if (counter == 0) {
System.out.println("-------------------" + adder
+ "-------------------");
System.out.print("Ticker: ");
}
if (counter == 2) {
System.out.print("Company: ");
}
if (counter == 3) {
System.out.print("Open: ");
}
if (counter == 4) {
System.out.print("High: ");
}
if (counter == 5) {
System.out.print("Low: ");
}
if (counter == 6) {
System.out.print("Close: ");
}
if (counter == 7) {
System.out.print("Volume: ");
}
if (counter == 8) {
System.out.print("52 Week Range: ");
}
if (counter == 9) {
System.out.print("50 Day Average: ");
}
if (counter == 10) {
System.out.print("200 Day Average: ");
}
System.out.println(adder);
counter++;
}
Stock snew = new Stock(otable);
mappin.put(ticker, snew);
}
System.out.println();
}
static class Stock {
String compname;
String ticker;
String date;
String open;
String high;
String low;
String close;
String volume;
String range;
String average50;
String average200;
public Stock(Object otable[]) {
compname = (String) otable[0];
ticker = (String) otable[1];
date = (String) otable[2];
open = (String) otable[0];
high = (String) otable[1];
low = (String) otable[2];
close = (String) otable[3];
volume = (String) otable[4];
range = (String) otable[5];
average50 = (String) otable[6];
average200 = (String) otable[7];
}
}
}

You'll need to iterate through the map and print what you want for each entry. Easiest way to iterate through the values would be:
for (Stock stock : mappin.values()) {
System.out.println(stock.toString());
}
This assumes of course your Stock class has meaningful output for toString()

Related

Take user input and search through 2D array and printout the result

I am trying to make a program that takes input from the user, searches through 2D array and prints out if the input matches data from the arrays. So, basically if the user types in VA, it should output Virginia. I am reading data from a Binary file that has 2 rows of data. The 1st row contains 2 letter abbreviations for all the states and the 2nd row contains the state names. For example: VA Virginia and in new line FL Florida and so on. Below is what I have so far. readStateFile() method works fine. I just need some help with getState method.
public static void main(String[] args) throws IOException {
try {
int age = getAge();
String[][] states = readStateFile();
String state = getState(states);
int ZIPCode = getZIPcode();
System.out.printf("\nAge:\t\t%d\n", age);
System.out.printf("Address:\t%s %s\n\n", ZIPCode, state);
System.out.println("Your survey is complete. " + "Your participation has been valuable.");
} catch (CancelledSurveyException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Thank you for your time.");
}
}
private static String getState(String[][] states) throws IOException {
states = readStateFile();
String in = "";
String[][] abb;
abb = states;
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
Scanner st = new Scanner(System.in);
in = st.next();
if (in.equals("q")) {
System.out.println("Your survey was cancelled.\n" + "Thank you for your time.");
System.exit(0);
}
if (abb.equals(states)) {
for (int i = 0; states[0][i] != null; i++) {
if (abb.equals(states[0][i])) {
for (int state = 1; state <= 100; state++) {
System.out.println(states[0][i]);
}
}
}
} else {
System.out.println("You've entered invalid state abbrevation.");
}
return in;
}
private static String[][] readStateFile() throws IOException {
String states[][] = new String[50][50];
try {
FileInputStream fstream = new FileInputStream("states copy.bin");
DataInputStream inputFile = new DataInputStream(fstream);
for (int i = 0, j = i + 1; i < 50; i++) {
states[i][0] = inputFile.readUTF();
states[i][j] = inputFile.readUTF();
// System.out.println(states);
}
inputFile.close();
return states;
} catch (EOFException e) {
System.out.println("Survey Cancelled");
}
return states;
} ```
Instead of using a multidimensional array, it might be more helpful to use a HashMap.
Each abbreviation is used as a key, and the name of the state can be found using that key as a lookup. Illustrated below:
public static void main(final String[] args)
{
try
{
final Map<String, String> states = readStateFile();
// Display the contents of the file
// for (final Map.Entry<String, String> s : states.entrySet())
// {
// System.out.println(s.getKey() + " = " + s.getValue());
// }
final String state = getState(states);
final int age = getAge();
final int postalCode = getZIPcode();
System.out.println();
System.out.printf("Age:\t\t%d\n", Integer.valueOf(age));
System.out.printf("Address:\t%s %s\n\n", Integer.valueOf(postalCode), state);
System.out.println("Your survey is complete. Your participation has been valuable.");
}
catch (final IOException ex)
{
System.out.println(ex.getMessage());
}
System.out.println("Thank you for your time.");
}
private static String getState(final Map<String, String> states)
{
System.out.println("Please enter the 2 letter state abbrevation or 'q' to quit: ");
final StringBuilder sb = new StringBuilder();
try (final Scanner st = new Scanner(System.in))
{
final String stateAbbrev = st.next().toUpperCase(Locale.getDefault());
if ("Q".equals(stateAbbrev))
{
System.out.println("Your survey was cancelled." + System.lineSeparator() + "Thank you for your time.");
System.exit(0);
}
if (states.containsKey(stateAbbrev))
{
final String stateName = states.get(stateAbbrev);
sb.append(stateName);
}
else
{
System.out.println("You've entered an invalid state abbrevation: " + stateAbbrev);
}
}
return sb.toString();
}
private static Map<String, String> readStateFile() throws IOException
{
final List<String> lines = Files.readAllLines(Paths.get("C:/states copy.bin"));
// Get a list of items, with each item separated by any whitespace character
final String[] stateAbbrev = lines.get(0).split("\\s");
final String[] stateNames = lines.get(1).split("\\s");
final Map<String, String> states = new HashMap<>();
for (int i = 0; i < stateAbbrev.length; i++)
{
states.put(stateAbbrev[i], stateNames[i]);
}
return states;
}

Read and write an ArrayList to a .txt file

I can't get this part of my project to work. (fileOut() and fileIn() methods). I would appreciate any help!
I am trying to construct a method to open a text file and to write the details of an ArrayList of type to it.
I am also trying to construct a second method to open the text file containing details of all the bank’s accounts and uses the incoming data to create BankAccount objects using a BankAccount Constructor and storing each account in an ArrayList.
Please note that other methods in the class need to use the information stored in the arraylist(s).
Here is the main bit of code to focus on(reading and writing):
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is the code for the whole class:
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
public class MyBankController
{
private ArrayList<BankAccount> bankAccArrayList;
public MyBankController()
{
bankAccArrayList = new ArrayList<BankAccount>();
}
public void createAccount (String accNum, String custName)
{
bankAccArrayList.add(new BankAccount( accNum,custName));
printAccountDetails(bankAccArrayList.get(bankAccArrayList.size()-1));
}
private void printAccountDetails(BankAccount incomingAcc)
{
JOptionPane.showMessageDialog(null,incomingAcc.toString(),"Account Details",JOptionPane.PLAIN_MESSAGE);
}
public void listAllAccounts()
{
String outputStr = "List of all accounts :\n\n";
for(BankAccount account : bankAccArrayList){
outputStr += account + "\n\n";
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Accounts",JOptionPane.PLAIN_MESSAGE);
}
public void listAllActiveAccounts()
{
String outputStr = "List of all active accounts :\n\n";
for(BankAccount account : bankAccArrayList){
if(account.getActive()) {
outputStr += account + "\n\n";
}
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Active Accounts",JOptionPane.PLAIN_MESSAGE);
}
private int getIndex(String bankAccNum)
{
for (int i = 0; i < bankAccArrayList.size(); i++) {
if (bankAccNum.equals(bankAccArrayList.get(i).getAccNumber()))
{
return i;
}
}
JOptionPane.showMessageDialog(null,"Bank Account Number: " + bankAccNum + " is invalid","Error wrong account number",JOptionPane.ERROR_MESSAGE);
return -1;
}
public void makeWithdrawal(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeWithdraw(amount);
}
}
public void makeLodgement(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeLodgement(amount);
}
}
public void displayAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
JOptionPane.showMessageDialog(null,(bankAccArrayList.get(getIndex(accNumber)).toString()),"Accounts Details",JOptionPane.PLAIN_MESSAGE);
}
}
public void closeAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).closeAccount();
}
}
public void removeAccount(String accNumber)
{
int index = getIndex(accNumber);
if(index != -1){
BankAccount myAcc = bankAccArrayList.get(index);
if ((myAcc.getActive() == false) && (myAcc.getAccBalance() == 0)){
bankAccArrayList.remove(index);
}else if((myAcc.getActive() == false) && (myAcc.getAccBalance() > 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account has a balance,do you wish to withdraw this balance " +
"so as to remove the account ?"," Balance in inactive account",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
myAcc.makeWithdraw(myAcc.getAccBalance());
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else if((myAcc.getActive() == true) && (myAcc.getAccBalance() == 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status, do you wish to change its status so as to remove account ?"
,"Account Active",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else{
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status and a balance, do you wish to close the account so as remove it"
,"Account Active with Balance",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.closeAccount();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
public void customerInterface()
{
String accNumber = JOptionPane.showInputDialog(null,"Please enter your account number","Account Login",JOptionPane.PLAIN_MESSAGE);
if(getIndex(accNumber) != -1)
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Make a lodgment:\n\n [2] Make a withdrawal:\n\n [3] Display account details:\n\n" +
" [4] Close account:\n\n [5] Exit","MyBank ATM",JOptionPane.PLAIN_MESSAGE);
if (numOption == null) //User presses cancel or 'x'.
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE);
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Brings up lodgement interface
String amount = JOptionPane.showInputDialog("Please enter the amount you would like to lodge.");
makeLodgement(accNumber, Double.parseDouble(amount)); // Lodges amount into account.
customerInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
String amount = JOptionPane.showInputDialog("Please enter the amount you wish to withdraw.");
makeWithdrawal(accNumber, Double.parseDouble(amount)); //Call on makeWithdrawl method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
displayAccount(accNumber); //Calls on displayAccount method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
closeAccount(accNumber); //Call on close account method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
return; //Exits system.
}
else if(Integer.parseInt(numOption) > 5 || Integer.parseInt(numOption) < 1) //If number enter is outside of 1-5.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-5 and try again.","Error",JOptionPane.ERROR_MESSAGE);
customerInterface();
}
}
}
public void bankInterface()
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Display All Accounts:\n\n [2] Display All Active Accounts:\n\n [3] Open a New Account:\n\n" +
" [4] Close an Existing Account:\n\n [5] Run Start of Day:\n\n [6] Run End of Day:\n\n [7] Exit:","MyBank System",JOptionPane.PLAIN_MESSAGE);
if (numOption == null)
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE); //User presses cancel or 'x'.
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Displays all accounts.
listAllAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
//Display all active accounts.
listAllActiveAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
//Open a new account
String accNum = JOptionPane.showInputDialog("Please allocate an account number:");
String custName = JOptionPane.showInputDialog("Please enter the customers name:");
createAccount (accNum, custName);
bankInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
//Close an existing account.
String accNumber = JOptionPane.showInputDialog("Please enter the account number you would like to close:");
closeAccount(accNumber);
bankInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
//Run start of day file.
fileIn();
bankInterface();
}
else if(Integer.parseInt(numOption) == 6)
{
//Run end of day file.
fileOut();
bankInterface();
}
else if(Integer.parseInt(numOption) == 7)
{
//Exits system.
return;
}
else if(Integer.parseInt(numOption) > 7 ||Integer.parseInt(numOption) < 1) //If user enters number outside of 1-7.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-7 and try again.","Error",JOptionPane.ERROR_MESSAGE);
bankInterface();
}
}
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
In your fileIn method, you're trying to add a String to an ArrayList of type BankAccount. Instead of aList.add(line), you should use aList.add(new BankAccount(line)).
Assuming your BankAccount constructor takes only a single String parameter, this should work.
Full method:
public void fileIn()
{
List<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(new BankAccount(line));
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
aList.forEach(System.out::println); // Java8
}
I've also changed your aList to use the List interface, and added a lambda to print each value in aList at the end.

How do I export the ArrayList to a CSV file

I have this code, it gets the average grade, but I need to export the arraylist Hell to a CSV file. How do I do this?
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.text.*;
public class hello3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.printf("Please enter the name of the input file: ");
String input_name = in.next();
System.out.printf("Please enter the name of the output CSV file: ");
String csv_name = in.next();
System.out.printf("Please enter the name of the output pretty-print file: ");
String pretty_name = in.next();
processGrades(input_name, csv_name, pretty_name);
System.out.printf("\nExiting...\n");
}
public static void processGrades (String input_name, String csv_name, String pretty_name)
{
PrintWriter csv = null;
PrintWriter pretty = null;
String[][] data = readSpreadsheet(input_name);
boolean resultb = sanityCheck(data);
int length = data.length;
ArrayList<String> test_avg = new ArrayList<String>();
ArrayList<String> HW_avg = new ArrayList<String>();
ArrayList<String> NAME = new ArrayList<String>();
ArrayList<String> ColN = new ArrayList<String>();
ArrayList<String> Hell = new ArrayList<String>();
for(int row = 1; row<length; row++)
{
String name = data[row][0];
String name2 = data[row][1];
String Name = name+" "+name2;
int test1 = Integer.parseInt(data[row][2]);
int test2 = Integer.parseInt(data[row][3]);
int test3 = Integer.parseInt(data[row][4]);
int Test = (test1+test2+test3)/3;
String Testav = Integer.toString(Test);
int hw1 = Integer.parseInt(data[row][5]);
int hw2 = Integer.parseInt(data[row][6]);
int hw3 = Integer.parseInt(data[row][7]);
int hw4 = Integer.parseInt(data[row][8]);
int hw5 = Integer.parseInt(data[row][9]);
int hw6 = Integer.parseInt(data[row][10]);
int hw7 = Integer.parseInt(data[row][11]);
int HW = (hw1+hw2+hw3+hw4+hw5+hw6+hw7)/7;
int[] trying = {Test, HW};
int low = find_min(trying);
String grade = null;
if(low>=90)
{
grade ="A";
}
if(low < 90&& low>= 80)
{
grade = "B";
}
if(low <80&&low>=70)
{
grade ="C";
}
if(low<70&&low>=60)
{
grade="D";
}
if(low<60)
{
grade = "F";
}
String Lows = Integer.toString(low);
String HWav = Integer.toString(HW);
test_avg.add(Testav);
HW_avg.add(HWav);
NAME.add(Name);
Hell.add(Name);
Hell.add(Testav);
Hell.add(HWav);
Hell.add(Lows);
Hell.add(grade);
System.out.println(Hell);
System.out.printf("\n");
}
}
public static int find_min(int[] values)
{
int result = values[0];
for(int i = 0; i<values.length; i++)
{
if(values[i]<result)
{
result = values[i];
}
}
return result;
}
public static boolean sanityCheck(String[][] data)
{
if (data == null)
{
System.out.printf("Sanity check: nul data\n");
return false;
}
if(data.length<3)
{
System.out.printf("Sanity check: %d rows\n",data.length);
return false;
}
int cols= data[0].length;
for(int row = 0; row<data.length; row++)
{
int current_cols = data[row].length;
if(current_cols!=cols)
{
System.out.printf("Sanity Check: %d columns at rows%d\n", current_cols, row);
return false;
}
}
return true;
}
public static String[][] readSpreadsheet(String filename)
{
ArrayList<String> lines = readFile(filename);
if (lines == null)
{
return null;
}
int rows = lines.size();
String[][] result = new String[rows][];
for (int i = 0; i < rows; i++)
{
String line = lines.get(i);
String[] values = line.split(",");
result[i] = values;
}
return result;
}
public static ArrayList<String> readFile(String filename)
{
File temp = new File(filename);
Scanner input_file;
try
{
input_file = new Scanner(temp);
} catch (Exception e)
{
System.out.printf("Failed to open file %s\n",
filename);
return null;
}
ArrayList<String> result = new ArrayList<String>();
while (input_file.hasNextLine())
{
String line = input_file.nextLine();
result.add(line);
}
input_file.close();
return result;
}
}
Any help would be appreciated. thank you.
Broadly, you need to open a file with the name you require, and a writer in a loop - like this:
File csvFile = new File(csvName);
try (PrintWriter csvWriter = new PrintWriter(new FileWriter(csvFile));){
for(String item : list){
csvWriter.println(item);
}
} catch (IOException e) {
//Handle exception
e.printStackTrace();
}
Obviously you will have to print some commas as required

inefficient looping in java

This is my csv data:
Name,Code,Price,Colour,Type,Stock
A,1001,35000,Red,Car Paint,54
B,1002,56000,Blue,House Paint,90
As you can see, my coding is inefficient.
This is because all the textfields in netbeans do not allow same variable names, I have to give different variable names to each text field (Example: code1, code2, code3, name1, name2,name3)
Can someone help me on how to loop this data so they do it four times and i dont have to repeat the coding? and to skip the process if the fields are blank.
The following is my coding:
try
{
for(int z=0; z<4;z++)
{
String code1;
code1=this.text1.getText();
System.out.println("this is the code: " + code1);
String qty;
int qty1;
qty=this.quantity1.getText();
qty1=Integer.parseInt(qty);
System.out.println("quantity: "+qty1);
String code2;
code2=this.text2.getText();
System.out.println("this is the code: " + code2);
int qty2;
qty=this.quantity2.getText();
qty2=Integer.parseInt(qty);
System.out.println("quantity: "+qty2);
String code3;
code3=this.text3.getText();
System.out.println("this is the code: " + code3);
int qty3;
qty=this.quantity2.getText();
qty3=Integer.parseInt(qty);
System.out.println("quantity: "+qty3);
String code4;
code4=this.text4.getText();
System.out.println("this is the code: " + code4);
int qty4;
qty=this.quantity2.getText();
qty4=Integer.parseInt(qty);
System.out.println("quantity: "+qty4);
int sum=0;
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\product.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[6];
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
for (int i = 0; i < dataArr.size(); i++) {
String[] nameData = dataArr.get(i);
if (nameData[1].equals(code1)) {
System.out.println("Found name.");
name1.setText(""+ nameData[0]);
int price;
price=Integer.parseInt(nameData[2]);
int totalprice=qty1*price;
String total=Integer.toString(totalprice);
price1.setText(total);
sum=sum+totalprice;
break;
}
}
for (int i = 0; i < dataArr.size(); i++) {
String[] nameData = dataArr.get(i);
if (nameData[1].equals(code2)) {
System.out.println("Found name.");
name2.setText(""+ nameData[0]);
int price;
price=Integer.parseInt(nameData[2]);
int totalprice=qty2*price;
String total=Integer.toString(totalprice);
price2.setText(total);
sum=sum+totalprice;
break;
}
}
for (int i = 0; i < dataArr.size(); i++) {
String[] nameData = dataArr.get(i);
if (nameData[1].equals(code3)) {
System.out.println("Found name.");
name3.setText(""+ nameData[0]);
int price;
price=Integer.parseInt(nameData[2]);
int totalprice=qty3*price;
int totalprice3=totalprice;
String total=Integer.toString(totalprice);
price3.setText(total);
sum=sum+totalprice;
break;
}
}
for (int i = 0; i < dataArr.size(); i++) {
String[] nameData = dataArr.get(i);
if (nameData[1].equals(code4)) {
System.out.println("Found name.");
name4.setText(""+ nameData[0]);
int price;
price=Integer.parseInt(nameData[2]);
int totalprice=qty4*price;
int totalprice4=totalprice;
String total=Integer.toString(totalprice);
price4.setText(total);
sum=sum+totalprice;
break;
}
}
total1.setText("Rp. "+sum);
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
Why don't you use a library like http://commons.apache.org/proper/commons-csv/
Solving this problem is actually rather straight forward if you break it down into separate parts.
First you need to solve the problem of loading the data into an internal data representation that is easy to use. Just loading the file into Java is rather simple and you have already done this:
BufferedReader csvFile = new BufferedReader(new FileReader(new File(path)));
String line = "start";
int count = 0;
while((line = csvFile.readLine()) != null){
System.out.println(line);
}
csvFile.close();
The next problem is splitting the line and store it in a meaningful way - for each line.
HashMap<Integer, String> record = new HashMap<Integer, String>();
String[] raw = line.split(",");
for(int i=0;i<raw.length; i++){
record.put(i, raw[i]);
}
Now you state you only want to store records that have non-empty fields so we need to check for that:
HashMap<Integer, String> record = new HashMap<Integer, String>();
String[] raw = line.split(",");
Boolean store = true;
for(int i=0;i<raw.length; i++){
if(raw[i].equals("") || raw[i].equals(null)){
store = false;
break;
}
record.put(i, raw[i]);
}
if(store)
csvData.add(record);
Now, you can load each record of the csv file as a dictionary that you can easily use. All that remains is to save a list of these dictionaries.
ArrayList<Map<Integer, String>> csvData = new ArrayList<Map<Integer, String>>();
BufferedReader csvFile = new BufferedReader(new FileReader(new File(path)));
String line = "start";
int count = 0;
while((line = csvFile.readLine()) != null){
if(count == 0){//skip first line
count++;
continue;
}
HashMap<Integer, String> record = new HashMap<Integer, String>();
String[] raw = line.split(",");
Boolean store = true;
for(int i=0;i<raw.length; i++){
if(raw[i].equals("") || raw[i].equals(null))
{
store = false;
break;
}
record.put(i, raw[i]);
}
if(store)
csvData.add(record);
}
csvFile.close();
Full code snippet that loads in data and easily access whatever information you want:
public class Main {
public static final int NAME = 0;
public static final int CODE = 1;
public static final int PRICE = 2;
public static final int COLOR = 3;
public static final int TYPE = 4;
public static final int STOCK = 5;
public static void main(String[] args) throws IOException{
ArrayList<Map<Integer, String>> csvData = loadCSVFile("C:\\path\\to\\file\\products.txt");
//Print some of the data
System.out.println("---------------------------");
for(Map<Integer, String> record : csvData){
printInfo(record);
}
}
public static ArrayList<Map<Integer, String>> loadCSVFile(String path) throws IOException{
ArrayList<Map<Integer, String>> csvData = new ArrayList<Map<Integer, String>>();
BufferedReader csvFile = new BufferedReader(new FileReader(new File(path)));
String line = "start";
int count = 0;
while((line = csvFile.readLine()) != null){
if(count == 0){
count++;
continue;
}
HashMap<Integer, String> record = new HashMap<Integer, String>();
String[] raw = line.split(",");
Boolean store = true;
for(int i=0;i<raw.length; i++){
if(raw[i].equals("") || raw[i].equals(null))
{
store = false;
break;
}
record.put(i, raw[i]);
}
if(store)
csvData.add(record);
}
csvFile.close();
return csvData;
}
public static void printInfo(Map<Integer, String> record){
System.out.println(record.get(CODE) + " : " + record.get(TYPE));
System.out.println(record.get(NAME) + " : " + record.get(STOCK) + " : " + record.get(PRICE));
System.out.println("---------------------------");
}
}

method to read array list to find certain string and value

public class array {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line;
List<String> list = new ArrayList<String>();
while((line=reader.readLine()) !=null)
{
list.add(line);
}
reader.close();
for (String s : list) {
System.out.println(s);
}
}
}
I have fruit.txt
apple 20 good
orange 30 good
banana 40 needmore
how do I retrieve how many oranges I have from the array list.
I want the program to read the user input in this case "orange" and display out 30 and the status is not good.
ideal output is
You have orange 30 of them and status is good
Try the following updated class.
public class array
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line;
boolean found = false;
int count = 0;
List<String> list = new ArrayList<String>();
while ((line = reader.readLine()) != null)
{
String[] items = line.split(" ");
if (fruit.equals(items[0]))
{
found = true;
count = Integer.parseInt(items[1]);
break;
}
list.add(line);
}
reader.close();
if (found)
{
System.out.println("You have " + fruit + " " + count + " of them and status is good");
}
}
}
You need to split your Strings in your List, and then print each elements of your array obtained within your specified string format: -
for (String s : list) {
String[] tokens = s.split(" ");
if (tokens[0].equals(fruit)) {
System.out.println("You have " + tokens[0] + " " + tokens[1] +
" of them and status is " + tokens[2]);
break;
}
}
Or, you can use: -
System.out.format("You have %s %s of them and status is %s",
tokens[0], tokens[1], tokens[2]);
You will need to split up the lines into the three fields using a StringTokenizer. Then I would create a new class to hold that information.
When you read a line, split the values into String array like this:
while((line=reader.readLine()) !=null)
{
String [] values = line.split(" ");
list.add("You have "+values[0] + " " + values[1] " of them and status is "+values[2] );
}
Not tested but should work, try:
public class array {
public static class Fruit {
private String name;
private String count;
private String status;
public Fruit(String name, String count, String status) {
this.name = name;
this.count = count;
this.status = status;
}
public String getName() {
return name;
}
public String getCount() {
return count;
}
public String getStatus() {
return status;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));
System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line= "";
HashMap<String, Fruit> map = new HashMap<String, Fruit>();
while ((line = reader.readLine()) != null) {
String[] strings = line.split(" ");
map.put(strings[0], new Fruit(strings[0], strings[1], strings[2]));
}
reader.close();
System.out.print("You have " + fruit + " " + map.get(fruit).getCount() + " of them and status is: " + map.get(fruit).getStatus());
}
}

Categories