Trouble with a small library-management program - java

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

Related

Interactive Brokers API - Executing multiple trades

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...
}

Reading textfile with multiple elements into arraylist (set and get)

I am trying to read from a text file of the type (Artist, Title, Genre, Recordcompany, Release year, Number of songs, Playtime):
The Beatles, Abbey Road, Rock, Apple Records, 1969, 17, 47.16
Sia, 1000 Forms of Fear, Pop, Intertia, 2014, 12, 48.41
Taylor Swift, Speak Now
I have created a CD class:
package q;
public class CD {
//
private String artist;
private String titel;
private String genre;
private String recordcompany;
private int year; //
private int songs; //
private double playtime; //
public CD() { //
}
public CD(String newArtist, String newTitel) {
artist = newArtist;
titel = newTitel;
}
public CD(String newArtist, String newTitel, String newGenre, String newRecordcompany, int newYear, int newSongs, double newPlaytime) {
artist = newArtist;
titel = newTitel;
genre = newGenre;
recordcompany = newRecordcompany;
year = newYear;
songs = newSongs;
playtime = newPlaytime;
}
public String getArtist() { //
return artist;
}
public String getTitel() {
return titel;
}
public String getGenre() {
return genre;
}
public String getRecordcompany() {
return recordcompany;
}
public int getYear() {
return year;
}
public int getsong() {
return songs;
}
public double getPlaytime() {
return playtime;
}
public void setArtist(String newArtist) { //
artist = newArtist;
}
public void setTitel(String newTitel) {
titel = newTitel;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRecordcompany(String newRecordcompany) {
recordcompany = newRecordcompany;
}
public void setYear(int newYear) {
year = newYear;
}
public void setSongs(int newSongs) {
songs = newSongs;
}
public void setplaytime(double newPlaytime) {
playtime = newPlaytime;
}
#
Override public String toString() { //
return ("Artist " + artist + System.lineSeparator() + "Titel: " + titel + System.lineSeparator() + "Genre: " + genre + System.lineSeparator() + "Recordcompany: " + recordcompany + System.lineSeparator() + "Year: " + year + System.lineSeparator() + "Songs: " + songs + System.lineSeparator() + "Playtime: " + playtime + System.lineSeparator());
}
}
I am trying to read from the text file and then convert it into a arraylist. I know I have overcomplicated it by first conerting the text file to a string array and then converting it to an arraylist. I would like to use set and get methods when I create the array, if it is possible. I wonder if any of you have any tips for me for how I can make the code less complicated and include set and get methods if possible, thank you.
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
String year = "";
String songs = "";
String playtime = "";
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String tmp[] = line.split(",");
artist = tmp[0];
titel = tmp[1];
if (tmp.length > 2) {
genre = tmp[2];
recordcompany = tmp[3];
year = (tmp[4]);
songs = (tmp[5]);
playtime = (tmp[6]);
} else {
genre = "";
recordcompany = "";
year = "";
songs = "";
playtime = "";
}
List < String > unsorted = Arrays.asList(tmp);
for (String e: unsorted) {
System.out.println(e);
}
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
EDITED
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
int year = 0;
int songs = 0;
double playtime = 0.0;
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
System.out.println(cdsList);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Something like below.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
cdsList.add(cd);
}
System.out.println(cdsList);
br.close();
} catch (IOException e) {
System.out.println(e);
}
}

java.lang.RuntimeException: Cannot open files

