While Loops with Search Strings
I had a java lab in which I was to create a program that holds a list of names and telephone numbers, and allows the list to be searched. I have done this lab and turned it in. Now my professor gives a chance to earn extra credit on our class grade by fixing the "mistakes" that we make on our assignments. I put mistakes in parenthesis b/c while my program worked, he believed I should have done it differently.
Here is my code:
import javax.swing.JOptionPane;
import java.io.*;
publicclass Lab12{
publicstaticvoid main( String[] args )throws Exception{
String[][] info = arrayFile();
for (String searchString = getSearchString(); searchString !=null; searchString = getSearchString()){
if (searchString ==null){
System.exit(0);
}
int i;
for (i = 0; i < info.length && !searchString.equals(""); i++){
boolean findline = info[i][0].toLowerCase().startsWith( searchString.toLowerCase() );
if (findline){
System.out.println(info[i][0]+"\t" + info[i][1] +"\t" + info[i][2]);
break;
}
}
if (i == info.length){
System.out.println("There is no match in the list for: " + searchString);
}
}
}
publicstatic String[][] arrayFile()throws Exception{
String fileName = JOptionPane.showInputDialog( null,"Enter filename to read with file path:","phone.txt" );
BufferedReader readIn =new BufferedReader(new FileReader( fileName ));
String input = readIn.readLine();
int i;
for (i = 0; input !=null; i++){
input = readIn.readLine();
}
readIn.close();
readIn =new BufferedReader(new FileReader( fileName ));
String[][] array =new String[i][3];
for (i = 0; i < array.length; i++){
input = readIn.readLine();
String[] lineArray = input.split("\t");
array[i][0] = lineArray[0];
array[i][1] = lineArray[1];
array[i][2] = lineArray[2];
}
readIn.close();
return array;
}
publicstatic String getSearchString(){
String returnStr = JOptionPane.showInputDialog( null,"Enter the name to search:",null);
return returnStr;
}
}
This was the only correction my professor suggested:
The loop would probably be better as a while loop. Then you wouldn't need
that test in
line 15 for searchString == null, which is only useful if CANCEL is hit the
very first time
the input is requested.
The problem is that I for the life of me can't figure out how to implement a While Loop in this situation.

