How to identify if a number has been entered in the vector

Asked

Viewed 408 times

3

Write a program that asks the user to enter 6 numbers of a lottery ticket in a vector and later check if there is the number 25 in this sequence of numbers passed by the user.

I have a question, I do not know how to identify if there is the number 25, if it was typed by the user.

Follow the command I made

public class Ex04 {

    public static void main (String[] args){

        int [] num = new int [6];
        for(int i=0;i<6;i++) {
            num[i] = Integer.parseInt(JOptionPane.showInputDialog("Insira o número do bilhete: "));  
        }    
        for (Integer integer : num) {
            System.out.print(integer + ", ");
        }                
    }
}

2 answers

2

The first thing you should do is create the variable, which you you wish to find, in this way:

//Número procurado: 
int numeroProcurado = 25;

Second, create the booelana variable that you will receive true or false, true if the number is found, false, case contrary:

//Uma flag para verificar se existe:
        boolean vinteCincoExiste = false;

        for (Integer numero : num) {

            if (numero == numeroProcurado) {
                vinteCincoExiste = true;
            }

        }

And finally, take the test to see if it really exists or no, in this way:

//Se a variável vinteCincoExiste for igual a true, então, existe.
 if (vinteCincoExiste) {
            System.out.println("o número " + numeroProcurado + " existe.");
        }
else{ //Caso contrário, não existe.
 System.out.println("o número " + numeroProcurado + " não existe.");
}

Test not found: Entries: 2,6,4,8,9,10
Output: number 25 does not exist.

Test successfully: Entries: 2,6,25,8,9,10
Output: number 25 exists.

Demo:

https://repl.it/@TaffarelXavier/SlowOptimisticStack

0

You can use an arrayList, because it has a method to search for values`

import java.util.ArrayList;

/**
 * FindNumber
 */
public class FindNumber {

    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<>();

        System.out.println(array.contains(25));
    }
}`

Browser other questions tagged

You are not signed in. Login or sign up in order to post.