Autor Tema: duda Java uso de Scanner dentro de loops y arrays  (Leído 4249 veces)

josephb401

  • Visitante
duda Java uso de Scanner dentro de loops y arrays
« en: 20 de Enero 2015, 04:28 »
Saludos! En estos momentos me encuentro haciendo un programa usando arrays y loops pero cuando intento usar el Scanner en el loop varias veses en el loop para obtener informacion del usuario varias veces no funciona, solamente el usuario puede introducir informacion una sola vez. Aquí debajo les dejo el codigo les agradeceria mucho si me pudieran ayudar gracias!!!

Código: [Seleccionar]
import java.util.Scanner;

public class practica
{
public static int size = 5;

public static void main(String[] args)
{

Scanner input = new Scanner(System.in);

int num = 5, get = 0;

String info[] = new String[size];
int test1[] = new int[size];
int test2[] = new int[size];
int test3[] = new int[size];
int test4[] = new int[size];


for(int count = 0; count <= 4;)
{
if(count < 4)
{

System.out.print("Please enter the name of the reminder " +num+ " students: ");
info[count] = input.nextLine();
System.out.println();
System.out.print("Please enter " +info[count]+ "'s first test score: ");
test1[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s secound test score: ");
test2[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s third test score: ");
test3[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s five test score: ");
test4[count] = input.nextInt();

System.out.println();
}

else
{

System.out.print("Please enter the name of the last student: ");
info[count] = input.nextLine();
System.out.print("Please enter " +info[count]+ "'s first test: ");
test1[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s secound test: ");
test2[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s third test: ");
test3[count] = input.nextInt();
System.out.print("Please enter " +info[count]+ "'s five test: ");
test4[count] = input.nextInt();

}

num = num - 1;
count = count + 1;
}

do
{
System.out.println();
System.out.println("The student's name are " + info[0] + "," + info[1] + "," + info[2] + "," + info[3] + "," + info[4]);
System.out.println();

System.out.print("Please type the name of the Student you want to look up: ");
String name = input.nextLine();

if(name.equals(info[0]))
{
System.out.print(info[0] + "'s grade is " + test1[0] + ", " + test2[0] + ", " + test3[0] + ", " + test4[0]);
System.out.print("The average grade for " + info[0] + " is " + (test1[0] + test2[0] + test3[0] + test4[0]) / 4);
}

else if(name.equals(info[1]))
{
System.out.print(info[1] + "'s grade is " + test1[1] + ", " + test2[1] + ", " + test3[1] + ", " + test4[1]);
System.out.print("The average grade for " + info[1] + " is " + (test1[1] + test2[1] + test3[1] + test4[1]) / 4);
}

else if(name.equals(info[2]))
{
System.out.print(info[2] + "'s grade is " + test1[2] + ", " + test2[2] + ", " + test3[2] + ", " + test4[2]);
System.out.print("The average grade for " + info[2] + " is " + (test1[2] + test2[2] + test3[2] + test4[2]) / 4);
}

else if(name.equals(info[3]))
{
System.out.print(info[3] + "'s grade is " + test1[3] + ", " + test2[3] + ", " + test3[3] + ", " + test4[3]);
System.out.print("The average grade for " + info[3] + " is " + (test1[3] + test2[3] + test3[3] + test4[3]) / 4);
}

else if(name.equals(info[4]))
{
System.out.print(info[4] + "'s grade is " + test1[4] + ", " + test2[4] + ", " + test3[4] + ", " + test4[4]);
System.out.print("The average grade for " + info[4] + " is " + (test1[4] + test2[4] + test3[4] + test4[4]) / 4);
}

else
{
System.out.println("The name you student name you enter is not valid.");
System.out.println();
}

System.out.print("Enter any number to find another student otherwise type -1 to end the program: ");
get = input.nextInt();

}while(get != -1);

}
}
« Última modificación: 20 de Enero 2015, 08:09 por Alex Rodríguez »

toni_apr

  • Avanzado
  • ****
  • Mensajes: 497
  • Curiosidad, es uno de los pilares del Conocimiento
    • Ver Perfil
Re:duda Java uso de Scanner dentro de loops y arrays
« Respuesta #1 en: 21 de Enero 2015, 18:19 »
Hola josephb401

Te envio una modificación de tu código con mis comentarios.

Código: [Seleccionar]
import java.util.Scanner;

public class practica
{
    public static int size = 5;

    public static void main(String[] args)
    {
        // modificacion
        Scanner input;
        // modificacion
        int num = 5;  // get = 0;

        String info[] = new String[size];
        int test1[] = new int[size];
        int test2[] = new int[size];
        int test3[] = new int[size];
        int test4[] = new int[size];
        // modificacion
        for(int count = 0; count <= 4;)

        {
            if(count < 4)
            {

                System.out.print("Please enter the name of the reminder " +num+ " students: ");
                // modificacion         
                input = new Scanner(System.in);

                info[count] = input.nextLine();
                System.out.println();
                System.out.print("Please enter " +info[count]+ "'s first test score: ");
                test1[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s secound test score: ");
                test2[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s third test score: ");
                test3[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s five test score: ");
                test4[count] = input.nextInt();

            }

            else
            {

                System.out.print("Please enter the name of the last student: ");
                // modificacion
                input = new Scanner(System.in);

                info[count] = input.nextLine();
                System.out.print("Please enter " +info[count]+ "'s first test: ");
                test1[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s secound test: ");
                test2[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s third test: ");
                test3[count] = input.nextInt();
                System.out.print("Please enter " +info[count]+ "'s five test: ");
                test4[count] = input.nextInt();

            }

            num = num - 1;
            count = count + 1;
        }
        String name;
        do
        {
            System.out.println();
            System.out.println("The student's name are " + info[0] + "," + info[1] + "," + info[2] + "," + info[3] + "," + info[4]);
            System.out.println();

            System.out.println("Please type the name of the Student you want to look up: ");
            // modificacion
            System.out.println("Por favor escriba el nombre del estudiante que desea buscar, o la palabra FIN para salir:");
            // modificacion
            input = new Scanner(System.in);
            name = input.nextLine();
            if(name.equals(info[0]))
            {
                System.out.println(info[0] + "'s grade is " + test1[0] + ", " + test2[0] + ", " + test3[0] + ", " + test4[0]);
                System.out.println("The average grade for " + info[0] + " is " + (test1[0] + test2[0] + test3[0] + test4[0]) / 4);
            }

            else if(name.equals(info[1]))
            {
                System.out.println(info[1] + "'s grade is " + test1[1] + ", " + test2[1] + ", " + test3[1] + ", " + test4[1]);
                System.out.println("The average grade for " + info[1] + " is " + (test1[1] + test2[1] + test3[1] + test4[1]) / 4);
            }

            else if(name.equals(info[2]))
            {
                System.out.println(info[2] + "'s grade is " + test1[2] + ", " + test2[2] + ", " + test3[2] + ", " + test4[2]);
                System.out.println("The average grade for " + info[2] + " is " + (test1[2] + test2[2] + test3[2] + test4[2]) / 4);
            }

            else if(name.equals(info[3]))
            {
                System.out.println(info[3] + "'s grade is " + test1[3] + ", " + test2[3] + ", " + test3[3] + ", " + test4[3]);
                System.out.println("The average grade for " + info[3] + " is " + (test1[3] + test2[3] + test3[3] + test4[3]) / 4);
            }

            else if(name.equals(info[4]))
            {
                System.out.println(info[4] + "'s grade is " + test1[4] + ", " + test2[4] + ", " + test3[4] + ", " + test4[4]);
                System.out.println("The average grade for " + info[4] + " is " + (test1[4] + test2[4] + test3[4] + test4[4]) / 4);
            }

            else
            {
                System.out.println("The name you student name you enter is not valid.");
                System.out.println();
            }

            //             System.out.println("Enter any number to find another student otherwise type -1 to end the program: ");
            //             get = input.nextInt();
        // modificacion
        }while(!name.equals("FIN"));

    }
}

Línea 5
La variable size se puede declarar dentro del main. No parece ser un atributo de clase que se puede consultar o modificar.

Línea 10
Declarar la variable input sin inicializar (para que no espere entrada por teclado)

Línea 12
Variable get anulada, no se utilizará.

Línea 20
El contador del for se cambia dentro del for más adelante. No es usual, no se que ventajas tiene.

Línea 28
Inicializar la variable input para leer una entrada de teclado.

Línea 48
Idem que la línea 28

Línea 66
Declarar la variable name, se inicializa dentro del siguiente while

Línea 75
En este mensaje se informa al usuario de como salir del bucle while

Línea 77
Idem que la línea 28 y 48

Líneas 115 y 116
 Eliminadas, no se usan.

Línea 118
Condición del while para salir del bucle.

He intentado respetar al máximo tu código.
Por eso verás el mensaje de: Nombre de estudiante inválido cuando tecleas FIN como nombre de usuario.

Nota: La variable input se inicializa en cada bucle porque sino, no lee del teclado para el método nextLine (cosa que no ocurre con nextInt. No sé cual es la razón técnica, pero es así)

Saludos

josephb401

  • Visitante
Re:duda Java uso de Scanner dentro de loops y arrays
« Respuesta #2 en: 22 de Enero 2015, 00:03 »
muchisimas gracias me ayudaste en gran manera

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".