Skip to content

issue-43-busca-linear#76

Open
cintiambelem wants to merge 1 commit intodevs-javagirl:mainfrom
cintiambelem:issue-43-busca-linear
Open

issue-43-busca-linear#76
cintiambelem wants to merge 1 commit intodevs-javagirl:mainfrom
cintiambelem:issue-43-busca-linear

Conversation

@cintiambelem
Copy link

criacao da classe de busca linear
criacao do readme

criacao da classe de busca linear
criacao do readme

var sc = new Scanner(System.in);

int[] vetor = new int[5];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aqui você pode iniciar o array com int[] vetor = new int[]{5, 1, 2, 3, 4}; para maior legibilidade

vetor[4] = 4;

boolean isNumero = false;
int numeroLocalizado = 0;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vc pode remover essa variável pois consegue printar no final somente com o numeroBuscado

for (int i : vetor) {
if (numeroBuscado == i) {
isNumero = true;
numeroLocalizado = i;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vc pode remover a numeroLocalizado aqui

}
}
if (isNumero) {
System.out.println("valor encontrado: " + numeroLocalizado);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Substituir numeroLocalizado por numeroBuscado

numeroLocalizado = i;
}
}
if (isNumero) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se vc quiser substituir o for e utilizar lambda é possível usar a seguinte expressão:

Suggested change
if (isNumero) {
if (Arrays.stream(vetor).anyMatch(numero -> numero == numeroBuscado))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explicando cada parte:
Arrays.stream(vetor): vai passar em cada valor do vetor
.anyMatch(): retorna um boolean se a expressão atende o buscado
numero -> numero == numeroBuscado): numero é o nome que definimos para cada elemento do vetor, ele valida se cada número é igual ao numeroBuscado

System.out.println("insira o numero a ser buscado: ");
int numeroBuscado = sc.nextInt(); // criada uma variável pra armazenar o numero que será buscado pelo algoritmo

for (int i : vetor) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Para aumentar a legibilidade do for sugiro:

Suggested change
for (int i : vetor) {
for (int numero : vetor) {
if (numero == numeroBuscado) {
isNumeroEncontrado = true;
break;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants