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.
Related
I have written a small program in Java (eclipse) to run R using JRI (rjava). All paths are set. The problem is that while I can run numeric functions (like add), I can't run a string function like cat. (please excuse any errors; I did Java coding for the first time yesterday).
package com.trial.ss;
import org.rosuda.JRI.Rengine;
public class RScriptConnection {
public Rengine getRScriptEngine() throws Exception {
Rengine engine = null;
try {
engine = Rengine.getMainEngine();
if (engine == null) engine = new Rengine(new String[] {
"--vanilla"
},
false, null);
/* if (!engine.waitForR()) {
System.out.println("Unable to load R");
return null;
} else*/
System.out.println("Connected to R");
String rScriptSourceFile = "source('" + RScriptConstant.RS_FILE_LOCATION + "',verbose=TRUE)";
engine.eval(rScriptSourceFile);
System.out.println("loading RScript file || completed");
//return engine;
} catch(Exception ex) {
System.out.println("Exeption while connecting to REngine " + ex.getMessage());
//throw new Exception("Error while creating REngine in RScriptConnection:getRScriptEngine()");
}
return engine;
}
public static void main(String[] args) {
String libpath = System.getProperty("java.library.path");
System.out.println("##############libpath=" + libpath);
// System.out.println("Method to be called in RScript=" + "Add(x1 = " + 10 + ", x2 = " + 20 + ", x3 = " + 30 + ", x4 = " + 50 + ")");
RScriptConnection rScriptConnection = new RScriptConnection();
try {
Rengine rEngine = rScriptConnection.getRScriptEngine();
String Value1 = "\"Advisory\"";
String Value2 = "\"Assurance\"";
double svalue = rEngine.eval("(1+2)").asDouble();
System.out.println("mvalue=" + svalue);
System.out.println("method to be called in RScript is " + "cat(" + Value1 + "," + Value2 + ")");
String value = rEngine.eval("cat(" + Value1 + "," + Value2 + ")").asString();
System.out.println(value);
rEngine.end();
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please help me understand why my string function like cat doesn't work.
Here is the output I am currently getting:
##############libpath=C:\Users\myname\Documents\R\win-library\3.3\rJava\jri\x64
Connected to R
loading RScript file || completed
mvalue=3.0
method to be called in RScript is cat("Advisory","Assurance")
null
Why am I getting null in the end? I should get Advisory Assurance
Bellow is an example of how to show R output into Java. You basically have to implement RMainLoopCallbacks.
import org.rosuda.JRI.RMainLoopCallbacks;
import org.rosuda.JRI.Rengine;
import java.util.logging.Logger;
public class Runner {
private static Logger log = Logger.getLogger("Runner");
static class LoggingConsole implements RMainLoopCallbacks {
private Logger log;
LoggingConsole(Logger log) {
this.log = log;
}
public void rWriteConsole(Rengine re, String text, int oType) {
log.info(String.format("rWriteConsole: %s", text));
}
public void rBusy(Rengine re, int which) {
log.info(String.format("rBusy: %s", which));
}
public void rShowMessage(Rengine re, String message) {
log.info(String.format("rShowMessage: %s", message));
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
return null;
}
public String rChooseFile(Rengine re, int newFile) {
return null;
}
public void rFlushConsole(Rengine re) {
}
public void rLoadHistory(Rengine re, String filename) {
}
public void rSaveHistory(Rengine re, String filename) {
}
}
Rengine engine = new Rengine(new String[] {"--no-save"}, false, new LoggingConsole(log));
...
// Use the engine somewhere to evaluate a R method and see the output
engine.eval(rScriptSourceFile);
}
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...
}
I'm trying to read objects from a file in the Internet. I have been given the object class, which is this:
import java.io.Serializable;
public class Sulearvuti extends Arvuti implements Serializable {
private static final long serialVersionUID = 1L;
//isendiväli
private int aku;
//konstruktor
public Sulearvuti(String tootja, String mudel, String lisainfo,
int järjekorraNumber, int raskusaste, boolean kiirtellimus, int aku)
throws ValeRaskusAsteErind {
super(tootja, mudel, lisainfo, järjekorraNumber, raskusaste,
kiirtellimus);
this.aku = aku;
}
// meetod toString, kasutama ülemklassi meetodit
public String toString() {
return "Sülearvuti [aku=" + aku + ", " + super.toString() + "]";
}
// meetodi ülekatmine
double parandamiseAeg(){
return this.getRaskusaste()*2;
}
}
Now when I'm trying to read the objects (Sulearvuti), I get ClassNotFoundException. This is the piece of code :
ObjectInputStream ois =
new ObjectInputStream (
new URL("http://www.ut.ee/~marinai/sulearvutid.dat")
.openConnection()
.getInputStream());
int arv=ois.readInt();
Sulearvuti sülearvuti=(Sulearvuti)ois.readObject();
There's no problem with the Integer, but it won't recognize the class. I've been desperate for the past hour or so...
Also here's the code for the superclass "Arvuti":
import java.io.Serializable;
public class Arvuti implements Serializable, Comparable<Arvuti> {
private String tootja;
private String mudel;
private String lisainfo;
private int jrnumber;
private int vea_raskusaste;
private boolean kiirtellimus;
String getTootja() {
return tootja;
}
String getMudel() {
return mudel;
}
String getLisainfo() {
return lisainfo;
}
int getJrnumber() {
return jrnumber;
}
int getVea_raskusaste() {
return vea_raskusaste;
}
boolean isKiirtellimus() {
return kiirtellimus;
}
void setTootja(String tootja) {
this.tootja = tootja;
}
void setMudel(String mudel) {
this.mudel = mudel;
}
void setLisainfo(String lisainfo)throws WindowsXPErind {
this.lisainfo = lisainfo;
if(lisainfo.contains("WindowsXP"))throw new WindowsXPErind();
}
void setJrnumber(int jrnumber) {
this.jrnumber = jrnumber;
}
void setVea_raskusaste(int vea_raskusaste)throws ValeRaskusAsteErind {
if(vea_raskusaste<1 || vea_raskusaste>10) throw new ValeRaskusAsteErind();
this.vea_raskusaste = vea_raskusaste;
}
void setKiirtellimus(boolean kiirtellimus) {
this.kiirtellimus = kiirtellimus;
}
Arvuti(String tootja, String mudel, String lisainfo, int jrnumber,
int vea_raskusaste, boolean kiirtellimus)throws ValeRaskusAsteErind {
try{
setTootja( tootja);
setMudel(mudel);
setJrnumber(jrnumber);
setVea_raskusaste(vea_raskusaste);
setKiirtellimus(kiirtellimus);
setLisainfo(lisainfo);
}
catch (WindowsXPErind e){
System.out.println("WindowsXPErind");
setVea_raskusaste(vea_raskusaste+2);
}
}
double parandamiseAeg(){
return getVea_raskusaste()*1.5;
}
public String toString() {
return "Arvuti [tootja=" + tootja + ", mudel=" + mudel + ", lisainfo="
+ lisainfo + ", järjekorranumber=" + jrnumber + ", vea raskusaste="
+ vea_raskusaste + ", kiirtellimus=" + kiirtellimus
+ ", parandamise aeg=" + parandamiseAeg() + "]";
}
public int compareTo(Arvuti arvuti){
if(this.isKiirtellimus()==true && arvuti.isKiirtellimus()==false) return -1;
else if(this.isKiirtellimus()==false && arvuti.isKiirtellimus()==true) return 1;
else{
if(this.getJrnumber()<arvuti.getJrnumber())return -1;
else if(this.getJrnumber()>arvuti.getJrnumber())return 1;
else return 0;
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type ClassNotFoundException
at Peaklass.main(Peaklass.java:36)
You are missing some classes contained in the .dat file. Lookout for the classname shown in the classnotfound exception.
It is not sufficient to have the "Sulearvuti", you also need "Arvuti" (superclass) and "ValeRaskusAsteErind" (Exception) in your classpath.
BTW the language looks very funny to me, what language is this ?
Is "Sulearvuti" class on the classpath of the application trying to deserialize the object?
I think my problem will be e laughti thing for you.
I have three classes called (CloudCommunicator, EnergyManagerJob and the Main)
My CloudCommunicator looks like that:
public class CloudCommunicator {
private String _chargingStationId;
public void cloudCommunicator(String charginStationId)
{
_chargingStationId = charginStationId;
}
public EnergyManagerJob SendRequest(boolean chargingOnGoing, boolean setCarConnectedToChargePoint, int setChargingStationDisfunction, float setMeterValue, String setUserId)
{
DChargingStationRequest dChargingStationRequest = new DChargingStationRequest();
dChargingStationRequest.chargingOnGoing=chargingOnGoing;
dChargingStationRequest.carConnectedToChargePoint=setCarConnectedToChargePoint;
dChargingStationRequest.chargingStationDisfunction=setChargingStationDisfunction;
dChargingStationRequest.chargingStationId = _chargingStationId;
dChargingStationRequest.meterValue=setMeterValue;
dChargingStationRequest.userId=setUserId;
try
{
EVSEHeartbeatService_Service hbs = new EVSEHeartbeatService_Service();
EVSEHeartbeatService h = hbs.getEVSEHeartbeatServiceSoap11();
DChargingStationResponse response = h.chargingStation(dChargingStationRequest);
EnergyManagerJob emj = new EnergyManagerJob();
emj.allowedMaximumCurrent = response.allowedMaximumCurrent;
emj.chargingPending = response.chargingPending;
emj.powerOn = response.powerOn;
}
catch(Exception e)
{
System.out.println("Exception = " + e.getMessage());
}
return SendRequest(chargingOnGoing = true, setCarConnectedToChargePoint =false, setChargingStationDisfunction = 0, setMeterValue = 44, setUserId ="ich");
}
and my EnergyManagerJob look like this:
public class EnergyManagerJob {
public double allowedMaximumCurrent;
public boolean chargingPending;
public boolean powerOn;
}
So we will come to the Problem. In my main i have a while. I want to send the Dates of de CloudCommunicator to the server. And then I get an answer.
My Main look like this.
public class Main {
public static void main(String[] args){
while (true)
{
CloudCommunicator ccc = new CloudCommunicator();
ccc.SendRequest (chargingOnGoing, setCarConnectedToChargePoint, setChargingStationDisfunction , setMeterValue , setUserId);
DChargingStationResponse response = new DChargingStationResponse();
System.out.println("\nDie Lade Station Startet: " + response.allowedMaximumCurrent);
System.out.println("Die Lade Station wurde gestartet: " +response.isChargingPending());
System.out.println("Die Lade Station wurde gestartet: " +response.isPowerOn());
try {
Thread.sleep(30000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
Thank you for the Help. I think its not a big Problem but i have a blackout. xD
Your code doesn't compile. The variables chargingOnGoing, setCarConnectedToChargePoint, setChargingStationDisfunction, setMeterValue and setUserId are simply not defined. In your main method.
Either define them (boolean charginOnGoing = true) or call SendRequest with the values inlined (ccc.SendRequest( true, ... )).
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