Interactive Brokers API - Executing multiple trades - java

I'm trying to create a program for an API to place multiple trades at once, and then get prices for the stocks, and then rebalance every so often. I used a tutorial from online to get some of this code, and made a few tweaks.
However, when I run the code, it often connects and will place an order if I restart IB TWS. But if I go to run the code again it does not work, or show any indication that it will connect. Can anyone help me figure out how to keep the connection going, so that I can run the main.java file, and it will execute multiple trades and then end the connection? Do I need to change the client id number in either the code, or the settings of TWS?
There are three files:
Ordermanagement.java:
package SendMarketOrder;
//import statements//
class OrderManagement extends Thread implements EWrapper{
private EClientSocket client = null; //IB API client Socket Object
private Stock stock = new Stock();
private Order order = new Order();
private int orderId;
private double limitprice;
private String Ticker;
//method to create connection class. It's the constructor
public OrderManagement() throws InterruptedException, ClassNotFoundException, SQLException {
// Create a new EClientSocket object
System.out.println("////////////// Creating a Connection ////////////");
client = new EClientSocket(this); //Creation of a socket to connect
//connect to the TWS Demo
client.eConnect(null,7497,1);
try {
Thread.sleep(3000); //waits 3 seconds for user to accept
while (!(client.isConnected()));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("///////// Connected /////////");
}
public void sendMarketOrder(String cusip, String buyorSell, int shares) throws SQLException, ClassNotFoundException{
//New Order ID
orderId++;
order.m_action = buyorSell;
order.m_orderId = orderId;
order.m_orderType = "MKT";
order.m_totalQuantity = shares;
order.m_account = "DU33xxxxx"; //write own account
order.m_clientId = 1;
//Create a new contract
stock.createContract(cusip);
client.placeOrder(orderId, stock.contract, order);
//Show order in console
SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
String current_time_str = time_formatter.format(System.currentTimeMillis());
System.out.println("////////////////////////////////////////////////\n" +
"#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n" +
"#Client number: " + order.m_clientId + "///////////////////////////\n" +
"#OrderType: " + order.m_orderType + "///////////////////////////\n" +
"#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n" +
"#Account number: " + order.m_account + "///////////////////////////\n" +
"#Symbol: " + stock.contract.m_secId + "///////////////////////////\n" +
"///////////////////////////////////////"
);
}
Stock.java
public class Stock{
private int StockId; //we can identify the stock
private String Symbol; //Ticker
public Stock() { //default constructor
}
public Stock(int StockId, String Symbol) { //constructor
this.StockId = StockId;
this.Symbol = Symbol;
}
//getter and setters
public int getStockId() {
return StockId;
}
public String getSymbol() {
return Symbol;
}
Contract contract = new Contract ();
public void createContract(String cusip){
contract.m_secId = cusip;
contract.m_secIdType = "CUSIP";
contract.m_exchange = "SMART";
contract.m_secType = "STK";
contract.m_currency = "USD";
}
}
Main.java:
package SendMarketOrder;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws InterruptedException, ClassNotFoundException, SQLException {
OrderManagement order = new OrderManagement();
order.sendMarketOrder("922908363","BUY", 100);
order.sendMarketOrder("92204A504","BUY", 50);
order.sendMarketOrder("92204A702","BUY", 100);
System.exit(0);
}
}
These are my current settings TWS settings if that helps:
Thanks in advance for the help!

I changed a few things around in the code and added comments.
package sendmarketorder;//usually lower case pkg names
public class Main {
//you throw a bunch of exceptions that are never encountered
public static void main(String[] args) {
//since there's a Thread.sleep in this class
//it will block until ready
OrderManagement order = new OrderManagement();
//obviously you need some logic to buy/sell
//you can use command line args here if you want
order.sendMarketOrder("922908363", "BUY", 100);
order.sendMarketOrder("92204A504", "BUY", 50);
order.sendMarketOrder("92204A702", "BUY", 100);
//the socket creates a reader thread so this will stop it.
//if you didn't have this line the non-daemon thread would keep a
//connection to TWS and that's why you couldn't reconnect
//System.exit(0);//use better exit logic
}
}
.
package sendmarketorder;
import com.ib.client.*;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
//doesn't extend thread and if you implement EWrapper you have to implement all methods
//in API 9.72 you can extend DefaultWrapper and just override the methods you need
public class OrderManagement implements EWrapper{
private EClientSocket client = null; //IB API client Socket Object
private int orderId = -1;//use as flag to send orders
//private double limitprice;
//private String Ticker;
//keep track of all working orders
private Map<Integer, Order> workingOrders = new HashMap<>();
//method to create connection class. It's the constructor
public OrderManagement(){
// Create a new EClientSocket object
System.out.println("////////////// Creating a Connection ////////////");
client = new EClientSocket(this); //Creation of a socket to connect
//connect to the TWS Demo
client.eConnect(null, 7497, 123);//starts reader thread
try {
while (orderId < 0){ //not best practice but it works
System.out.println("waiting for orderId");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("///////// Connected /////////");
}
public void sendMarketOrder(String cusip, String buyorSell, int shares) {
//make new stock and order for each stock
Stock stock = new Stock();
Order order = new Order();
//New Order ID, but get from API as you have to increment on every run for life
orderId++;
order.m_action = buyorSell;
order.m_orderId = orderId;
order.m_orderType = "MKT";
order.m_totalQuantity = shares;
//I don't think you're supposed to use these fields
//order.m_account = "DU33xxxxx"; //write own account
//order.m_clientId = 1;
//Create a new contract
stock.createContract(cusip);
//remember which orders are working
workingOrders.put(orderId, order);
client.placeOrder(orderId, stock.contract, order);
//Show order in console
SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
String current_time_str = time_formatter.format(System.currentTimeMillis());
System.out.println("////////////////////////////////////////////////\n"
+ "#Limit Price: " + order.m_lmtPrice + "///////////////////////////\n"
+ "#Client number: " + order.m_clientId + "///////////////////////////\n"
+ "#OrderType: " + order.m_orderType + "///////////////////////////\n"
+ "#Order Quantity: " + order.m_totalQuantity + "///////////////////////////\n"
+ "#Account number: " + order.m_account + "///////////////////////////\n"
+ "#Symbol: " + stock.contract.m_secId + "///////////////////////////\n"
+ "///////////////////////////////////////"
);
}
//always impl the error callback so you know what's happening
#Override
public void error(int id, int errorCode, String errorMsg) {
System.out.println(id + " " + errorCode + " " + errorMsg);
}
#Override
public void nextValidId(int orderId) {
System.out.println("next order id "+orderId);
this.orderId = orderId;
}
#Override
public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
//so you know it's been filled
System.out.println(EWrapperMsgGenerator.orderStatus(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld));
//completely filled when remaining == 0, or possible to cancel order from TWS
if (remaining == 0 || status.equals("Cancelled")){
//remove from map, should always be there
if (workingOrders.remove(orderId) == null) System.out.println("not my order!");
}
//if map is empty then exit program as all orders have been filled
if (workingOrders.isEmpty()){
System.out.println("all done");
client.eDisconnect();//will stop reader thread
//now is when you stop the program, but since all
//non-daemon threads have finished, the jvm will close.
//System.exit(0);
}
}
//impl rest of interface...
}

Related

Spark: Run through List Asyncronously and perform SparkContext Actions

In my application I am running through a list synchronously in order to process all hostnames in a list.
While the application works, the problem is I want to now be able to run through that list asynchronously, however I am not entirely sure how to do this with spark since the SparkContext object is not serializable, meaning you can only have a single SparkContext object running at any given time, preventing you from doing multiple spark actions simultaneously.
So my question is, how do other people approach this problem? Maybe I am not thinking about it in the right way.
Possible Solution: Map List(modelFilteredTopology) to a JavaRDD and then use JavaRDD.foreachAsync(Call MapProcessing with VoidFunction) in order to perform the actions asynchronously. However I may run into some head scratching issues if I do this. And I believe I will still be limited by the SparkContext as it wont execute the actions asynchronously anyways.
Sample of my code below:
MainClass.java snippet - Loads some data from a SchemaRDD over to a LIST
List<modelFilteredTopology> filteredList = FILTERED_TOPOLOGY.map(new Function<Row, modelFilteredTopology>() {
public modelFilteredTopology call(Row row){
modelFilteredTopology modelF = new modelFilteredTopology();
modelF.setHOSTNAME(row.getString(0));
modelF.setMODEL(row.getString(1));
modelF.setCOMMIT_TS(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
return modelF;
}
}).collect();
for(modelFilteredTopology f : filteredList) {
MapProcessing2 map = new MapProcessing2(schemaTopology, sc, sqlContext);
map.runApp(f.getHOSTNAME(),f.getMODEL(),f.getCOMMIT_TS());
}
MapProcessing2.class - This is a small snippet of the code that performs a TON of JAVARDD transformations, I have to make SparkContext static, otherwise it will obviously through a Serialization not allowed error.
public class MapProcessing2 implements Serializable {
private static final Integer HISTORYDATE = 30;
private static JavaSchemaRDD TOPO_EXTRACT;
private static JavaSparkContext SC;
private static JavaSQLContext sqlContext;
private static final String ORACLE_DRIVER = Properties.getString("OracleDB_Driver");
private static final String ORACLE_CONNECTION_URL_PROD = Properties.getString("DB_Connection_PROD");
private static final String ORACLE_USERNAME_PROD = Properties.getString("DB_Username_PROD");
private static final String ORACLE_PASSWORD_PROD = Properties.getString("DB_Password_PROD");
public MapProcessing2(JavaSchemaRDD TOPO_EXTRACT, JavaSparkContext SC, JavaSQLContext sqlContext) {
this.TOPO_EXTRACT = TOPO_EXTRACT;
this.SC = SC;
this.sqlContext = sqlContext;
}
public void runApp(String hostname, String model, String commits) throws Exception{
if (String.valueOf(hostname).equals("null")) {
System.out.println("No Value Retrieved");
} else {
try {
//Retrieve Tickets for GWR
JavaSchemaRDD oltint = getOLTInterfaces(TOPO_EXTRACT, hostname);
System.out.println("Number of OLT's Found for "+hostname+": " + oltint.collect().size());
if (oltint.collect().size() < 1) {
System.out.println("No OLT's found for: " + hostname);
} else {
System.out.println("Processing Router: " + hostname + " Model:" + model);
System.out.println("Processing Tickets for: " + hostname + " " + model);
}
} catch (Exception e) {
System.out.println("Error Processing GWR: " + hostname + " " + model + " Stacktrace Error: " + e);
}
}
}

GridSim: how to send message among peer nodes through a router?

I'm a new user to the Gridsim, and currently wish to use it for my work. I wish to connect users (say 2) through a router. I followed example01 (sends pkt directly from sender to recipient), and included one router, attach it with both users. But I don't know how to start communication between both entities through router. It returns null values. On the other hand, when I use link.attach, both users bypass the router and directly communicate.
Example03 works fine but sends msg from users to the resource, but not to peer user.
I hope you could help me to sort out this issue.
Any help in this regard would be highly appreciated.
Thanks.
I find out the solution. Here is the code:
Program_name: FlowNetEx01.java
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import java.util.*;
public class FlowNetEx01
{
public static void main(String[] args)
{
System.out.println("Starting network example ...");
try
{
int num_user = 2; // number of grid users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
System.out.println("Initializing GridSim package");
GridSim.initNetworkType(GridSimTags.NET_FLOW_LEVEL);
GridSim.init(num_user, calendar, trace_flag);
// In this example, the topology is:
// user(s) --10Mb/s-- r1 --1.5Mb/s-- r2 --10Mb/s-- GridResource(s)
Router r1 = new FlowRouter("router1", trace_flag); // router 1
Router r2 = new FlowRouter("router2", trace_flag); // router 2
String sender1 = "user1";
String receipient1 = "test1";
// these entities are the senders
FlowNetUser user1 = new FlowNetUser(sender1, receipient1, 5.0);
// these entities are the receipients
FlowTest test1 = new FlowTest(receipient1, sender1);
// The schedulers are redundent and will be stripped out soon
FIFOScheduler userSched1 = new FIFOScheduler("NetUserSched_0");
r1.attachHost(user1, userSched1);
FIFOScheduler testSched1 = new FIFOScheduler("FlowTestSched_0");
r2.attachHost(test1, testSched1);
double baud_rate = 1572864; // bits/sec (baud) [1.5Mb/s]
double propDelay = 200; // propagation delay in millisecond
int mtu = Integer.MAX_VALUE;; // max. transmission unit in byte
Link link = new FlowLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
r1.attachRouter(r2, link, r1Sched, r2Sched);
GridSim.startGridSimulation();
System.out.println("\nFinish ...");
}
catch (Exception e)
{
e.printStackTrace();
System.err.print(e.toString());
System.out.println("Unwanted errors happen");
}
}
}
Program_name: FlowNetUser.java
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import eduni.simjava.*;
import java.util.*;
public class FlowNetUser extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private double wait_; // Delay until I begin sending
/** Custom tag that denotes sending a message */
public static final int SEND_MSG = 1;
public static final int ACK_MSG = 2;
/**
* Creates a new NetUser object
* #param name this entity name
* #param destName the destination entity's name
* #param link the physical link that connects this entity to destName
* #throws Exception This happens when name is null or haven't
* initialized GridSim.
*/
public FlowNetUser(String name, String destName, Link link, double wait) throws Exception
{
super(name, link);
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
public FlowNetUser(String name, String destName, double wait) throws Exception
{
// 10,485,760 baud = 10Mb/s
super(name, new FlowLink(name+"_link",10485760,450,Integer.MAX_VALUE));
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
/**
* The core method that handles communications among GridSim entities.
*/
public void body()
{
int packetSize = 524288000; // packet size in bytes [5MB]
//int packetSize = 52428800; // packet size in bytes [50MB]
//int packetSize = 524288000; // packet size in bytes [500MB]
//int packetSize = 5242880000; // packet size in bytes [5000MB]
int size = 3; // number of packets sent
int i = 0;
// get the destination entity ID
this.destID_ = GridSim.getEntityId(destName_);
//super.sim_pause(this.wait_);
this.gridSimHold(this.wait_);
// sends messages over the other side of the link
for (i = 0; i < size; i++)
{
String msg = "Message_" + i;
IO_data data = new IO_data(msg, packetSize, destID_);
System.out.println(name_ + ".body(): Sending " + msg +
", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_SUBMIT, data);
//super.sim_pause();
super.sim_pause(10.0);
//this.gridSimHold((Math.random()*10)+1.0);
}
////////////////////////////////////////////////////////
// get the ack back
Object obj = null;
for (i = 0; i < size; i++)
{
// waiting for incoming event in the Input buffer
obj = super.receiveEventObject();
System.out.println(name_ + ".body(): Receives Ack for " + obj);
}
// Wait for other FlowNetUser instances to finish
this.gridSimHold(1000.0);
super.send(destID_, GridSimTags.SCHEDULE_NOW,
GridSimTags.END_OF_SIMULATION);
////////////////////////////////////////////////////////
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
} // end class
Program_name: FlowTest.java
package network.flow.example01;
import java.util.*;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import gridsim.util.SimReport;
import eduni.simjava.*;
public class FlowTest extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private SimReport report_; // logs every activity
public FlowTest(String name, String destName, Link link) throws Exception
{
super(name, link);
this.name_ = super.get_name();
this.myID_ = super.get_id();
this.destName_ = destName;
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public FlowTest(String name, String destName) throws Exception
{
super(name, new FlowLink(name+"_link",10485760,250,Integer.MAX_VALUE));
this.name_ = super.get_name();
this.myID_ = super.get_id();
this.destName_ = destName;
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public void body()
{
this.destID_ = GridSim.getEntityId(destName_);
int packetSize = 1500; // packet size in bytes
Sim_event ev = new Sim_event(); // an event
// a loop waiting for incoming events
while ( Sim_system.running() )
{
// get the next event from the Input buffer
super.sim_get_next(ev);
// if an event denotes end of simulation
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
{
System.out.println();
write(super.get_name() + ".body(): exiting ...");
break;
}
// if an event denotes another event type
else if (ev.get_tag() == GridSimTags.FLOW_SUBMIT)
{
System.out.println();
write(super.get_name() + ".body(): receive " +
ev.get_data() + ", at time = " + GridSim.clock());
// No need for an ack, it is handled in FlowBuffer now on our behalf
// sends back an ack
IO_data data = new IO_data(ev.get_data(), packetSize, destID_);
write(name_ + ".body(): Sending back " +
ev.get_data() + ", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_ACK, data);
}
else if (ev.get_tag() == GridSimTags.INFOPKT_SUBMIT)
{
processPingRequest(ev);
}
}
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
/**
* Handles ping request
* #param ev a Sim_event object
*/
private void processPingRequest(Sim_event ev)
{
InfoPacket pkt = (InfoPacket) ev.get_data();
pkt.setTag(GridSimTags.INFOPKT_RETURN);
pkt.setDestID( pkt.getSrcID() );
// sends back to the sender
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.INFOPKT_RETURN,
new IO_data(pkt,pkt.getSize(),pkt.getSrcID()) );
}
private void write(String msg)
{
System.out.println(msg);
if (report_ != null) {
report_.write(msg);
}
}
} // end class

Get variable from one Java class into GUI form Java class JLabel

I want to get device connected: true JLabel in DisplayForm.java GUI if I press the connectBtn in DisplayForm.java GUI, but I can't get the variable String connected = "true"; from ArduinoDisplay.java to DisplayForm.java connectedDevice JLabel when I press connectBtn in DisplayForm.java.
Part of ArduinoDisplay.java
String connected = "";
public void initialize() {
if (portId == null) {
System.out.println("Could not find COM port.");
connected = "False";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
return;
} else if( portId != null) {
connected = "True";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
} else {
connected = "False";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
}
}
public static void main(String[] args) throws Exception {
ArduinoDisplay main = new ArduinoDisplay();
main.initialize();
// Start GUI
DisplayForm gui = new DisplayForm();
gui.setVisible(true);
}
Part of the DisplayForm.java
private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
ArduinoDisplay ad = new ArduinoDisplay();
String devCon = ad.connected;
deviceConnected.setText(devCon);
}
If more code is needed, let me know, thank you
Put the connected variable outside of any method and do not allow direct access to it (use a getter method)
public class ArduinoDisplay {
private String connected = "false":
public String getConnected (){
return this.connected;
}
....
}
and get it like this:
private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
ArduinoDisplay ad = new ArduinoDisplay();
String devCon = ad.getConnected();
deviceConnected.setText(devCon);
}
Side Note: try to use boolean instead of a String. Or Enum's if you need several states. It saves you time and eliminates developer typo's

Trouble with a small library-management program

I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file

cant find my logical error

I have made a simple program with :
working with files(read write)
end class extends
but the program does not work. Netbeans show no errors but when i run it ......some kind of errors show up .....and well i can't understand where is my bug (i think is a logical one).
Here is the simple program:
package detyre_kursi;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Detyre_kursi {
public static void main(String[] args) {
LlogariBankare llogaria1 = new LlogariBankare("aaa", 1000);
llogaria1.Balanca();
}
}
class LlogariBankare {
//variablat e instances
private String id;
private int nrLlogarise;
private int vitiHapjes;
private double balanca;
static int nrTranasksioneve = 0;
public LlogariBankare() {
System.out.println("Ju keni harruar te vendosi id dhe nrLlogarise");
}
public LlogariBankare(String id, int nrLlogarise) {
this.id = id;
this.nrLlogarise = nrLlogarise;
vitiHapjes = 0;
balanca = 0;
Lexim(this.id, this.nrLlogarise);
}
public double getBalanca() {
return balanca;
}
public int getVitiHapjes() {
return vitiHapjes;
}
private void Lexim(String s, int llog) {
try {
File file = new File("c:\\java\\balanca.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if (scanner.next().equals(s) && scanner.nextInt() == llog) {
vitiHapjes = scanner.nextInt();
balanca = scanner.nextDouble();
}
}
} catch (IOException e) {
e.getMessage();
}
}
void Balanca() {
try{
File file = new File("c:\\java\\test.txt");
PrintWriter out = new PrintWriter(file);
out.println(this.balanca);
} catch (IOException e) {
e.getMessage();
}
System.out.println(this.id + " , ju keni " + this.balanca +
" lek ne llogarine tuaj te krijuar ne vitin " + vitiHapjes +
" dhe keni kryer " + nrTranasksioneve + " transaksione gjithsej");
}
void Terheqe(double terheqe) {
this.balanca -= terheqe;
System.out.println("Ju sapo keni terhequr " + terheqe + " nga llogaria juaj");
nrTranasksioneve++;
}
void Depozitim(double depozitim) {
this.balanca += depozitim;
System.out.println("Ju sapo keni depozituar " + depozitim + " nga llogaria juaj");
nrTranasksioneve++;
}
}
class Interesi extends LlogariBankare {
int vitiTanishem = 2012;
double interesi = 0;
int diferencaViteve = vitiTanishem - getVitiHapjes();
Interesi(String id, int nrLlogarise) {
super(id,nrLlogarise);
}
void gjejInteresisn() {
interesi = getBalanca() + getBalanca() * diferencaViteve * 0.01;
}
}
The file balanca has this line in it :
aaa 1000 1990 34000
In poor words this is some simple version of a bank.
You read the balance from a file, and
you use the Terheqe() and Depozitim() for - and + the balance.
You use Balance() to see how many $ you have. When I run it, this error show up:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at detyre_kursi.LlogariBankare.Lexim(Detyre_kursi.java:57)
at detyre_kursi.LlogariBankare.<init>(Detyre_kursi.java:40)
at detyre_kursi.Detyre_kursi.main(Detyre_kursi.java:11)
Java Result: 1
This line causing issue. scanner.nextInt() might not be an int and I feel it is not good to do two next() calls unless you have specific reason.
if(scanner.next().equals(s)&&scanner.nextInt()==llog){
It's just a wild guess, but try replacing:
scanner.next().equals(s)
with:
s.equals(scanner.next())
I think your logical problem is from the constructor of
LlogariBankare llogaria1 = new LlogariBankare("aaa", 1000);
Check it out again.

Categories

Resources