Comparar 2 Strings
Amogos, bom dia...
Estou fazendo uma aplicação onde eu quero fazer um pesquisa pelo nome, mas não consigo comparar 2 strings
as informações vem de um arquivo de texto... neste if: if(campos[1] == pesquisa) ele não compara, fiz a mesma sequencia com o código, mas funciona.
Alguem sabe com me ajudar?
Att.
public void pesquisaNome(String caminho){
try {
FileReader f = new FileReader(caminho);
BufferedReader in = new BufferedReader(f);
String pesquisa = JOptionPane.showInputDialog("Digite o código do funcionário para pesquisa");
while ((linha = in.readLine()) != null) {
campos = linha.split("[;]");
if(campos[1] == pesquisa){
fun.codigo = Integer.parseInt(campos[0]);
fun.nome = campos[1];
fun.departamento = campos[2];
fun.salario = Double.parseDouble(campos[3]);
fun.rg = campos[4];
fun.dataEntrada = campos[5];
fun.exibir();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Pedro
Curtidas 0
Respostas
Alexandre Moraes
09/04/2009
tente .equals
procure a documentação e estude a classe String Java...
vai te ajudar muito
GOSTEI 0
Isaias Pfaffenseller
09/04/2009
Olá,
A sua condição fica assim:
if(campos[1].equals(pesquisa))
Se for diferente dai fica assim:
if(!(campos[1].equals(pesquisa)))
É isso ai xD
Abraço!
GOSTEI 0
Pedro
09/04/2009
vlw pessoal, vou tentar aki e ver se consigo
GOSTEI 0
Camilo Lopes
09/04/2009
para strings e objetos usa equals...
GOSTEI 0
Camilo Lopes
09/04/2009
um exemplo de aplicação
lembre se de importar o pacote java util
import java.util.*;
public void ordenaPessoa()
{
int i, f;
for(f=1;f<nElems;f++)
{
Pessoa temp = vetObjeto[f];
i=f;
while(i>0&&vetObjeto[i-1].getNome().compareTo(temp.getNome())>0)
{
vetObjeto[i]=vetObjeto[i-1];//move para direita
i--;
}
vetObjeto[i]=temp;
}
}
segue a descriçao do método compareTo da classe String
compareTo
public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
abraço espero ter ajudado
GOSTEI 0
Camilo Lopes
09/04/2009
Boa tarde,
Pessoal, como eu faria para dizer que uma string é diferente de outra?
Obrigado!
GOSTEI 0
Camilo Lopes
09/04/2009
[quote="victor_luiz"]Boa tarde,
Pessoal, como eu faria para dizer que uma string é diferente de outra?
Obrigado!
String teste1 = "texto1";
String teste2 = "texto2";
if(!teste1.equals(teste2)){
System.out.println("!=");
}
GOSTEI 0
Camilo Lopes
09/04/2009
[quote="victor_luiz"]Boa tarde,
Pessoal, como eu faria para dizer que uma string é diferente de outra?
Obrigado!
para testar se uma string não é igual a outra?
leu as mensagens anteriores?
[quote="I_Pfaffenseller"]Olá,
A sua condição fica assim:
if(campos[1].equals(pesquisa))
Se for diferente dai fica assim:
if(!(campos[1].equals(pesquisa)))
É isso ai xD
Abraço!
GOSTEI 0
Camilo Lopes
09/04/2009
Quando eu tento negar um String com um Vector nao da certo !
e ele consegue adicionar mesmo eu repetindo os nomes
nomes <- vector de String
nomes2 <- String
nomes2 = input.nextLine();
if (!(nomes2.equals(nomes.contains(nomes2) ) ) ) {
nome.add(nomes2)
}else Sysout("Ja existe")
GOSTEI 0
Alison Souza
09/04/2009
http://javafree.uol.com.br/artigo/6953/Cap-7-Objetos-e-conjuntos.html
GOSTEI 0
Ricardo Staroski
09/04/2009
String nome = input.nextLine();
if (!nomes.contains(nome)) {
nomes.add(nome);
} else {
System.out.println("Ja existe");
}
GOSTEI 0
Jose Junior
09/04/2009
Como fazer um método insertionSort que implemente uma comparação entre duas Strings e as ordene em ordem Crescente?
Desde já muito obrigado.
GOSTEI 0
Marcelo Senaga
09/04/2009
[quote="JBLiraJr"]Como fazer um método insertionSort que implemente uma comparação entre duas Strings e as ordene em ordem Crescente?
Desde já muito obrigado.
Ver:
http://www.java2s.com/Tutorial/Java/0140__Collections/SortingObjectsusinginsertionsort.htm
GOSTEI 0
Jose Junior
09/04/2009
Valeu Obrigado!!
GOSTEI 0
Jacy Silva
09/04/2009
System.out.println("Digite o Nome do Cliente");
nomeCli[j] = enter.nextLine();
for(int k=0;k<tam2;k++){
if(!nomeCli[k].equals(nome[k])){
System.out.println("Digite o Nome do Filme");
filme[i] = input.nextLine();
}
to tentando cm esse codigo comparar dois vetores de String, porem elas sao de classes diferentes... alguem pod me ajudar??
GOSTEI 0
Luis Bueno
09/04/2009
[quote="luazinhasg"]System.out.println("Digite o Nome do Cliente");
nomeCli[j] = enter.nextLine();
for(int k=0;k<tam2;k++){
if(!nomeCli[k].equals(nome[k])){
System.out.println("Digite o Nome do Filme");
filme[i] = input.nextLine();
}
to tentando cm esse codigo comparar dois vetores de String, porem elas sao de classes diferentes... alguem pod me ajudar??
Por favor, use sempre as tags [b]C O D E[/b] quando for postar um código.
Sobre sua dúvida, acredito que você tenha que instanciar a classe onde está o vetor [b]nome[k][/b]
ClasseExemplo classExem = new ClasseExemplo();
for(int k=0;k<tam2;k++){
if(!nomeCli[k].equals(classExemp.nome[k])){
System.out.println("Digite o Nome do Filme");
filme[i] = input.nextLine();
}
GOSTEI 0
Luis Bueno
09/04/2009
[quote="JStealth"][quote="luazinhasg"]System.out.println("Digite o Nome do Cliente");
nomeCli[j] = enter.nextLine();
for(int k=0;k<tam2;k++){
if(!nomeCli[k].equals(nome[k])){
System.out.println("Digite o Nome do Filme");
filme[i] = input.nextLine();
}
to tentando cm esse codigo comparar dois vetores de String, porem elas sao de classes diferentes... alguem pod me ajudar??
Por favor, use sempre as tags [b]C O D E[/b] quando for postar um código.
Sobre sua dúvida, acredito que você tenha que instanciar a classe onde está o vetor [b]nome[k][/b]
ClasseExemplo classExem = new ClasseExemplo();
for(int k=0;k<tam2;k++){
if(!nomeCli[k].equals(classExemp.nome[k])){
System.out.println("Digite o Nome do Filme");
filme[i] = input.nextLine();
}
GOSTEI 0