Im trying to make a counter that tells how many times a name appears with array. I am using a scanner that read the names from a file and stores it an array. It then uses random class to pick a random name. I then stored all the names that is chosen into an array. How do i make a counter for each name.
for example:
john
david
carl
john
then it prints out:
john(2)
david(1)
carl(1)
heres my code:
//The goal of this program is to generate random Strings
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
public class RandomName
{
public static void main(String[] args) throws IOException
{
Scanner key = new Scanner(System.in);
Random randomNumbers = new Random();
int n = 0;
String[] names= new String[50];
int index = 0;
int index2 =0;
int count =0;
int count2=0;
int count3=0;
String [] names2 = new String[5];
int [] counter = new int[20];
//Opens the file from user
//
File file = new File("name.txt");
Scanner read = new Scanner(file);
while(read.hasNext())
{
names[index] = read.nextLine();
index++;
n++;
}
//prints out the number of people in the file
//Store into an array
//prints out a random name from the file
System.out.println("Number of people: " + n );
int x = randomNumbers.nextInt(n);
System.out.println(names[x]);
names2[index2] = names[x];
count++;
count2++;
index2++;
System.out.print("Command? ");
String command = key.nextLine();
//contine to loop the program
//Write to the file
//
while(!command.equals("exit"))
{
if(command.equals("n"))
{
x = randomNumbers.nextInt(n);
System.out.println(names[x]);
names2[index2]=names[x];
count2++;
index2++;
System.out.print("Command? ");
command = key.nextLine();
count++;
}
else if(command.equals("help"))
{
System.out.println(" n Next random name");
System.out.println(" exit Exit the program");
System.out.print(" list List all the unique names that have been");
System.out.println(" called as well the number of times");
System.out.println(" help Display this message");
System.out.print("Command? ");
command = key.nextLine();
}
else if(command.equals("list"))
{
command = key.nextLine();
System.out.print("Command? ");
System.out.println(count);
}
}
read.close();
//Exit the program if user enter exit
//
if(command.equals("exit"))
{
System.out.println("The program has generated " + count + " name(s) with " + "" + "repetition(s)");
System.exit(0);
}
}
}
thank you