Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Buscar una matriz con la entrada del usuario e imprimir todos los elementos que tienen este valor

Estoy tratando de buscar un valor determinado en una matriz y mostrar todos los elementos que contienen este valor en Java. Por ejemplo, el usuario selecciona el número 5, hay 3 proyectos almacenados en la matriz con este valor, por lo que se imprimirán los 3. Mi código se está compilando bien, pero cuando lo ejecuto, salta a la declaración else, incluso si estoy ingresando un número que está en la matriz. Cualquier ayuda sería increíble. Aquí está mi código:

 case 3: //display all elements with the same state //get number user wishes to search for boolean found = false; Scanner input = new Scanner(System.in); System.out.print("Please enter the number you wish to search for"); //read user input num = input.nextInt(); //traverse array int k = 0; for(k=0; k < myMonths.length; k++){ if(myMonths[index] == num){ found = true; break;} if(found){System.out.println(k);} else{System.out.println("not found");} } break;

Aquí está la matriz:

 //Menu loop int myMonths[] = new int[5]; int index = 0; int num; while(choice !=6){ switch (choice){ case 1: //int n = number of projects int n = 1; Scanner sc = new Scanner(System.in); System.out.println("How many months was your project?"); for(int i=0; i<1; i++){ int a = sc.nextInt(); //if months is lesser than 2/greater than 12 if((a < 2) || (a > 12)){ System.out.println("Please enter an amount between 2 and 12 months");} //if months is between 2 and 12 add it to the array else{myMonths[index++] = a;} } break;
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Primero, deberías usar k en lugar de index . En segundo lugar, no debe imprimir "no encontrado" (o probarlo) en cada iteración. Debe limitar el alcance variable tanto como sea práctico. Y también menciona que desea encontrar todos los índices coincidentes para que no termine el ciclo prematuramente; Creo que querías algo como

 //assume the value isn't present. boolean found = false; //read user input int num = input.nextInt(); //traverse array for(int k = 0; k < myMonths.length; k++) { if (myMonths[k] == num){ found = true; System.out.println(k); // don't break or the loop ends early. } } //this test can only be done after you iterate **all** values. if (!found) { System.out.println("not found"); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!