Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

297
Vistas
Escáner que solicita entrada dos veces y solo almacena la segunda entrada en una matriz

Estoy haciendo una declaración de cambio de caso en Java con condiciones. Si una persona agrega un proyecto al sistema de entre 2 y 12 meses de duración, se agregará a una matriz. Si la duración del proyecto es inferior a 2 o superior a 12, el sistema debería solicitarles que vuelvan a introducir un número válido. Por alguna razón, mi sistema les solicita que ingresen el número dos veces y solo almacenan la segunda entrada en la matriz: Imagen de la terminal que solicita dos veces e Imagen de la segunda entrada que solo se almacena en la matriz .

Estoy pensando que es porque tengo 'myMonths[index] = sc.nextInt();' declaró dos veces, pero no sé cómo puedo evitarlo sin que esté allí dos veces. ¿Alguien puede averiguar por qué sucede esto y cómo podría corregirlo? Cualquier ayuda sería muy apreciada. Aquí está mi código:

 //Menu loop int myMonths[] = new int[5]; int index = 0; 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++){ myMonths[index] = sc.nextInt(); //if months is lesser than 2/greater than 12 if((myMonths[index] < 2) || (myMonths[index] > 12)){ System.out.println("Enter a number between 2 and 12 months");} //if months is between 2 and 12 add it to the array for(int x=0; x<1; x++){ //read the elements of the array myMonths[index++]=sc.nextInt();}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

 for(int i=0; i<1; i++){ myMonths[index] = sc.nextInt();// put this in a variable int a = sc.nextInt(); //if months is lesser than 2/greater than 12 if((myMonths[index] < 2) || (myMonths[index] > 12)){ System.out.println("Enter a number between 2 and 12 months");}//here your are just checking if provided value is between 2 or 12 but there is no logical branching ie an else //if months is between 2 and 12 add it to the array for(int x=0; x<1; x++){ //read the elements of the array myMonths[index++]=sc.nextInt();}//since there is no else this block will always execute

Puedes probar algo como esto en tu código.

 for(int i=0; i<1; i++){ int ip = sc.nextInt(); //if months is lesser than 2/greater than 12 if((ip < 2) || ip > 12){ System.out.println("Enter a number between 2 and 12 months"); //here ask for ip again ip = sc.nextInt();//if you wanna continue doing this until you get a valid ip use an infinite while loop with a flag for break --- see below }else{ //code for saving ip to array whatever logic you might need }

Un ejemplo de cómo podría usar while loop para solicitar ip hasta que sea válido

 int ip; boolean valid = false; while(!valid){ ip = sc.nextInt(); if(condition){ //if codition is satisfied valid = true; } //else sysout("invalid ip"); loop will continue until you get a valid ip }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda