I am making a program that makes use of two Array Lists. I've researched how to write the objects to binary and I've tried implementing it but it never works correctly. I need to be able to run the program create the file and then write to the file when I want to save. The next time the program is loaded it needs to be able to read the array lists back in. I already have Serializable implemented in my two objects that I'm storing.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
//Add person functionality next
public class main {
ArrayList<Person> people = new ArrayList<Person>();
ArrayList<Date> dates = new ArrayList<Date>();
//Possibly add a checkExistence Function somewhere
//Otherwise self explanatory
public boolean newPerson(){
Scanner kbd = new Scanner(System.in);
String input = "";
boolean nameIsCorrect = false;
boolean typeIsCorrect = false;
do{
boolean nameContinue = false;
while(!nameContinue){
System.out.println("What is the name?");
input = kbd.nextLine();
nameContinue = yesOrNo();
if(nameContinue){
nameContinue = checkForExistence(input);
if(!nameContinue){
System.out.println("Name already exists, try again");
}
}
}
String[] tokens = input.split(" ");
if(tokens.length == 1){
String name = tokens[0];
String type = "";
do{
System.out.println("What type? F (Family) P (Punch) S (Season)");
input = kbd.nextLine();
if(input.equalsIgnoreCase("f")){
type = "f";
typeIsCorrect = true;
nameIsCorrect = true;
}
else if(input.equalsIgnoreCase("s")){
type = "s";
typeIsCorrect = true;
nameIsCorrect = true;
}
else if(input.equalsIgnoreCase("p")){
type = "p";
typeIsCorrect = true;
nameIsCorrect = true;
}
else{
System.out.println("Invalid, try again");
}
} while(!typeIsCorrect);
Person np = new Person(name, type);
people.add(np);
System.out.println(np.getName() + " added!");
}
else{
System.out.println("Not correct format let's try again");
}
} while(!nameIsCorrect);
return true;
}//End of newPerson function
//Cycles through and prints a roster
public boolean printPeopleList(){
for(int i = 0; i < people.size(); i++){
System.out.println(people.get(i).getName());
}
return true;
}
//Testing for valid input
public boolean testDateValidity(String input, int which){
if(which == 1){
String[] dates = new String[21];
int count = 0;
for(int i = 1; i <= 12; i++){
if(i < 10){
dates[count] = "0" + Integer.toString(i);
count++;
}
dates[count] = Integer.toString(i);
count++;
}
for(int j = 0; j < dates.length; j++){
if(input.equalsIgnoreCase(dates[j])){
return true;
}
}
}
else if(which == 2){
String[] dates = new String[40];
int count = 0;
for(int i = 1; i <= 31; i++){
if(i < 10){
dates[count] = "0" + Integer.toString(i);
count++;
}
dates[count] = Integer.toString(i);
count++;
}
for(int j = 0; j < dates.length; j++){
if(input.equalsIgnoreCase(dates[j])){
return true;
}
}
}
else{
return false;
}
return false;
}
//Cycles through and prints all dates and their attendance
public boolean printListOfDates(){
System.out.println("Date\tPeople");
for(int i = 0; i < dates.size(); i++){
System.out.println(dates.get(i).toString());
}
return true;
}
public boolean printCurrentPeople(int day){
dates.get(day).printList();
return true;
}
//Returns the day position from the ArrayList
public int findDayPosition(String month, String day){
for(int i = 0; i < dates.size(); i++){
if(month.equalsIgnoreCase(dates.get(i).getMonth()) && day.equalsIgnoreCase(dates.get(i).getDay())){
return i;
}
}
return -1;
}
public boolean addVisit(String name, int date){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
people.get(i).incrementVisits();
people.get(i).addDay(dates.get(date).toStringPerson());
dates.get(date).addVisitor(name);
return true;
}
}
System.out.println("Person not found");
return false;
}
public boolean addVisit(String name, int visits, int date){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
people.get(i).incrementVisits(visits);
dates.get(date).addVisitor(name, visits);
people.get(i).addDay(dates.get(date).toStringPerson(), visits);
return true;
}
}
System.out.println("Person not found");
return false;
}
public boolean regAdd(int date){
dates.get(date).addRegular();
return true;
}
public boolean regAdd(int date, int visits){
dates.get(date).addRegular(visits);
return true;
}
public boolean helpFunction(){
File fin = new File("help.txt");
if(!fin.exists()){
System.out.println("I'm sorry the help file has become corrupted :(");
System.out.println("Please contact the maker of this program to fix it");
System.out.println("Upon contact he will probably let out a loud UGH");
}
else{
try{
FileReader fr = new FileReader(fin);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException fnf) {
//This line is completely pointless as the if function above serves its purpose
System.out.println("File was not found");
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public boolean checkExistence(String name){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
return true;
}
}
return false;
}
public int getPersonPosition(String name){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
return i;
}
}
return -1;
}
public boolean printPersonDates(String name){
int x = getPersonPosition(name);
people.get(x).printDates();
return true;
}
public String changeMonth(){
Scanner kbd = new Scanner(System.in);
String input;
boolean continueProgram = false;
boolean monthContinue = false;
//Recieve the date
do{
System.out.println("What is the month?");
input = kbd.nextLine();
monthContinue = testDateValidity(input, 1);
if(monthContinue){
continueProgram = true;
}
} while (!continueProgram);
String month = input;
return month;
}
public String changeDay(){
Scanner kbd = new Scanner(System.in);
String input;
boolean continueProgram = false;
boolean dayContinue = false;
//Recieve the date
do{
System.out.println("What is the day?");
input = kbd.nextLine();
dayContinue = testDateValidity(input, 2);
if(dayContinue){
continueProgram = true;
}
} while (!continueProgram);
String day = input;
return day;
}
public boolean yesOrNo(){
Scanner kbd = new Scanner(System.in);
String input;
do{
System.out.println("Are you sure? Y or N");
input = kbd.nextLine();
} while(!checkYes(input));
if(input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")){
return true;
}
else if(input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")){
return false;
}
else{
return false;
}
}
public boolean checkYes(String input){
if(input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")){
return true;
}
else if(input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")){
return true;
}
else{
return false;
}
}
public boolean checkForExistence(String input){
for(int i = 0; i < people.size(); i++ ){
if(input.equalsIgnoreCase(people.get(i).getName())){
return false;
}
}
return true;
}
//Main Function
public static void main(String[] args){
main pool = new main();
Scanner kbd = new Scanner(System.in);
String input;
int numberData;
boolean continueProgram = false;
String month;
String day;
int dayPosition;
String dateString;
System.out.println("Welcome to the Pool Database Management System");
System.out.println("Copyright 2011 by Dalton Dick");
boolean monthContinue = false;
//Recieve the date
do{
System.out.println("What is the month?");
input = kbd.nextLine();
monthContinue = pool.testDateValidity(input, 1);
if(monthContinue){
continueProgram = true;
}
} while (!continueProgram);
month = input;
continueProgram = false;
boolean dayContinue = false;
//Recieve the date
do{
System.out.println("What is the day?");
input = kbd.nextLine();
dayContinue = pool.testDateValidity(input, 2);
if(dayContinue){
continueProgram = true;
}
} while (!continueProgram);
day = input;
//Adding the date object or finding the date already stored
if(pool.findDayPosition(month, day) != -1){
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date already exists, using.");
}
else{
Date dayObject = new Date(month, day);
pool.dates.add(dayObject);
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date added");
}
continueProgram = true;
boolean needsAFunction = true;
while(continueProgram){
System.out.println("Please enter a command");
input = kbd.nextLine();
String[] tokens = input.split(" ");
if(tokens[0].equalsIgnoreCase("help")){
if(tokens.length == 1){
pool.helpFunction();
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("new")){
if(tokens.length == 1){
pool.newPerson();
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("print")){
if(tokens.length == 2){
if(tokens[1].equalsIgnoreCase("people")){
pool.printPeopleList();
}
else if(tokens[1].equalsIgnoreCase("dates")){
pool.printListOfDates();
}
else if(tokens[1].equalsIgnoreCase("current")){
pool.printCurrentPeople(dayPosition);
}
}//End if Statement
else if(tokens.length == 3){
if(pool.checkExistence(tokens[1])){
if(tokens[2].equalsIgnoreCase("dates")){
pool.printPersonDates(tokens[1]);
}
else{
System.out.println("Invalid");
}
}
else{
System.out.println("Person does not exist");
}
}
}
else if(tokens[0].equalsIgnoreCase("quit") || tokens[0].equalsIgnoreCase("q") || tokens[0].equalsIgnoreCase("exit")){
System.out.println("Exiting System");
System.exit(0);
}
else if(tokens[0].equalsIgnoreCase("add")){
if(tokens.length == 1){
System.out.println("Invalid use of the command");
}
else if(tokens.length == 2){
pool.addVisit(tokens[1], dayPosition);
}
else if(tokens.length == 3){
try{
int x = Integer.parseInt(tokens[2]);
pool.addVisit(tokens[1], x, dayPosition);
} catch (NumberFormatException nfe){
System.out.println("Not a number");
}//End try catch block
}//End else if
}
else if(tokens[0].equalsIgnoreCase("change")){
if(tokens.length == 2){
if(tokens[1].equalsIgnoreCase("date")){
month = pool.changeMonth();
day = pool.changeDay();
if(pool.findDayPosition(month, day) != -1){
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date already exists, using.");
}
else{
Date dayObject = new Date(month, day);
pool.dates.add(dayObject);
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date added");
}
}
else{
System.out.println("Invalid Command");
}
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("regular") || tokens[0].equalsIgnoreCase("reg")){
if(tokens.length == 1){
pool.regAdd(dayPosition);
}
else if(tokens.length == 2){
try{
pool.regAdd(dayPosition, Integer.parseInt(tokens[1]));
} catch (NumberFormatException nfe) {
System.out.println("Not correct input");
}
}
}
else{
System.out.println("Invalid Command");
}
}
}
}
Check this example:
ArrayList<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
FileOutputStream fos;
try
{
fos = new FileOutputStream(FILENAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
// read back
FileInputStream fis = new FileInputStream(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ArrayList<Student> listFromFile = (ArrayList) obj;
for (Student student: listFromFile)
{
System.out.println(student.toString());
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am working on automating some excel task and when running the program, I stumbled across an error that says this:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.xssf.usermodel.XSSFRow.getCell(int)" because the return value of "org.apache.poi.xssf.usermodel.XSSFSheet.getRow(int)" is null
at com.excel.auto.ExcelAuto.main(ExcelAuto.java:43)
Below is the code that I have typed so far:
public class ExcelAuto {
public static void main(String args[]) throws IOException {
// To get File Path
Scanner scannerFilePath = new Scanner(System.in);
System.out.println("Please Enter File Path: ");
String excelFilePath = scannerFilePath.nextLine();
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// To get Sheet Name
Scanner scannerSheet = new Scanner(System.in);
System.out.println("Please Enter Excel Sheet Name: ");
String excelSheetName = scannerSheet.nextLine();
XSSFSheet sheet = workbook.getSheet(excelSheetName);
// To set matching transactions to yellow background
CellStyle stylePerfectTrades = workbook.createCellStyle();
stylePerfectTrades.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
stylePerfectTrades.setFillPattern(FillPatternType.SOLID_FOREGROUND);
DataFormatter df = new DataFormatter();
for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {
Cell cellDescriptionSaxo = sheet.getRow(j).getCell(2);
Cell cellNetChangeSaxo = sheet.getRow(j).getCell(3);
Cell cellCheckStatusSaxo = sheet.getRow(j).getCell(5);
if (df.formatCellValue(cellCheckStatusSaxo).contains("-")) {
if (df.formatCellValue(cellDescriptionSaxo).contains(df.formatCellValue(cellTitleWPBO))) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals");
break;
}
// Transaction with same title but not same amount.
else {//If cell has a different value as the one in the row below it
System.out.println("Not Equals lah");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Conversion")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("DEPOSIT")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else {
System.out.println("Not Equals (Conversion)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("stamp duty")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (stamp duty)");
break;
} else {
System.out.println("Not Equals Amount(stamp duty)");
}
} else {
System.out.println("Not Equals (stamp duty)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Dividend")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("Corporate Actions ")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (dividend)");
break;
} else {
System.out.println("Not Equals Amount (Dividend)");
}
} else {
System.out.println("Not Equals (Dividend)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Withdrawal")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Withdrawal)");
break;
} else {
System.out.println("Not Equals Amount (Withdrawal)");
}
} else {
System.out.println("Not Equals (Withdrawal)");
}
}
} else {
System.out.println("Checked");
}
}
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
System.out.println("Done");
}
}
}
Change code blocks like this:
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
to Code like this:
XSSFRow row = sheet.getRow(i);
if (row != null) {
Cell cellTitleWPBO = row.getCell(9);
Cell cellAmountWPBO = row.getCell(10);
Cell cellCheckStatusWPBO = row.getCell(6);
}
I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}
It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now
I want to save a library for a small scale java application which stores technical manuals. Right now I am able to save the library to an external file but I am unable to load it back into the library itself, currently "-1" just gets printed to the console.
How can I solve this?
Here is my code:
//Choice 7: Load Library:
if(Menu.menuChoice == 7){
boolean loadYesNo = Console.readYesNo("\n\nThe manualKeeper app is able to load and display any 'Library.txt' files \nfound in your home folder directory.\n\nWould you like to load and display library? (Y/N):\n");
String fileName = "Library.bin";
if(loadYesNo==true){
try {
FileInputStream fileIs = new FileInputStream(fileName);
ObjectInputStream is = new ObjectInputStream(fileIs);
int x = is.read();
System.out.println(x);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Menu.displayMenu();
}
else if(loadYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not loaded!\n");
System.out.println("--------------------------------------------------------------------------\n");
Menu.displayMenu();
}
}
//Choice 0: Exit the program:
if(Menu.menuChoice == 0){
if(Menu.menuChoice == 0){
if(Library.ManualList.size() > 0){
boolean saveYesNo = Console.readYesNo("\nThe manualKeeper app is able to save your current library to a '.txt' \nfile in your home folder directory (C:\\Users\\ 'YOUR NAME').\n\nWould you like to save the current library? (Y/N):\n");
String fileName = "Library.bin";
if(saveYesNo==true){
try {
FileOutputStream fileOs = new FileOutputStream(fileName);
ObjectOutputStream os = new ObjectOutputStream(fileOs);
for (int i = 0; i < Library.ManualList.size(); i++){
os.writeObject(Library.ManualList.get(i).displayManual());
os.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE WRITING!");
} else if(saveYesNo==false){
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Library not saved!\n");
System.out.println("--------------------------------------------------------------------------\n");
break exit;
}
Menu.displayMenu();
}else if(Library.ManualList.isEmpty()){
Menu.displayMenu();
}
}
}
}
System.out.println("\n ~ You have exited the manualKeeper app! ~ ");
System.out.println("\n Developed by Oscar Moore - 2014 - UWL\n");
System.out.println("\n <3\n");
}
}
Here is also my library class:
package library;
import java.util.ArrayList;
public class Library {
public static int ManualChoice;
static String returnManualTitle;
static String status1 = "Available";
static String status2 = "Borrowed";
public static ArrayList<Manual> ManualList = new ArrayList<Manual>();
static ArrayList<Manual> borrowedManuals = new ArrayList<Manual>();
static void addManual(){
Manual newManual = new Manual();
newManual.createManual();
ManualList.add(newManual);
System.out.println("\n\n--------------------------------------------------------------------------");
System.out.println("\n Manual added to library!\n");
System.out.println("--------------------------------------------------------------------------\n");
}
static void displayManualList(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
System.out.printf("\n\nHere are the Manual/s currently stored in the library:\n\n\n");
for (int i = 0; i < ManualList.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(ManualList.get(i).displayManual());
System.out.println("---------------------------------------------------------\n");
}
}
}
static void displayBorrowedManuals(){
if (ManualList.isEmpty()){
System.out.println("-------------------------------------------------------------");
System.out.println(Messages.empltyLibraryMessage + Messages.tryAgainMessage);
System.out.println("-------------------------------------------------------------");
Menu.menuChoice = 8;
} else {
for (int i = 0; i < borrowedManuals.size(); i++){
System.out.printf("-------------------- Index Number: %s --------------------\n",i);
System.out.println(borrowedManuals.get(i).displayManual());
System.out.println("---------------------------------------------------------");
}
}
}
public static void borrowManual(){
displayManualList();
ManualChoice = (Console.readInteger(Messages.enterManualIndexMessage, Messages.ManualIndexNotInListMessage, 0, Library.ManualList.size() - 1));
borrowLoop:
while(Menu.menuChoice == 3){
if ((ManualList.get(ManualChoice).status.equalsIgnoreCase(status1)) && (ManualList.size() >= ManualChoice)){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n Manual borrowed!\n");
System.out.println("--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualList.get(ManualChoice).status.equalsIgnoreCase(status2) && ManualList.size() >= ManualChoice){
System.out.println("\n--------------------------------------------------------------------------");
System.out.println("\n "
+ " The Manual you wish to borrow is already on loan.");
System.out.println("\n--------------------------------------------------------------------------\n");
break borrowLoop;
}else if(ManualChoice > ManualList.size()-1){
System.out.println(Messages.noSuchManualMessage);
break borrowLoop;
}
if(ManualList.size() > 1){
displayManualList();
}
else if(ManualList.size() == 1){
ManualList.get(ManualChoice).status = "Borrowed";
ManualList.get(ManualChoice).borrower = User.userName;
ManualList.get(ManualChoice).borrowDate = "Today.";
ManualList.get(ManualChoice).returnDate = "In two weeks.";
borrowedManuals.add(ManualList.get(ManualChoice));
System.out.printf("\n\n %s\n\n", ManualList.get(ManualChoice).displayManual());
System.out.println("Please return the Manual within two weeks!\n");
displayManualList();
}
}
Menu.displayMenu();
}
static void returnManual(){
System.out.printf("\n\nHere are the Manual/s currently out on loan:\n\n");
if(borrowedManuals.size() > 0){
for (int i = 0; i < borrowedManuals.size(); i++)
System.out.println(borrowedManuals.get(i).displayManual());
returnManualTitle = Console.readString(Messages.enterManualSerial, Messages.tooShortMessage, 3);
}
int x = 0;
boolean serialExistance = false;
while (x < ManualList.size()){
if (ManualList.get(x).serial.equalsIgnoreCase(returnManualTitle)){
ManualList.get(x).status = "Available";
ManualList.get(x).borrower = "N/A";
ManualList.get(x).borrowDate = "N/A";
ManualList.get(x).returnDate = "N/A";
int p = 0;
while (p < borrowedManuals.size()) {
Manual borrowed = borrowedManuals.get(p);
if (borrowed.serial.equalsIgnoreCase(returnManualTitle)) {
borrowedManuals.remove(p);
break;
}
p++;
}
System.out.println(Messages.successReturnMessage);
serialExistance = true;
break;
}
x = x+1;
}
if(serialExistance == false){
boolean repeatReturnManual = Console.readYesNo("\n--------------------------------------------------------------------------" + "\n\nThe Manual with the serial "+"\""+returnManualTitle +"\""+ " wasn't found!"
+"\n\nDo you want to try again? (Y/N):\n");
System.out.println("\n--------------------------------------------------------------------------");
if(repeatReturnManual){
returnManual();
}
}else if(serialExistance){
Menu.menuChoice = 8;
}
}
public static void removeManual(){
if(ManualList.size() >0){
displayManualList();
ManualChoice = Console.readInteger(Messages.enterRemoveManualIndex ,Messages.ManualIndexNotInListMessage, 0, ManualList.size());
int p = 0;
while (p < borrowedManuals.size()){
if (borrowedManuals.get(p).title.equalsIgnoreCase(returnManualTitle)){
borrowedManuals.remove(p);
}
}
ManualList.remove(ManualChoice);
System.out.print(Messages.successRemovedManualMessages);
Menu.menuChoice = 8;
}
}
static void emptyLibrary(){
System.out.println("\n WARNING!");
System.out.println("\n You have chosen to delete all Manuals in the library.\n");
System.out.println("--------------------------------------------------------------------------");
boolean emptyLibraryChoice = Console.readYesNo("\nAre you sure you wish to destroy the library? (Y/N): \n");
System.out.println("\n--------------------------------------------------------------------------\n");
if(emptyLibraryChoice){
Library.ManualList.clear();
System.out.println(Messages.successEmptyLibraryMesssage);
System.out.println("--------------------------------------------------------------------------\n");
Menu.menuChoice = 8;
}
}
}
You are using ObjectInputStream not in the intended manner. The correct way would be like:
ObjectInputStream is = new ObjectInputStream(fileIs);
Library x = (Library) is.readObject(); // change Library to the type of object you are reading
System.out.println(x);
You probably need to change Library, but I could not find out, what type of object you are reading.
My code reads a file called sort.txt, in which there are lexicon words ordered alphabetically and by length. There is one word in each line. The program works fine and please don't comment how it is written. The user then inputs a word he is searching for, e.g. "C**", and program returns all possible matches (Car, Cat, Cam, etc.). My question is how to search the array using binary search to speed things up. But the binary search would only be used if the first or first two or first 3 characters were input by the user, for instance "Ca*" or "Mou**". If the user inputs "***se" for instance, then the program would skip the binary search and would search the entire array.
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class main{
public static void main(String[] args) {
String izbira;
int dolzina=0;
Scanner in = new Scanner(System.in);
String vnos;
Scanner input = new Scanner(System.in);
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
ArrayList list3 = new ArrayList();
ArrayList list4 = new ArrayList();
ArrayList list5 = new ArrayList();
ArrayList list6 = new ArrayList();
ArrayList list7 = new ArrayList();
ArrayList list8 = new ArrayList();
ArrayList list9 = new ArrayList();
ArrayList list10plus = new ArrayList();
try {
File file = new File("sort.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String vrstica;
while ((vrstica = bufferedReader.readLine()) != null) {
if (vrstica.length() == 1) {
list1.add(vrstica);
}
if (vrstica.length() == 2) {
list2.add(vrstica);
}
if (vrstica.length() == 3) {
list3.add(vrstica);
}
if (vrstica.length() == 4) {
list4.add(vrstica);
}
if (vrstica.length() == 5) {
list5.add(vrstica);
}
if (vrstica.length() == 6) {
list6.add(vrstica);
}
if (vrstica.length() == 7) {
list7.add(vrstica);
}
if (vrstica.length() == 8) {
list8.add(vrstica);
}
if (vrstica.length() == 9) {
list9.add(vrstica);
}
if (vrstica.length() > 9) {
list10plus.add(vrstica);
}
}
do{
do {
System.out.println("Vnesi dožino besede, ki jo iščeš:");
if (in.hasNextInt()) {
dolzina = in.nextInt();
} else if (in.hasNextLine()) {
System.out.printf("Napačen vnos! Poskusi ponovno:%n ",
in.nextLine());
}
} while (dolzina <= 0);
System.out.println("Vnesi besedo za neznano črko vpiši * :");
vnos = input.nextLine();
vnos = vnos.replace("*", ".");
if (dolzina == 1) {
for (int i = 0; i < list1.size(); i++) {
String s = (String) list1.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 2) {
for (int i = 0; i < list2.size(); i++) {
String s = (String) list2.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 3) {
for (int i = 0; i < list3.size(); i++) {
String s = (String) list3.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 4) {
for (int i = 0; i < list4.size(); i++) {
String s = (String) list4.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 5) {
for (int i = 0; i < list5.size(); i++) {
String s = (String) list5.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 6) {
for (int i = 0; i < list6.size(); i++) {
String s = (String) list6.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 7) {
for (int i = 0; i < list7.size(); i++) {
String s = (String) list7.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 8) {
for (int i = 0; i < list8.size(); i++) {
String s = (String) list8.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina == 9) {
for (int i = 0; i < list9.size(); i++) {
String s = (String) list9.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
if (dolzina > 9) {
for (int i = 0; i < list10plus.size(); i++) {
String s = (String) list10plus.get(i);
if (s.matches(vnos))
System.out.println(s);
}
}
dolzina=-1;
System.out.println("Ponovni vnos (da/ne):");
Scanner inn= new Scanner (System.in);
izbira = inn.next();
}while (izbira.equalsIgnoreCase("da"));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
This won't give you a complete answer, but just puts in that direction.
You need to check if the first char is not *, then do a binary search otherwise iterate over all the strings and do String.endsWith().
if(vnos.charAt(0) != '*') {
//do binary search with the substring
} else {
//iterate and check if the string endsWith given suffix.
}
I want to implement Find mechanism (like text editors or word) in my JTextPane.
I want it to have next / previous options (up/down arrows) and highlighting to all the words it found.
Is there a simple way to do so?
I am not an expert, I found the following code working:-
public static void GetTextToFindAndFind(String textToFind, int ignorecase, int findCounter){
// findCounter = 0 or 1. 0 represents find and 1 represents findCounter.
String Current2 = textPane.getText();
if(findCounter ==0){
if(textToFind == null){
optionPane.showMessageDialog(null, "Please Enter Text.", "Error", 0);
}
else if(textToFind.isEmpty()){
optionPane.showMessageDialog(null, "Please Enter Text.", "Error", 0);
}
else{
// Use any Character. But I a suggest to use a character from an Encrypted file.
Replacer = "¥";
CurrentText = textPane.getText();
if(ignorecase==1){
CurrentText = CurrentText.toLowerCase();
textToFind = TextToFind.toLowerCase();
}
int counter = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
try {
String Line = readBuffer.readLine();
int found = 0;
while(Line!=null || found != 1){
if(Line.contains(TextToFind)){
Line = null;
found = 1;
}
if(Line!=null){
Line = readBuffer.readLine();
counter = counter + 1;
}
}
if(found == 1){
textPane.setSelectionStart(CurrentText.indexOf(textToFind) - counter);
textPane.setSelectionEnd(CurrentText.indexOf(textToFind) + textToFind.length() - counter);
int counter2 = 1;
while(counter2!=textToFind.length()){
Replacer = Replacer + "¥";
counter2 = counter2 + 1;
}
CurrentText = CurrentText.replaceFirst(textToFind, Replacer);
findCounter = 1;
}
else{
optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException e){
optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
}
}
}
else{
int counter = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
try {
String Line = readBuffer.readLine();
int found = 0;
while(Line!=null || found != 1){
if(Line.contains(textToFind)){
Line = null;
found = 1;
}
if(Line!=null){
Line = readBuffer.readLine();
counter = counter + 1;
}
}
if(found == 1){
textPane.setSelectionStart(CurrentText.indexOf(textToFind) - counter);
textPane.setSelectionEnd(CurrentText.indexOf(textToFind) + textToFind.length() - counter);
CurrentText = CurrentText.replaceFirst(textToFind, Replacer);
}
else{
optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
}
}
catch(IOException e){
e.printStackTrace();
} catch(NullPointerException e){
optionPane.showMessageDialog(null, "No Matches.", "Message", 0);
}
}
}
There's a JFindReplace tool. You can disable replace and just have find. Apart from that I don't know how good it is.
Link: http://www.javalobby.org/java/forums/t19015.html