GARANTIR DESCONTO

Fórum Comparar 2 Strings #565782

09/04/2009

0

Amogos, bom dia... Estou fazendo uma aplicação onde eu quero fazer um pesquisa pelo nome, mas não consigo comparar 2 strings
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();
		}
}
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.
Pedro

Pedro

Responder

Posts

09/04/2009

Alexandre Moraes

tente .equals procure a documentação e estude a classe String Java... vai te ajudar muito
Responder

Gostei + 0

09/04/2009

Isaias 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!
Responder

Gostei + 0

09/04/2009

Pedro

vlw pessoal, vou tentar aki e ver se consigo
Responder

Gostei + 0

09/04/2009

Camilo Lopes

para strings e objetos usa equals...
Responder

Gostei + 0

09/04/2009

Camilo Lopes

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
Responder

Gostei + 0

09/04/2009

Camilo Lopes

Boa tarde, Pessoal, como eu faria para dizer que uma string é diferente de outra? Obrigado!
Responder

Gostei + 0

09/04/2009

Camilo Lopes

[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("!=");
}

Responder

Gostei + 0

09/04/2009

Camilo Lopes

[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!
Responder

Gostei + 0

18/11/2009

Camilo Lopes

Quando eu tento negar um String com um Vector nao da certo !
nomes <- vector de String
nomes2 <- String


         nomes2 = input.nextLine();
if (!(nomes2.equals(nomes.contains(nomes2) ) ) ) {
               nome.add(nomes2)
         }else  Sysout("Ja existe")



e ele consegue adicionar mesmo eu repetindo os nomes
Responder

Gostei + 0

18/11/2009

Alison Souza

http://javafree.uol.com.br/artigo/6953/Cap-7-Objetos-e-conjuntos.html
Responder

Gostei + 0

18/11/2009

Ricardo Staroski

String nome = input.nextLine();
if (!nomes.contains(nome)) {
    nomes.add(nome);
} else {
    System.out.println("Ja existe");
}
Responder

Gostei + 0

19/03/2013

Jose Junior

Como fazer um método insertionSort que implemente uma comparação entre duas Strings e as ordene em ordem Crescente? Desde já muito obrigado.
Responder

Gostei + 0

19/03/2013

Marcelo Senaga

[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
Responder

Gostei + 0

19/03/2013

Jose Junior

Valeu Obrigado!!
Responder

Gostei + 0

15/04/2013

Jacy Silva

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??
Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar