vendredi 3 novembre 2017

Is something wrong with this code?

So what I'm trying to do is create a program that takes input (names) from the user and prints them out. No name should be the same (so like I don't want to see John Smith twice or anything; something should pop out in that case like 'That name has already been used, try again'), and there can only be 32 students.

What I've tried to do is use a while loop for how many students there can be, and then as people input their names, put each name into an array. I tried to compare each new name to the ones in the array using a for loop. Then, using an if-else statement, the program would print the name or tell the user to put in a different name.

However, it takes a really long time to compile. Getting the first and last names is no problem; however, after that, the code runs for a really long time. It hasn't even finished by now (around 5 minutes later). On Browxy, the code just killed. Is there something wrong in the code that I'm not aware of?

Here is the code:

import java.util.Scanner;

public class Students { private static Scanner input = new Scanner (System.in);

public static void main (String [] args)
{
    int names = 1;
    while (names <=32)
    {
        names=names+1;

        String [] nameArray = new String [32];

        System.out.println ("Enter your first name.");
        String firstName=input.nextLine();

        System.out.println();

        System.out.println ("Now enter your last name.");
        String lastName=input.nextLine();

        String fullName=firstName + " " + lastName;

        for (int i=0 ; i<32 ; i++)
        {
            nameArray[i]=input.nextLine();
        }

        if (fullName.equals(nameArray))
        {
            System.out.println ("Are you sure you know your name? If yes, please type your real name. If not, please exit out of this program.");
        }
        else
        {
            System.out.println (fullName);
        }
    }
}

}

Aucun commentaire:

Enregistrer un commentaire