Java Stock Viewer Application Issue - java

For the past few hours, I've been trying to figure out my problem with this stock viewer application. I had it working perfectly fine yesterday, did some edits today, then attempted to revert it back to its original form. Now, instead of printing all the stock prices from the dates listed in StockClient (January 7, 2016 to January 7, 2017), it starts in February instead. Please help!
STOCK VIEWER CLASS:
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
public class StockViewer
{
private ArrayList<String> dates;
private ArrayList<String> opens;
private ArrayList<String> highs;
private ArrayList<String> lows;
private ArrayList<String> closes;
private ArrayList<String> volumes;
private ArrayList<String> adjCloses;
private String sym;
private boolean success = false;
public StockViewer(String symbol)
{
dates = new ArrayList<String>();
opens = new ArrayList<String>();
highs = new ArrayList<String>();
lows = new ArrayList<String>();
closes = new ArrayList<String>();
volumes = new ArrayList<String>();
adjCloses = new ArrayList<String>();
sym = symbol;
}
public void viewStock(GregorianCalendar begin, GregorianCalendar fin)
{
while(!success)
{
String url = "http://chart.finance.yahoo.com/table.csv?s=" + sym +
"&a=" + begin.get(Calendar.MONTH) +
"&b=" + begin.get(Calendar.DAY_OF_MONTH) +
"&c=" + begin.get(Calendar.YEAR) +
"&d=" + fin.get(Calendar.MONTH) +
"&e=" + fin.get(Calendar.DAY_OF_MONTH) +
"&f=" + fin.get(Calendar.YEAR) +
"&g=d&ignore=.csv";
try
{
URL yhooFin = new URL(url);
URLConnection data = yhooFin.openConnection();
Scanner input = new Scanner(data.getInputStream());
if(input.hasNext()) // skip a line (that's the header)
input.nextLine();
// start reading data
while(input.hasNextLine())
{
String line = input.nextLine();
String[] elements = line.split(",");
success = true;
dates.add(elements[0]);
opens.add(elements[1]);
highs.add(elements[2]);
lows.add(elements[3]);
closes.add(elements[4]);
volumes.add(elements[5]);
adjCloses.add(elements[6]);
for(int count = 0; count < elements.length; count++)
{
if(count < 6)
System.out.print(elements[count] + " - ");
else
System.out.print(elements[count] + "\n");
}
}
}
catch(Exception e)
{}
}
}
public void viewStockCurrent(GregorianCalendar c1, GregorianCalendar c2)
{
viewStock(c1, c2);
}
}
STOCK CLIENT CLASS:
import java.util.*;
public class StockClient
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a stock symbol: ");
String symbol = scan.next();
StockViewer stock = new StockViewer(symbol);
GregorianCalendar start = new GregorianCalendar(2016, 1, 7);
GregorianCalendar end = new GregorianCalendar(2017, 1, 7);
stock.viewStock(start, end);
}
}

Month property is zero based, you have wrong value in
GregorianCalendar start = new GregorianCalendar(2016, 1, 7);
GregorianCalendar end = new GregorianCalendar(2017, 1, 7);
See Calendar.MONTH for details.
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Related

Is there any way to store the elements present in the file to the to the array of the object in java

