我正在尝试做一个小的搜索方法,到目前为止我有一个只搜索 int 类型的方法,我一直想知道是否有可能重新实现这个方法来搜索字符串?
//Searches only ints
public void buscarCliente_Codigo(int cod) throws IOException{ /*cod is for the input
for eg. a textfield input which im using*/
try{
RandomAccessFile f = new RandomAccessFile("Clientes.txt","rw"); //.txt File name
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
nombre = leerNombre(f); //Reads String
numTelefono = leerNumTelefono(f);
direccion = leerDireccion(f);
seguro = leerSeguro(f);
nacionalidad = leerNacionalidad(f);
cedula = leerCedula(f);
if(cod==codigo){
iCodigoBusqueda = codigo;
encontrado=true;
registroExistente = true;
break;
}else{
iCodigoBusqueda = 0; //Type int
registroExistente = false;
}
bytes +=1;//Changes
f.seek(bytes);
}
while(bytes<f.length());
f.close();
} catch (Exception e){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Data not found");
}
}
之后,我只编写了几个 .getText 代码,并且我有一个漂亮的搜索机制,它只适用于数字,但我真的想要一个搜索字符串的方法,所以我做了几个 tweeks:
**enter code here**
public void buscarCliente_Nombre(String nom) throws IOException{ //change to String
try{
RandomAccessFile f = new RandomAccessFile("Clientes.txt","rw");
boolean encontrado=false;
registroExistente = false ;
long bytes = 0;
do{
codigo = f.readInt();
nombre = leerNombre(f);
numTelefono = leerNumTelefono(f);
direccion = leerDireccion(f);
seguro = leerSeguro(f);
nacionalidad = leerNacionalidad(f);
cedula = leerCedula(f);
if(nom.equals(nombre)){
iNombreString = nombre;
encontrado=true;
registroExistente = true;
break;
}else{
iNombreString = ""; //String type
registroExistente = false;
}
bytes +=1;//cambios
f.seek(bytes);
}
while(bytes<f.length());
f.close();
} catch (Exception e){
registroExistente = false;
JOptionPane.showMessageDialog(null,"Data not found");
}
}
它不起作用,它给了我例外。
那么无论如何这段代码是否适用于Strings_?
谢谢