SoloCodigo

Programación General => Java => JSP/Servlets => Mensaje iniciado por: pipelin85 en Martes 14 de Abril de 2009, 05:25

Título: llenar arreglo while y scanner
Publicado por: pipelin85 en Martes 14 de Abril de 2009, 05:25
hola quiero llenar un arreglo con while utilizando scanner para leer los datos pero no me funciona podrian ayudarme? el siguiente es el codigo que no funciona. Y despues quiero imprimirlo.

import java.util.Scanner;


public class usandoscanner {


public static void main(String[] args) {
int [] arr = new int [50];
int i=0;
Scanner sc = new Scanner(System.in);

while (sc.nextInt()!=0){
arr=sc.nextInt();
i++;
}

for (int j=0; j<=i;j++)
System.out.println(arr[j]);

}

}
Título: Re: llenar arreglo while y scanner
Publicado por: arielb en Martes 14 de Abril de 2009, 23:48
Hola, resulta que en el while estás poniendo a leer nuevamente con el sc.nextInt y son dos veces y se queda esperando puedes usar una variable tipo boolean

Código: Java
  1. public static void main(String[] args) {
  2.    
  3.     int [] arr = new int [50];
  4.     int i=0;
  5.     boolean guia = true;
  6.     Scanner sc = new Scanner(System.in);
  7.    
  8.     System.out.print("Introduzca un valor ");
  9.    
  10.     while (guia){
  11.        
  12.         arr[i]=sc.nextInt();
  13.        
  14.         if ( arr[i] ==  0)
  15.             guia = false;
  16.        
  17.         i++;
  18.        
  19.         System.out.print("Introduzca un valor ");
  20.     }
  21.    
  22.     for (int j=0; j<=i;j++)
  23.         System.out.println(arr[j]);
  24.  
  25. }
  26.