The program is giving correct output when System.out.println(mem[i].memName); but the array of class "member" is giving output (alex alex alex alex) i.e of the last line of the file (mentioned at the END of the CODE)
it should give all the names listed in the file.
import java.io.*;
import java.util.*;
class member//CLASS TO BE USED AS ARRAY TO STORE THE PRE REGISTERED MEMBERS FED INSIDE
{ //THE FILE "member.txt"
static int memId;
static String memName, memEmail, memPh, date;
}
public class entry// file name
{
static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
static LocalDateTime now = LocalDateTime.now();
static Scanner input = new Scanner(System.in);
static member[] mem = new member[100];
static trainer[] tr = new trainer[100];
static FileWriter fwriter = null;
static BufferedWriter bwriter = null;
static FileReader fread = null;
static BufferedReader bread = null;
static void memberEntry() {
int i = 0;
System.out.println("NEW MEMBER IS BEING ADDED");
try {
fwriter = new FileWriter("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM
PROJECT\\member.txt
",true);
bwriter = new BufferedWriter(fwriter);
System.out.println("Member ID is being automatically genrated");
int autoID = 101 + getMemberRecords();//Fetching the number of members so that ID can
//Be genrated automatically
i = autoID % 100;//jumping toward the next loaction location
System.out.println("Member ID of new member is" + autoID);
mem[i].memId = autoID;
System.out.print("Enter the name of the member:");
mem[i].memName = input.next();
System.out.print("Enter the email address of memeber:");
mem[i].memEmail = input.next();
System.out.print("Enter the contact number of memeber:");
mem[i].memPh = input.next();
System.out.println("Date has been feeded automatically:" + dtf.format(now));
mem[i].date = dtf.format(now);
bwriter.write(String.valueOf(mem[i].memId));
bwriter.write("|");
bwriter.write(mem[i].memName);
bwriter.write("|");
bwriter.write(mem[i].memEmail);
bwriter.write("|");
bwriter.write(mem[i].memPh);
bwriter.write("|");
bwriter.write(mem[i].date);
bwriter.write("\n");
System.out.println("MEMBER CREATED SUCCESSFULLY");
System.out.println("---------------------------------------");
bwriter.close();
} catch (IOException e) {
System.out.print(e);
}
}
static int getMemberRecords() {
int count = 0, i = 0;
try {
fread = new FileReader("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM PROJECT\\member.txt");
bread = new BufferedReader(fread);
String lineRead = null;
while ((lineRead = bread.readLine()) != null)//Just to get to know the number of member
//alreadyinside the file
{
String[] t = lineRead.split("\\|");
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);//should print the 1st name present in the name
//i.e, RAVI
} catch (IOException e) {
System.out.println(e);
}
return count;
}
public static void main(String[] args) throws IOException {
System.out.println("Total number of accounts:" + getMemberRecords());
}
}
Elements stored in the file:
101|RAVI|itisadi23#gmai.com|9102019656|2020/04/30
102|aditya|adi#gmail.com|9386977983|2020/04/30
103|anurag|anu#ymail.com|10000000000|2020/04/30
104|alex|alex123#mail.com|2829578303|2020/04/30
Expected output:
RAVI
Total number of accounts = 4
My output:
alex
Total number of accounts=4
In Short it is giving last name as output no matter what index number is given to fetch the data.
Your member class members must not be static, if they are, they're shared by every member class object.
The other problem is that your member array nodes are not being initialized, you'll need:
Live demo
class member
{
int memId; //non-static
String memName, memEmail, memPh, date; //non-static
}
and
//...
while ((lineRead = bread.readLine()) != null) {
String[] t = lineRead.split("\\|");
mem[i] = new member(); // initialize every node
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);
//...
Output:
RAVI
Note that you can use ArrayList or other java collection.

The identifier that starts with 'x' is too long (SQL)

I'm passing a date into a SQL query (which works in other code I have) but for some reason isn't playing nicely here. I'll post the code below.
Calendar limitDate = Calendar.getInstance();
limitDate.set(Calendar.HOUR_OF_DAY, 0);
limitDate.set(Calendar.MINUTE, 0);
limitDate.set(Calendar.SECOND, 0);
limitDate.set(Calendar.MILLISECOND, 0);
//remove records 221 days old or older
limitDate.add(Calendar.DAY_OF_YEAR, -221);
java.sql.Date sqlDate = new java.sql.Date(limitDate.getTimeInMillis());
int deleteCnt = 0;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
StringBuilder wgpSql = new StringBuilder("select wgpapt.* ");
wgpSql.append("from THB_View.WGPAPT wgpapt ");
wgpSql.append("left outer join THB_View.WGP wgp on wgpapt.WGP_TAG = wgp.WGP_TAG ");
wgpSql.append("where wgpapt.CREATE_DATE <= '" + sqlDate + "' ");
wgpSql.append("and wgp.RECORD_KEY is null");
List<Object[]> sqlResultSet = ExecuteSql.executeNativeSqlString(wgpSql.toString(), null);
The error I get in the console is: The identifier that starts with 'Ljava.lang.Object;#4906038d,[Ljava.lang.Object;#366cabed,[Ljava.lang.Object;#651d74a9,[Ljava.lang.Object;#354aea35,[Ljava.lang.O' is too long. Maximum length is 128.
edit: my complete code is below
package com.yrc.mcc.app.batch;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.yrc.mcc.core.core.MccMidusException;
import com.yrc.mcc.core.file.MList;
import com.yrc.mcc.core.program.BatchProgram;
import com.yrc.mcc.core.sql.ExecuteSql;
import com.yrc.mcc.data.file.Wgpapt;
#Component
#Scope("prototype")
public class BShp830 extends BatchProgram {
public int deleteRecords(Map<String, List<String>> recordKeys) {
MList<Wgpapt> delList = new MList<>();
delList.populateFromTypeMap(Wgpapt.class, recordKeys);
for (Wgpapt record : delList) {
record.delete();
}
recordKeys.get("").clear();
int result = 0;
try {
this.commit();
print("Succesfully deleted " + delList.size() + " records");
result = delList.size();
// Do we want a delay here?
} catch (MccMidusException mme) {
if ("0080".equals(mme.getErrorCode())) {
this.getIoHarness().pokeUow(mme.getUow());
// Call commit to get a new transaction started.
this.commit();
// Reset the counter.
} else {
throw mme;
}
}
return result;
}
#Override
public void process() {
// Find the first 5,000 records to remove.
Calendar limitDate = Calendar.getInstance();
limitDate.set(Calendar.HOUR_OF_DAY, 0);
limitDate.set(Calendar.MINUTE, 0);
limitDate.set(Calendar.SECOND, 0);
limitDate.set(Calendar.MILLISECOND, 0);
//remove records 221 days old or older
limitDate.add(Calendar.DAY_OF_YEAR, -221);
java.sql.Date sqlDate = new java.sql.Date(limitDate.getTimeInMillis());
int deleteCnt = 0;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
StringBuilder wgpSql = new StringBuilder("select wgpapt.* ");
wgpSql.append("from THB_View.WGPAPT wgpapt ");
wgpSql.append("left outer join THB_View.WGP wgp on wgpapt.WGP_TAG = wgp.WGP_TAG ");
wgpSql.append("where wgpapt.CREATE_DATE <= '" + sqlDate.toString() + "' ");
wgpSql.append("and wgp.RECORD_KEY is null");
List<Object[]> sqlResultSet = ExecuteSql.executeNativeSqlString(wgpSql.toString(), null);
int i = 0;
Map<String, List<String>> recordKeys = new HashMap<>();
recordKeys.put("", new ArrayList<String>());
for (Object value : sqlResultSet) {
recordKeys.get("").add(value.toString());
i++;
if (i == 100) {
deleteRecords(recordKeys);
deleteCnt += i;
print("Running delete count is: " + deleteCnt);
i = 0;
}
}
if (i != 0) {
// Ensure anything else gets committed.
deleteRecords(recordKeys);
deleteCnt += i;
}
print("** P R O C E D U R E S H P 8 3 0", false);
print("** DELETING RECORDS WITH A CREATE DATE ", false);
print("** PRIOR TO " + limitDate.getTime().toString(), false);
print("** TOTAL WGPAPT RECORDS DELETED = " + deleteCnt, false);
print("*****************************************", false);
print("** PROCEDURE SHP830 COMPLETED * ", false);
print("** AT: " + formatter.format(date) + " *", false);
print(" ", false);
this.webDone();
}
}
I solved my own problem. My SQL statement says ("select wgpapt.* "); which takes the entire result rather than the record key sequence I was trying to obtain. This was far too long and causing my code to error out.
the solution was to change my select statement to
("select wgpapt.RECORD_KEY ");

Java calculate time difference between check in and out

I want to calculate the time difference hour and minute without using java dateformat
user should input like
Clock In: 23:00
Clock Out: 01:00
The expected output shall be something like 2 hours 00 minutes.
But how can I calculate them?
Scanner input = new Scanner(System.in);
//Read data
System.out.print("Clock In: ");
String sTimeIn = input.nextLine();
System.out.print("Clock Out: ");
String sTimeOut = input.nextLine();
// Process data
String sHourIn = sTimeIn.substring(0, 2);
String sMinuteIn = sTimeIn.substring(3, 5);
String sHourOut = sTimeOut.substring(0, 2);
String sMinuteOut = sTimeOut.substring(3, 5);
int iHourIn = Integer.parseInt(sHourIn);
int iMinuteIn = Integer.parseInt(sMinuteIn);
int iHourOut = Integer.parseInt(sHourOut);
int iMinuteOut = Integer.parseInt(sMinuteOut);
int sumHour =
int sumMinute =
//Display Output
System.out.print(sumHour +"Hour "+ sumMinute + " Minute");
}
}
After I have reviewed all the solutions you given. Here is what I have edited. But I still found an issue is,
if Clock in 23:00 Clock Out: 01:00 and the output is 22Hour(s) 0 Minute(s). The output should be 02 Hour(s) 0 Minute(s).
System.out.println("*Your time format must be 00:00");
System.out.print("Clock In: ");
String getTimeIn = input.nextLine();
System.out.print("Clock Out: ");
String getTimeOut = input.nextLine();
// Process data
String sHourIn = getTimeIn.substring(0, 2);
String sMinuteIn = getTimeIn.substring(3, 5);
String sHourOut = getTimeOut.substring(0, 2);
String sMinuteOut = getTimeOut.substring(3, 5);
int sumHour = Integer.parseInt(sHourIn) - Integer.parseInt(sHourOut);
int sumMinute = Integer.parseInt(sMinuteIn) - Integer.parseInt(sMinuteOut);
if(sumHour < 0) {
sumHour =-sumHour;
}
if(sumMinute < 0) {
sumMinute =- sumMinute;
}
//Display Output
System.out.print(sumHour +"Hour(s) "+ sumMinute + " Minute(s)");
If you want to use LocalTime and ChronoUnit classes of Java 8:
String sTimeIn = "23:15";
String sTimeOut = "1:30";
LocalTime timeIn = LocalTime.parse(sTimeIn, DateTimeFormatter.ofPattern("H:m"));
LocalTime timeOut = LocalTime.parse(sTimeOut, DateTimeFormatter.ofPattern("H:m"));
long dif = ChronoUnit.MINUTES.between(timeIn, timeOut);
if (dif < 0)
dif += 24 * 60;
long sumHour = dif / 60;
long sumMinute = dif % 60;
System.out.println(sumHour + ":"+ sumMinute);
or formatted to HH:mm:
System.out.println(String.format("%02d", sumHour) + ":"+ String.format("%02d", sumMinute));
will print:
02:15
As #Stultuske said the time library should be a safer option, I have provided an example below
import java.time.LocalTime;
public class HelloWorld
{
public static void main(String[] args)
{
LocalTime in = LocalTime.parse("18:20");
LocalTime out = LocalTime.parse("20:30");
int hoursDiff = (out.getHour() - in.getHour()),
minsDiff = (int)Math.abs(out.getMinute() - in.getMinute()),
secsDiff = (int)Math.abs(out.getSecond() - in.getSecond());
System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
}
}
Update:
The solution is missing the midnight crossing as pointed by #Joakim Danielson, So I have modified the above solution to check for in > out or out < in.
import java.time.LocalTime;
public class HelloWorld
{
public static void main(String[] args)
{
LocalTime in = LocalTime.parse("16:00");
LocalTime out = LocalTime.parse("01:00");
int hOut = out.getHour(),
hIn = in.getHour();
int hoursDiff = hOut < hIn ? 24 - hIn + hOut : hOut - hIn,
minsDiff = (int)Math.abs(out.getMinute() - in.getMinute()),
secsDiff = (int)Math.abs(out.getSecond() - in.getSecond());
System.out.println(hoursDiff+":"+minsDiff+":"+secsDiff);
}
}
Here is my suggested solution including some simple (not perfect) validation of the input, I have put the solution inside a method so asking user for input is not handled
public static void calcTime(String sTimeIn, String sTimeOut) {
final String timePattern = "[0-2][0-9]:[0-5][0-9]";
if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
throw new IllegalArgumentException();
}
String[] timeIn = sTimeIn.split(":");
String[] timeOut = sTimeOut.split(":");
int inMinutes = 60 * Integer.valueOf(timeIn[0]) + Integer.valueOf(timeIn[1]);
int outMinutes = 60 * Integer.valueOf(timeOut[0]) + Integer.valueOf(timeOut[1]);
int diff = 0;
if (outMinutes > inMinutes) {
diff = outMinutes - inMinutes;
} else if (outMinutes < inMinutes) {
diff = outMinutes + 24 * 60 - inMinutes;
}
System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut, diff / 60, diff % 60);
}
Update
Here is a solution based on LocalTime and Duration
public static void calcTime2(String sTimeIn, String sTimeOut) {
final String timePattern = "[0-2][0-9]:[0-5][0-9]";
if (sTimeIn == null || sTimeOut == null || !sTimeIn.matches(timePattern) || !sTimeIn.matches(timePattern)) {
throw new IllegalArgumentException();
}
String[] timeIn = sTimeIn.split(":");
String[] timeOut = sTimeOut.split(":");
LocalTime localTimeIn = LocalTime.of(Integer.valueOf(timeIn[0]), Integer.valueOf(timeIn[1]));
LocalTime localTimeOut = LocalTime.of(Integer.valueOf(timeOut[0]), Integer.valueOf(timeOut[1]));
Duration duration;
if (localTimeOut.isAfter(localTimeIn)) {
duration = Duration.between(localTimeIn, localTimeOut);
} else {
Duration prevDay = Duration.ofHours(24).minusHours(localTimeIn.getHour()).minusMinutes(localTimeIn.getMinute());
Duration nextDay = Duration.between(LocalTime.MIDNIGHT, localTimeOut);
duration = prevDay.plus(nextDay);
}
System.out.printf("Time difference between %s and %s is %d hours and %d minutes\n", sTimeIn, sTimeOut,
duration.toHours(), duration.minusHours(duration.toHours()).toMinutes());
}
try this :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Read data
System.out.println("Clock In: ");
String sTimeIn = "20:30";
System.out.println("Clock Out: ");
String sTimeOut = "18:20";
// Process data
String sHourIn = sTimeIn.substring(0, 2);
String sMinuteIn = sTimeIn.substring(3, 5);
String sHourOut = sTimeOut.substring(0, 2);
String sMinuteOut = sTimeOut.substring(3, 5);
int iHourIn = Integer.parseInt(sHourIn);
int iMinuteIn = Integer.parseInt(sMinuteIn);
int iHourOut = Integer.parseInt(sHourOut);
int iMinuteOut = Integer.parseInt(sMinuteOut);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,iHourIn);
cal.set(Calendar.MINUTE,iMinuteIn);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Long timeIn = cal.getTime().getTime();
cal.set(Calendar.HOUR_OF_DAY,iHourOut);
cal.set(Calendar.MINUTE,iMinuteOut);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Long timeOut = cal.getTime().getTime();
Long finaltime= timeIn-timeOut;
// Convert the result to Hours and Minutes
Long temp = null;
// get hours
temp = finaltime % 3600000 ;
int sumHour = (int) ((finaltime - temp) / 3600000 );
finaltime = temp;
int sumMinute = (int) (finaltime/ 60000);
//Display Output
System.out.println(sumHour +" Hour "+ sumMinute + " Minute");
}
I have added some code in addition to your code. Please check and let me know if this is enough for your requirement
public class MainClass1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Read data
System.out.print("Clock In: ");
String[] sTimeIn = input.nextLine().split(":");
System.out.print("Clock Out: ");
String[] sTimeOut = input.nextLine().split(":");
int iHourIn = Integer.parseInt(sTimeIn[0]);
int iMinuteIn = Integer.parseInt(sTimeIn[1]);
int iHourOut = Integer.parseInt(sTimeOut[0]);
int iMinuteOut = Integer.parseInt(sTimeOut[1]);
if(iMinuteIn < iMinuteOut) {
iMinuteIn = 60 + iMinuteIn;
iHourIn--;
}
int sumHour = iHourIn - iHourOut;
int sumMinute = iMinuteIn - iMinuteOut;
//Display Output
System.out.print(sumHour +"Hour "+ sumMinute + " Minute");
}
}

