MARCOS GARCES
MARCOS GARCES

Reputation: 55

Is there any more elegant solution for this simple loop?

Hello I'm new to programming, I'm trying to solve a problem in which I'm given an array of 10 random numbers and I have to say whether the number is in the array.

If it is - then the program has to show the message "I found it!", and if it isn't - "That number is not in the array!"

I wrote this solution and I would like to know if there is a simpler and faster way to solve it (language Java)

input: one number and an array of numbers

int cont=0;

for(i=0; i<10;i++){
  if(numbers[i]==number){
    System.out.println("I found it");
    cont++;
    break;
  }
}
if(cont==0)
  System.out.println("That number is not in the array!");

Thank you for helping, sorry if it's really simple, but I'm a beginner.

Upvotes: 0

Views: 186

Answers (2)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11120

Using Streams everywhere, just because of they are streams, isn't a good idea and doesn't make code cleaner, nor does it always make it more readable or even more faster.

Your loop seems good and I don't think you can improve the performance here. The only thing I'd have changed is, that I'd have introduced the found flag, it's a bit less code.

boolean found=false;

for(i=0; i<10; i++) {
    if(numbers[i]==number) {
        System.out.println("I found it");
        found=true;
        break;
    }
}
if(!found)
    System.out.println("That number is not in the array!");

Upvotes: 0

Jay Ehsaniara
Jay Ehsaniara

Reputation: 1529

try like this (Java 8 and later versions):

boolean contains = IntStream.of(numbers).anyMatch(x -> x == number); 
if(contains)
   System.out.println("I found it");
else
   System.out.println("That number is not in the array!");

Upvotes: 1

Related Questions