0

I've created a Java program, and I want to display statistics. When the user input 1, it is single. And when a user input 2, it is a couple. When a user input 3, it is a family of 3.

Heres the example:

Scanner sc = new Scanner(System.in);

System.out.print("Enter group #1: ");
int g1 = sc.nextInt();
sc.nextLine();

System.out.print("Enter group #2: ");
int g2 = sc.nextInt();
sc.nextLine();

System.out.print("Enter group #3: ");
int g3 = sc.nextInt();
sc.nextLine();

System.out.print("Enter group #4: ");
int g4 = sc.nextInt();
sc.nextLine();

int[] numbers = {g1,g2,g3,g4};
int[] count = new int[] { 0, 0, 0};

String[] category = new String[]{"Single", "Couple","Family of 3"};
//String[][] category = new String[][] {{"Single"}, {"Couple"}, {"Family of 3"}};
String a = Arrays.toString(category).replaceAll("[\\[\\]]", "");
for (int i = 0; i < numbers.length; i++) {
    count[numbers[i] - 1]++;
}

System.out.println("");
System.out.println("Statistic: ");

for (int i=2; i <count.length; i++)
{
    System.out.println(a + " : " + count[i]);
}

But the display is so weird. Can help?

Results:

run:
Enter group #1: 1
Enter group #2: 1
Enter group #3: 1
Enter group #4: 1

Statistic: 
Single, Couple, Family of 3 : 4
Single, Couple, Family of 3 : 0
Single, Couple, Family of 3 : 0
BUILD SUCCESSFUL (total time: 4 seconds)

Correct results should be:

run:
Enter group #1: 1
Enter group #2: 1
Enter group #3: 1
Enter group #4: 1

Statistic: 
Single : 4
Couple: 0
Family of 3 : 0
1
  • You are not storing count properly..... Commented Jul 21, 2016 at 5:38

1 Answer 1

3

Instead of

for (int i=2; i <count.length; i++)
{
    System.out.println(a + " : " + count[i]);
}

should be

for (int i=0; i <count.length; i++)
{
    System.out.println(category[i] + " : " + count[i]);
}

and get rid of variable a.

Sign up to request clarification or add additional context in comments.

1 Comment

@Hakim Lewis - Could you accept this answer since it worked for you. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.