How to loop through Map of List for specific startDate?

I have a hashmap of the following type
HashMap<String,List<Training>> map=new HashMap<String,List<Training>>();
Input:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
python 10-10-2017 12-11-2017 www viz
Enter Date: 01-10-2017
The attributes/values to be displayed are like this :
Output:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
I need to retrieve the details of list from getList().What code do i need to write in this method such that when user enters the date i can display output in the desired way as shown above.
public List<Training> getList(String fromDate) {
}
public static void main(String args[]) throws ParseException{
Map<String,List<Training>> map = new HashMap<String,List<Training>>();
Scanner sc = new Scanner(System.in);
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
//DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Date fromDate = dateFormat.parse(sc.next());
//Date toDate = dateFormat.parse(sc.next());
String fromDate = sc.next();
String toDate = sc.next();
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
List<Training> l1=new ArrayList<Training>();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
//System.out.println("list********"+l1);
if(!map.containsKey(fromDate)){
map.put(fromDate,l1);
}else{
map.get(fromDate).add(new Training(topicName,fromDate,toDate,trainer,venue));
}
}
System.out.println("map********"+map);
}
#Override
public String toString() {
return gettopicName() + getfromDate() + gettoDate() + gettrainer() + getvenue() ;
}
Since, fromDate is the key for your Map. Then, you could simply get method which will give you List<Training>.
return map.get(fromDate);
If there are no value for specified key, then it will return null.
Try below code instead of creating Map based on from Date keep a list of training. If user enter date iterate over the training to filter it.
public List<Training> getList(List<Training> trainingList, Date date) {
List<Training> list = new ArrayList<Training>();
for( Training training : trainingList ) {
if( training.getFromDate().getTime() <= date.getTime() &&
date.getTime() <= training.getToDate().getTime() ) {
list.add(training);
}
}
return list;
}
public static void main(String args[]) throws ParseException{
Scanner sc = new Scanner(System.in);
List<Training> l1=new ArrayList<Training>();
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date fromDate = dateFormat.parse(sc.next());
Date toDate = dateFormat.parse(sc.next());
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
}
System.out.println("map********"+l1);
}

Obtain values from array in one class from another class

I have this code in a class and want to ideally copy the values in the adjclose array list to another class for further process while preserving the original data. I am able to see that the arraylist is populated with the values with the println statement prior to the return statement as the array is being populated. The main method then iterates through the arraylist to again show the values for each element in the arraylist adjclose.
How can I get to the adjclose arraylist from another class to enable me to copy them to a new arraylist to process further?
public ArrayList<Double> getadjClose(String symbol) {
String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
baseUrl += "&s=" + symbol;
baseUrl += "&a=" + startMonth;
baseUrl += "&b=" + startDay;
baseUrl += "&c=" + startYear;
baseUrl += "&d=" + endMonth;
baseUrl += "&e=" + endDay;
baseUrl += "&f=" + endYear;
baseUrl += "&g=" + freq;
URL url;
ArrayList<Double> adjclose = new ArrayList<Double>();
System.out.print("Opening URL: ");
System.out.print(baseUrl);
System.out.println(" ");
int counter = 0;
try {
url = new URL(baseUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
in.readLine(); // Forward Header
while (true) {
String thisLine = in.readLine();
if (thisLine == null) {
break;
}
String[] separatedLine = thisLine.split("[,X]"); // split by commas
adjclose.add(Double.parseDouble(separatedLine[6]));
System.out.println(adjclose.get(counter) + " " + counter);
counter = counter + 1;
}
return adjclose;
} catch (IOException e) {
return null;
}
}
I have now made the changes to the code within the first class and it appears as follows.
package yahooapi;
/**
*
* #author RSLOMA
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
public class YahooAPI {
int startMonth;
int startDay;
int startYear;
int endMonth;
int endDay;
int endYear;
int TodayDate;
String freq;
public ArrayList<Double> data = new ArrayList<>();
public ArrayList<Double> getAdjClose(String symbol) throws IOException {
String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
baseUrl += "&s=" + symbol;
baseUrl += "&a=" + startMonth;
baseUrl += "&b=" + startDay;
baseUrl += "&c=" + startYear;
baseUrl += "&d=" + endMonth;
baseUrl += "&e=" + endDay;
baseUrl += "&f=" + endYear;
baseUrl += "&g=" + freq;
URL url;
// use a local variable
ArrayList<Double> adjclose = new ArrayList<>();
System.out.print("Opening URL: ");
System.out.print(baseUrl);
System.out.println(" ");
int counter = 0;
try {
url = new URL(baseUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
in.readLine(); //Forward Header
while (true){
String thisLine = in.readLine();
if (thisLine == null){
break;
}
String[] separatedLine = thisLine.split("[,X]"); // split by commas
adjclose.add(Double.parseDouble(separatedLine[6]));
System.out.println(adjclose.get(counter) + " " + counter);
// update the data once the read is done
data = adjclose;
System.out.println(data.get(counter));
counter = counter + 1;
}
return adjclose;
} catch (IOException e) {
return null;
}
}
public static void main(String args[]) throws IOException{
YahooAPI y = new YahooAPI();
Calendar cal = Calendar.getInstance();
y.startDay = 1;
y.startMonth = cal.get(Calendar.MONTH) - 1; //0 is jan, so 2 is march
y.startYear = cal.get(Calendar.YEAR) - 3;
System.out.println("Day: " + y.startMonth);
System.out.println("Day: " + y.startDay);
System.out.println("Day: " + y.startYear);
y.endDay = cal.get(Calendar.DATE) - (cal.get(Calendar.DATE) - 1);
y.endMonth = cal.get(Calendar.MONTH); //0 is jan, so 2 is march
y.endYear = cal.get(Calendar.YEAR);
y.freq = "m"; // d for daily frequency, w for weekly, m for monthly
ArrayList<Double> adjclose = y.getAdjClose("^GSPC");
//Iterator<Double> iter = adjclose.iterator();
//System.out.println("Returned Adjusted Close Values:");
//while (iter.hasNext()){
//System.out.println(iter.next());
int ArrayLngth = adjclose.size();
System.out.print("Array length = " + ArrayLngth + " ");
}
public ArrayList<Double> getAdjClose() {
for (int counter = 0; counter<data.size(); counter++) {
System.out.println(data.get(counter) + " " + counter);
}
return (ArrayList<Double>) data.clone();
}
}
I have another class in another package that I want to use for calculations, retain the original data elements in the original array, and save the new calculated data in an array in the 2nd class. The beginning code for the other class is below. How do I call to obtain the data that is cloned in data.clone()?
package PortfolioDesign;
/**
*
* #author RSLOMA
*/
public class MonthlyReturns {
}
Have a method in your first class that will create a clone of the array and return the clone, then call that method from your second class.
If a result is used multiple times, I would split the method into
a data collector method
a data retrieval method
The data collector then fills a member of the class:
private ArrayList<Double> data = new ArrayList<Double>();
public void fillAdjClose(String symbol) throws IOException {
String baseUrl = "http://ichart.finance.yahoo.com/table.csv?ignore=.csv";
baseUrl += "&s=" + symbol;
baseUrl += "&a=" + startMonth;
baseUrl += "&b=" + startDay;
baseUrl += "&c=" + startYear;
baseUrl += "&d=" + endMonth;
baseUrl += "&e=" + endDay;
baseUrl += "&f=" + endYear;
baseUrl += "&g=" + freq;
URL url;
// use a local variable
ArrayList<Double> adjclose = new ArrayList<Double>();
System.out.print("Opening URL: ");
System.out.print(baseUrl);
System.out.println(" ");
int counter = 0;
url = new URL(baseUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
in.readLine(); // Forward Header
while (true) {
String thisLine = in.readLine();
if (thisLine == null) {
break;
}
String[] separatedLine = thisLine.split("[,X]"); // split by commas
adjclose.add(Double.parseDouble(separatedLine[6]));
System.out.println(adjclose.get(counter) + " " + counter);
counter = counter + 1;
}
// update the date once the read is done
data = adjclose;
}
public ArrayList<Double> getAdjClose() {
return (ArrayList<Double>) data.clone();
}
You can call getAdjClose() as often you want and always get a copy of the last read data.
You can always use clone() for an ArrayList unless you also need copies of the elements. Since you are using Double, which is immutable, there is no need to copy the elements.
If you want to publish the values of adjclose say from Class A to Class B then the containing class ClassA should ideally have a getter method which can be called my ClassB.
To preserve the original data you should publish a copy of adjClose and not the original list itself. Also to note, you should do a deep clone and not shallow clone.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public classA {
private List<Double> adjclose = null;
public List<Double> getAdjClose(){
List<Double> returnValue = new ArrayList<Double>();
if(adjclose != null) {
returnValue.addAll(adjclose); // this will ensure that if caller makes any changes to adjClose, copy of classA remains intact.
return returnValue;
}
return Collections.emptyList();
}
}
The caller class ClassB will then make an instance of ClassA and call getAdjClose() on it.
import java.util.List;
public class ClassB {
public static void main(String[] args){
ClassA classA = new ClassA();
List<Double> list = classA.getAdjClose();
System.out.println(list);
list.set(0, new Double(11));
System.out.println(list);
System.out.println(classA.getAdjClose());
}
}

Categories