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.
Related
I'm having a problem where I read a textfile named "songs.txt" with Scanner in a function called loadFiles() which every line is:
Music ID # Song Name # Release Date
And with this I create a Song object, and then store said object in a ArrayList. After reading the file, I clone this ArrayList so I can return a ArrayList with the songs read and clear the first ArrayList to prevent the cases where for exemple:
(PS: I use the ArrayLists as global variables)
songs.txt has this structure:
1oYYd2gnWZYrt89EBXdFiO#Message In A Bottle#1979
7zxc7dmd82nd92nskDInds#Sweet Child of Mine#1980
And the loadFiles() is called 2 times, the ArrayList would have a size of 4 instead of 2 as it should be. So that's why after songs.txt is read I copy the arrayList and then clear the first ArrayList that way the ArrayList that's returned only has the size of 2.
This is my code:
package pt.ulusofona.aed.deisiRockstar2021;
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Main {
public static ArrayList < Song > teste6 = new ArrayList < > ();
public static ArrayList < Song > getSongsArray = new ArrayList < > ();
public static ArrayList < Artista > testeSongArtists = new ArrayList < > ();
public static ParseInfo parseInfoSongsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsArtistsTxT = new ParseInfo(0, 0);
public static ParseInfo parseInfoSongsDetailsTxT = new ParseInfo(0, 0);
public static void main(String[] args) throws IOException {
ArrayList < Song > teste7 = new ArrayList < Song > ();
loadFiles();
loadFiles();
teste7 = getSongs();
ParseInfo teste8 = getParseInfo("songs.txt");
System.out.println("\n----------------------TESTE DO MAIN----------------------");
System.out.println(teste7.toString());
System.out.println(teste8.toString());
System.out.println(getSongsArray.size());
}
public static void loadFiles() throws IOException {
//Aqui lê-se o ficheiro songs.txt
System.out.println("----------------------LEITURA DO FICHEIRO songs.txt------------");
String nomeFicheiro = "songs.txt";
try {
File ficheiro = new File(nomeFicheiro);
FileInputStream fis = new FileInputStream(ficheiro);
Scanner leitorFicheiro = new Scanner(fis);
while (leitorFicheiro.hasNextLine()) {
String linha = leitorFicheiro.nextLine();
String dados[] = linha.split("#");
if (dados.length != 3) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[2].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
//Meter para ignorar a acabar com espaço
parseInfoSongsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String nome = dados[1];
int anoLancamento = Integer.parseInt(dados[2]);
Song song = new Song(idTemaMusical, nome, null, anoLancamento, 0, false, 0, 0, 0, 0);
teste6.add(song);
}
leitorFicheiro.close();
getSongsArray = (ArrayList < Song > ) teste6.clone();
teste6.clear();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro + " nao foi encontrado.";
System.out.println(mensagem);
}
System.out.println(teste6.toString());
System.out.println("Ok: " + parseInfoSongsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_artists.txt------------");
//Aqui é lido o ficheiro song_artists.txt, mas falta ver se é preciso separar vários artistas com o mesmo ID para posições diferentes no ArrayList
String nomeFicheiro2 = "song_artists.txt";
try {
File song_artists = new File(nomeFicheiro2);
FileInputStream fis2 = new FileInputStream(song_artists);
Scanner leitorFicheiro2 = new Scanner(fis2);
while (leitorFicheiro2.hasNextLine()) {
String linha = leitorFicheiro2.nextLine();
String dados[] = linha.split("#");
if (dados.length != 2) {
parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsArtistsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
String artista = dados[1];
Artista artista2 = new Artista(idTemaMusical, artista);
testeSongArtists.add(artista2);
}
leitorFicheiro2.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro2 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println(testeSongArtists.toString());
System.out.println("Ok: " + parseInfoSongsArtistsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsArtistsTxT.NUM_LINHAS_IGNORED + "\n");
System.out.println("----------------------LEITURA DO FICHEIRO song_details.txt------------");
//Aqui lê-se o ficheiro song_details.txt
boolean letra = false;
ArrayList < Song > testeSongDetails = new ArrayList < Song > ();
String nomeFicheiro3 = "song_details.txt";
try {
File song_details = new File(nomeFicheiro3);
FileInputStream fis3 = new FileInputStream(song_details);
Scanner leitorFicheiro3 = new Scanner(fis3);
while (leitorFicheiro3.hasNextLine()) {
String linha = leitorFicheiro3.nextLine();
String dados[] = linha.split("#");
if (dados.length != 7) {
parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[0].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[1].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[3].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[4].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[5].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
if (Character.isWhitespace(dados[6].charAt(0))) {
parseInfoSongsTxT.NUM_LINHAS_IGNORED += 1;
continue;
}
parseInfoSongsDetailsTxT.NUM_LINHAS_OK += 1;
String idTemaMusical = dados[0];
//System.out.println(idTemaMusical);
int duracao = Integer.parseInt(dados[1]);
//System.out.println(duracao);
int letraExplicita = Integer.parseInt(dados[2]);
//System.out.println(letraExplicita);
if (letraExplicita == 0) {
letra = false;
} else {
letra = true;
}
//System.out.println(letra);
int populariedade = Integer.parseInt(dados[3]);
//System.out.println(populariedade);
double dancabilidade = Double.parseDouble(dados[4]);
//System.out.println(dancabilidade);
double vivacidade = Double.parseDouble(dados[5]);
//System.out.println(vivacidade);
double volumeMedio = Double.parseDouble(dados[6]);
//System.out.println(volumeMedio);
Song song = new Song(idTemaMusical, null, null, 0, duracao, letra, populariedade, dancabilidade, vivacidade, volumeMedio);
testeSongDetails.add(song);
}
leitorFicheiro3.close();
} catch (FileNotFoundException exception) {
String mensagem = "Erro: o ficheiro " + nomeFicheiro3 + " não foi encontrado.";
System.out.println(mensagem);
}
System.out.println("Ok: " + parseInfoSongsDetailsTxT.NUM_LINHAS_OK + ", Ignored: " + parseInfoSongsDetailsTxT.NUM_LINHAS_IGNORED);
}
public static ArrayList < Song > getSongs() {
return getSongsArray;
}
public static ParseInfo getParseInfo(String fileName) {
if (fileName == "songs.txt") {
return parseInfoSongsTxT;
}
if (fileName == "song_artists.txt") {
return parseInfoSongsArtistsTxT;
}
if (fileName == "song_details.txt") {
return parseInfoSongsDetailsTxT;
}
return null;
}
}
The problem is that when I made a test to check the function where the ArrayList is returned to see the size of the ArrayList it always comes as 0.
I think it's because only the function the returns the ArrayList is tested so loadFiles() isn't executed so the ArrayListo never gets cloned and that makes the ArrayList that is returned stay the same.
I thought about calling loadFiles() inside getSongs() and that way I would guarantee that the ArrayList is cloned but that would make getSongs use "throws IOException" and since I have to respect the school's project guide and getSongs doesn't include "throws IOException" i can't put it there.
But the more I think about it, that doesn't even make sense because how can they test it with a file of their own and loadFiles() isn't executed?
I'm out of ideas how to solve this problem, any help is welcome thank you.
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 try 3 times when error happened.
What I have done so far....
public class TryTest {
public static void main(String[] args) {
TryTest test = new TryTest();
test.tryThis();
}
public void tryThis() {
int a = 10;
int x = 0;
int count = 1;
try {
System.out.println("Test " + count);
a = a / x;
System.out.println("Success !");
} catch (Exception e) {
if (count <= 3) {
// I want to try again with new x value
count++;
x++;
}
System.out.println("ERROR:\t" + e);
} finally {
System.out.println("Finish");
}
}
}
How can I do this?
Use a loop, which loops using you have a done values [0, 3)
for(int i = 0; i < 3; i++) {
try {
System.out.println("Test " + count);
int a = 10 / i;
System.out.println("Success !");
break;
} catch (Exception e) {
System.out.println("ERROR:\t" + e);
}
}
System.out.println("Finish");
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
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();
}