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
Related
I'm newly working with android Thread.
I have a thread Running:
private Thread startQuery(){
return new Thread(() -> {
Handler handler = new Handler(getApplicationContext().getMainLooper());
for(int i = 1; i <= NUMBER_OF_QUERY && isThreadAlive; i++){
int tempTime = timePerQuery;
int finalI = i;
handler.post(() -> {
Random random = new Random();
int num1 = Math.abs(random.nextInt(maxNumb1)), num2 = Math.abs(random.nextInt(maxNumb2));
setCurrentResult(num1, num2);
String strNum1 = num1 + "", strNum2 = num2 + "";
txtOp.setText(typeOfOperation);
txtNumbers.setText(equalizeNumbers(strNum1, strNum2));
queryCount = finalI;
String count = "Query No: " + queryCount;
txtQueryCount.setText(count);
});
while (tempTime > 0 && isThreadAlive){
int sec = tempTime/1000,
min = sec/60;
int sec1 = sec%60;
String s = min + " : " + sec1;
txtRemainingTime.setText(s);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tempTime -= 1000;
}
}
});
}
This thread is making values for variable "currentResult" in each iteration. Now
I want to use the value of "currentResult" from Main Thread on Clicking a button like this:
if(id == R.id.game_btnSubmit){
String strInput = edtUserResultInput.getText().toString();
if(strInput.isEmpty()){
edtUserResultInput.setError("Enter Result");
edtUserResultInput.requestFocus();
return;
}
double input = Double.parseDouble(strInput);
if(currentResult == input){
isRight[queryCount] = 1;
Toast.makeText(this, "Correct", Toast.LENGTH_LONG).show();
}
else{
isRight[queryCount] = 0;
Toast.makeText(this, "Wrong", Toast.LENGTH_LONG).show();
}
}
But the problem is, after clicking the button My app gets freeze.
Why?
Where is the problem or what is the solution?
I'm stuck with this.
Thank you <3
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.
I've been kicking this code around for a while and I think I know what the general problem is, I can't figure out how to correct it. I'm getting the following error:
C:\Documents and Settings\Joe King\My Documents\418.85A Java\Project5>javac Project5.java
Project5.java:408: error: variable boatNames might not have been initialized
boatArray1 = new Boat[boatNames.length];
^
1 error
The problem is my boatNames array is in a try/catch block and I think this is isolating it from the rest of the code. How can I get the boatNames array out of the try/catch block?
My code is as follows:
class Project5{
public static void main(String[] args){
String[] boatNames;
Boat[] boatArray1;
Boat[] boatArray2;
String result = " ";
String name = null;
char firstChar;
char firstLetter;
char secondLetter;
int totalRead;
int i;
int j;
int k;
int l;
int m;
Path inPath = Paths.get("C:/Documents and Settings/Joe King/My Documents/418.85A Java/Projects/Input").resolve("Boat Names.txt");
if(!Files.exists(inPath)){
System.out.println(inPath + " does not exist. Terminating the program.");
System.exit(1);
}
try(BufferedReader fileIn = Files.newBufferedReader(inPath, Charset.forName("UTF-16"))){
totalRead = 0;
while(fileIn.readLine() != null){
name = fileIn.readLine();
++totalRead;
name = null;
}
boatNames = new String[totalRead];
for(i = 0 ; i < boatNames.length ; ++i){
name = fileIn.readLine();
boatNames[i] = name;
name = null;
}
}catch(IOException e){
System.err.println("Error writing file: " + inPath);
e.printStackTrace();
}
Path outPath = Paths.get("C:/Documents and Settings/Joe King/My Documents/418.85A Java/Projects/Output").resolve("Fleet Registry.txt");
try{
Files.createDirectories(outPath.getParent());
}catch(IOException e){
System.err.println("Error creating directory: " + outPath.getParent());
e.printStackTrace();
System.exit(1);
}
boatArray1 = new Boat[boatNames.length];
if(boatNames.length > 0){
try(BufferedWriter fileOut = Files.newBufferedWriter(outPath, Charset.forName("UTF-16"))){
for(j = 0 ; j < boatNames.length ; j++){
String delimiters = "[. ,]";
int limit = -1;
String[]tokens = boatNames[j].split(delimiters, limit);
for(k = 0 ; k < tokens.length ; ++k){
firstChar = tokens[k].charAt(0);
firstChar = Character.toUpperCase(firstChar);
char[] tokenArray = tokens[k].toCharArray();
String text = new String(tokenArray, 1, (tokenArray.length - 1) );
tokens[k] = firstChar + text;
result = result + tokens[k] + " ";
if(k != tokens.length - 1){
continue;
}else{
result = result.trim();
boatNames[k] = result;
result = " ";
}
}
firstLetter = boatNames[j].charAt(0);
if((firstLetter == 'B') || (firstLetter == 'C') || (firstLetter == 'N')){
boatArray1[j] = new RaceBoat();
}else{
boatArray1[j] = new SailBoat();
}
boatArray1[j].christenBoat(boatNames[j]);
}
System.out.println("\n");
for(l = 0 ; l < boatNames.length ; ++l){
secondLetter = Character.toUpperCase(boatNames[l].charAt(1));
if((secondLetter == 'A') || (secondLetter == 'E')){
if(l > 0){
fileOut.newLine();
}
fileOut.write(boatArray1[l].goFast());
}else{
if(l > 0){
fileOut.newLine();
}
fileOut.write(boatArray1[l].goSlow());
}
fileOut.newLine();
fileOut.write(boatArray1[l].launchBoat());
fileOut.newLine();
fileOut.write(boatArray1[l].whatIsBoatState());
fileOut.newLine();
}
boatArray2 = new Boat[3];
boatArray2[0] = new SailBoat();
boatArray2[1] = new RaceBoat("Endurance", true);
boatArray2[2] = new RaceBoat(false);
for(m = 0 ; m < boatArray2.length ; ++m){
fileOut.newLine();
fileOut.write(boatArray2[m].toString());
fileOut.newLine();
fileOut.write(boatArray2[m].launchBoat());
fileOut.newLine();
fileOut.write(boatArray2[m].whatIsBoatState());
fileOut.newLine();
}
fileOut.newLine();
fileOut.write("There are " + Boat.boatCount + " boats in the fleet this morning.");
}catch(IOException e){
System.err.println("Error writing outPath: " + outPath);
e.printStackTrace();
}
}else{
System.out.println("\n\n\nArgh!... you forgot to enter ship names scalawag!" +
"\n\n\n\tPlease try again!");
}
System.out.println("\nThe Fleet Registry is completed, press ENTER to continue.\n");
try{
System.in.read();
} catch(IOException e){
return;
}
}
}
Thank you everyone, I've entered the following:
if(boatNames != null){
boatArray1 = new Boat[boatNames.length];
if(boatNames.length > 0){
try(BufferedWriter fileOut = Files.newBufferedWriter(outPath, Charset.forName("UTF-16"))){
for(j = 0 ; j < boatNames.length ; j++){
String delimiters = "[. ,]";
int limit = -1;
String[]tokens = boatNames[j].split(delimiters, limit);
for(k = 0 ; k < tokens.length ; ++k){
firstChar = tokens[k].charAt(0);
firstChar = Character.toUpperCase(firstChar);
char[] tokenArray = tokens[k].toCharArray();
String text = new String(tokenArray, 1, (tokenArray.length - 1) );
tokens[k] = firstChar + text;
result = result + tokens[k] + " ";
if(k != tokens.length - 1){
continue;
}else{
result = result.trim();
boatNames[k] = result;
result = " ";
}
}
firstLetter = boatNames[j].charAt(0);
if((firstLetter == 'B') || (firstLetter == 'C') || (firstLetter == 'N')){
boatArray1[j] = new RaceBoat();
}else{
boatArray1[j] = new SailBoat();
}
boatArray1[j].christenBoat(boatNames[j]);
}
System.out.println("\n");
for(l = 0 ; l < boatNames.length ; ++l){
secondLetter = Character.toUpperCase(boatNames[l].charAt(1));
if((secondLetter == 'A') || (secondLetter == 'E')){
if(l > 0){
fileOut.newLine();
}
fileOut.write(boatArray1[l].goFast());
}else{
if(l > 0){
fileOut.newLine();
}
fileOut.write(boatArray1[l].goSlow());
}
fileOut.newLine();
fileOut.write(boatArray1[l].launchBoat());
fileOut.newLine();
fileOut.write(boatArray1[l].whatIsBoatState());
fileOut.newLine();
}
boatArray2 = new Boat[3];
boatArray2[0] = new SailBoat();
boatArray2[1] = new RaceBoat("Endurance", true);
boatArray2[2] = new RaceBoat(false);
for(m = 0 ; m < boatArray2.length ; ++m){
fileOut.newLine();
fileOut.write(boatArray2[m].toString());
fileOut.newLine();
fileOut.write(boatArray2[m].launchBoat());
fileOut.newLine();
fileOut.write(boatArray2[m].whatIsBoatState());
fileOut.newLine();
}
fileOut.newLine();
fileOut.write("There are " + Boat.boatCount + " boats in the fleet this morning.");
}catch(IOException e){
System.err.println("Error writing outPath: " + outPath);
e.printStackTrace();
}
}else{
System.out.println("\n\n\nArgh!... you forgot to enter ship names scalawag!" +
"\n\n\n\tPlease try again!");
}
System.out.println("\nThe Fleet Registry is completed, press ENTER to continue.\n");
try{
System.in.read();
} catch(IOException e){
return;
}
}
Now I'm getting the following error:
C:\Documents and Settings\Joe King\My Documents\418.85A Java\Project5>java Project5
Exception in thread "main" java.lang.NullPointerException
at Project5.main(Project5.java:424)
This doesn't make sense to me, in order to get to line 424 the boatNames array cannot be null because the length of boatNames was used several times before line 424. What am I missing?
Thanks
The variable is out of the try/catch, otherwise the compile error would be different. The problem is that the initialization is inside the try block, so that code after the try can't be sure the variable was initialized.
There are two ways to deal with this:
Initialize the variable when you declare it. Just using this would be enough:
String[] boatNames = null;
Move all the code that uses the variable inside the try block. This is often a good strategy, but only if your methods are small. In your case, I wouldn't recommend this, as your method is much too long. Now, if you could break your code up into shorter methods, then limiting the scope of the variable to a single try block would make good sense.
Before the try/catch block, initialize the array like this:
String[] boatNames = null;
You have declared your array outside try block
String[] boatNames;
It will be initialized under first try block
boatNames = new String[totalRead];
Issue is here boatArray1 = new Boat[boatNames.length];
Reason, your compiler has no way to know if boatNames initialization will be successful as there might be an exception and initialization will fail.
As part of your declaration you can do this:
String[] boatNames = null; // This will fix your immediate problem
but doing this may lead you to NullPointerException since your File read can fail.
To solve this do a null check on your array before you use it.
if(boatNames == null){
// I am not going to go further or will take corrective measures here
}
The compiler here considers the possibility that an exception might be raised in the try block even before boatNames is initialized hence it gives the compiler error might not have been initialized. The might is important here!
The ideal solution here would be to tweak your code structure and put
boatArray1 = new Boat[boatNames.length];
in the same try block!
I implemented this code below in order to read contacts from the addressbook of the phone
The problem is, In a case when all the numbers in the phonebook are saved in the SIM it reads and displays the contacts for selection.
But in a case whereby any number is included on the phone memory, it gives an application error.(OutOfMemoryException)
What do I do (PS do not mind some System.out.println statements there. I used them for debugging)
public void execute() {
try {
// go through all the lists
String[] allContactLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
if (allContactLists.length != 0) {
for (int i = 0; i < allContactLists.length; i++) {
System.out.println(allContactLists[i] + " " + allContactLists[1]);
System.out.println(allContactLists.length);
loadNames(allContactLists[i]);
System.out.println("Execute() error");
}
} else {
available = false;
}
} catch (PIMException e) {
available = false;
} catch (SecurityException e) {
available = false;
}
}
private void loadNames(String name) throws PIMException, SecurityException {
ContactList contactList = null;
try {
// ----
// System.out.println("loadErr1");
contactList = (ContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, name);
// System.out.println(contactList.getName());//--Phone Contacts or Sim Contacts
// First check that the fields we are interested in are supported(MODULARIZE)
if (contactList.isSupportedField(Contact.FORMATTED_NAME)
&& contactList.isSupportedField(Contact.TEL)) {
// ContactLst.append("Reading contacts...", null);
// System.out.println("sup1");
Enumeration items = contactList.items();
// System.out.println("sup2");
Vector telNumbers = new Vector();
telNames = new Vector();
while (items.hasMoreElements()) {
Contact contact = (Contact) items.nextElement();
int telCount = contact.countValues(Contact.TEL);
int nameCount = contact.countValues(Contact.FORMATTED_NAME);
// System.out.println(telCount);
// System.out.println(nameCount);
// we're only interested in contacts with a phone number
// nameCount should always be > 0 since FORMATTED_NAME is
// mandatory
if (telCount > 0 && nameCount > 0) {
String contactName = contact.getString(Contact.FORMATTED_NAME, 0);
// go through all the phone numbers
for (int i = 0; i < telCount; i++) {
System.out.println("Read Telno");
int telAttributes = contact.getAttributes(Contact.TEL, i);
String telNumber = contact.getString(Contact.TEL, i);
System.out.println(telNumber + " " + "tel");
// check if ATTR_MOBILE is supported
if (contactList.isSupportedAttribute(Contact.TEL, Contact.ATTR_MOBILE)) {
if ((telAttributes & Contact.ATTR_MOBILE) != 0) {
telNames.insertElementAt(telNames, i);
telNumbers.insertElementAt(telNumber, i);
} else {
telNumbers.addElement(telNumber);
telNames.addElement(telNames);
}
}
// else {
//// telNames.addElement(contactName);
// telNumbers.addElement(telNumber);
// }
System.out.println("telephone nos");
}
// Shorten names which are too long
shortenName(contactName, 20);
for (int i = 0; i <= telNumbers.size(); i++) {
System.out.println(contactName + " here " + telNames.size());
telNames.addElement(contactName);
System.out.println(telNames.elementAt(i) + " na " + i);
}
names = new String[telNames.size()];
for (int j = 0; j < names.length; j++) {
names[j] = (String) telNames.elementAt(j);
System.out.println(names[j] + "....");
}
// allTelNames.addElement(telNames);
System.out.println("cap :" + telNames.size() + " " + names.length);
// telNames.removeAllElements();
// telNumbers.removeAllElements();
}
}
available = true;
} else {
// ContactLst.append("Contact list required items not supported", null);
available = false;
}
} finally {
// always close it
if (contactList != null) {
contactList.close();
}
}
}