I have DataManager.java and ExportBasicTest.java for tests.
I can't get my DataManager.java to pass the tests, even though they seem like basic errors.
I tried messing around with the directories of the two files and the file that I create called ExportedFile.txt but I can't fix any of my errors.
I have two arrayLists of type <Passenger> and <Flight> which have different parts of each. These parts are what my long methods are referencing.
DataManager.java:
import java.io.*;
import java.util.*;
public class DataManager {
private static File fileName;
private static Formatter fileFormatter;
private static ArrayList<Flight> theFlights;
private static ArrayList<Passenger> thePassengers;
public static void exportData(String filename, ArrayList<Passenger> passengers, ArrayList<Flight> flights) {
fileName = new File(filename);
theFlights = flights;
thePassengers = passengers;
openFile();
addFlights();
addPassengers();
closeFile();
}
public static void openFile(){
try{
fileFormatter = new Formatter(fileName);
System.out.println("you created a file");
}
catch(Exception e){
System.out.println("You have an error.");
}
}
public static int AlertsCount(int i){
return thePassengers.get(i).getAlerts().size();
}//AlertsCount
public static String listAlerts(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getAlerts().size();z++){
stringBuilder.append(thePassengers.get(i).getAlerts().get(z) + System.getProperty("line.separator"));
}
String alerts = stringBuilder.toString();
return alerts;
}//listAlerts close
public static int BookedFlightsCount(int i){
return thePassengers.get(i).getBookedFlights().size();
}//bookedFlightsCount close
public static String listBookedFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getBookedFlights().size();z++){
stringBuilder.append(thePassengers.get(i).getBookedFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getBookedFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getLandingTime()) + System.getProperty("line.separator"));
}
String bookedFlights = stringBuilder.toString();
return bookedFlights;
}//listBookedFlights close
public static int StandbyFlightsCount(int i){
return thePassengers.get(i).getStandbyFlights().size();
}//StandbyFlightsCount close
public static String listStandbyFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getStandbyFlights().size();z++){
stringBuilder.append(System.getProperty("line.separator") + thePassengers.get(i).getStandbyFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getStandbyFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getLandingTime()));
}
String standbyFlights = stringBuilder.toString();
return standbyFlights;
}//listStandbyFlights close
public static void addPassengers(){
fileFormatter.format("%s%d", "#passCount ", thePassengers.size());
for(int i = 0; i<thePassengers.size();i++){
fileFormatter.format("%s%s%s%s%s%s%d%s%s%d%s%s%d%s",System.getProperty("line.separator"), "#newPass",System.getProperty("line.separator"), thePassengers.get(i).getFirstName()+" , ", thePassengers.get(i).getLastName(),System.getProperty("line.separator"),
AlertsCount(i),System.getProperty("line.separator"), listAlerts(i), BookedFlightsCount(i),System.getProperty("line.separator"), listBookedFlights(i), StandbyFlightsCount(i), listStandbyFlights(i));
}
}//addPassengers close
public static void addFlights(){
fileFormatter.format("%s%d%s", "#flightCount ", theFlights.size(), System.getProperty("line.separator"));
for(int i = 0;i<theFlights.size();i++){
fileFormatter.format("%s%s%s , %s , %d , %d%s%d%s", "#newFlight",System.getProperty("line.separator"), theFlights.get(i).getSourceAirport(), theFlights.get(i).getDestinationAirport(),
theFlights.get(i).getTakeOffTime(), theFlights.get(i).getLandingTime(), System.getProperty("line.separator"),theFlights.get(i).getCapacity(),System.getProperty("line.separator"));
}
}//addFlights close
public static void closeFile(){
fileFormatter.close();
}//closeFile close
//This function creates and writes data for a new file using the specifications ,
//given earlier in order to store the data represented by those objects stored within the two ArrayLists.
}
ExportBasicTest.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import junit.framework.Assert;
import org.junit.Test;
public class ExportBasicTest {
#Test(timeout = 1000)
public void exportExampleFile()
{
ArrayList<Flight> flightList = new ArrayList<Flight>();
Flight f1 = new Flight("MCO", "MIA", 800, 930, 8);
Flight f2 = new Flight("MIA", "ATL", 1100, 1400, 23);
Flight f3 = new Flight("ATL", "GNV", 1430, 1615, 15);
flightList.add(f1);
flightList.add(f2);
flightList.add(f3);
ArrayList<Passenger> passList = new ArrayList<Passenger>();
Passenger p1 = new Passenger("Joshua", "Horton");
Passenger p2 = new Passenger("Adam", "Smith");
passList.add(p1);
passList.add(p2);
p1.addAlert("The 7:30 flight from BTR to GNV has been cancelled!");
p1.bookFlight(f1);
p1.bookFlight(f2);
p2.bookFlight(f3);
p2.addStandbyFlight(f1);
p2.addStandbyFlight(f2);
DataManager.exportData("ExportedFile.txt", passList, flightList);
// This file, given the initial setup, should almost perfectly match the provided example file.
Assert.assertEquals("File contents are not as expected!", true, matchFiles("ProjStage3BasicFile.txt", "ExportedFile.txt"));
}
// Checks if the files match by directly comparing their exact contents.
private boolean matchFiles(String expected, String actual)
{
Scanner inFile1;
Scanner inFile2;
try
{
inFile1 = new Scanner(new File(expected));
inFile2 = new Scanner(new File(actual));
}
catch(IOException e)
{
throw new RuntimeException("Cannot open files!", e);
}
ArrayList<String> expectedLines = new ArrayList<String>();
ArrayList<String> actualLines = new ArrayList<String>();
while(inFile1.hasNextLine())
{
expectedLines.add(inFile1.nextLine());
}
while(inFile2.hasNextLine())
{
actualLines.add(inFile2.nextLine());
}
// Erase a trailing blank line at the file's end; I don't mind that.
if(actualLines.get(actualLines.size() - 1).trim().equals(""))
{
actualLines.remove(actualLines.size() - 1);
}
return expectedLines.equals(actualLines);
}
}
You need to pass the path to the files not just the names where ever you use a filename.
Your match files method is throwing an error because it cannot open the file names you passed. To use the current working directory use ./ as in "./filename.txt" as opposed to "filename.txt"
You can always check if a path exists Using java.nio.file.Files
if(Files.exists(path)){...}

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.

How can i show it at first?

I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}

Categories

Resources