Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
how do I pair the student array with the grade array? When I find the highest grade the corresponding student should also show, and same with the lowest graded student. I cant figure out how to make this program perform as such with two separate arrays.
import java.util.Scanner;
public class Asm7 {
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
System.out.println("How many students do you have?: ");
int AMOUNT = 0;
AMOUNT = Scan.nextInt();
String[] STUDENT = new String [AMOUNT];
int COUNTER = 0;
int GRADE [] = new int [AMOUNT];
if (AMOUNT <= 0) {
System.out.println("Invalid student amount");
}
else {
for(int i = 0; i < AMOUNT; i++){
System.out.println("Enter student's first name: " + (i+1));
STUDENT[i] = Scan.next();
System.out.println("Enter student's grade in order added: ");
GRADE[i] = Scan.nextInt();
}
for(int i = 0; i < AMOUNT; i++){
System.out.println(STUDENT[i] + " received the final grade of " + GRADE[i]);}
System.out.println();
int [] Results = MinMax(GRADE);
System.out.println("The highest grade in the class was " + Results[1]);
System.out.println("The lowest grade in the class was "+ Results[0]);
}}
public static int[] MinMax(int[] value) {
int[] Result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : value) {
Result[0] = i < Result[0] ? i : Result[0];
Result[1] = i > Result[1] ? i : Result[1];
}
return Result;
}
}
Your while loop validation for number of students is a little late. You want to do this before you declare and initialize your arrays. However, the fact that the while loop was actually used in an attempt towards some form of validation is a really good sign. It's more than most new programmers tend to do. All input should be validated and provide a User the opportunity to supply a correct solution. This can only lead to a smoother, trouble free application and a much better experience for the User. Take a look at this while loop which is in your code:
while (amount < 0) {
System.out.println("Invalid student amount");
}
What is going to happen if the User supplies -1 (this is a valid integer value as is +1)? That's right...your application will end up in an infinite loop spitting out Invalid student amount to the Console Window. Your validation scheme should encompass the entire prompt and then the means to exit it should be more logically defined. With a while loop the best exit is done through its conditional statement, if the condition is false then exit the loop, for example:
Scanner scan = new Scanner(System.in);
// Number Of Students...
String inputString = "";
while (inputString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
inputString = scan.nextLine().trim();
/* Is the supplied Number Of Students valid and within
range (1 to 50 inclusive)? */
if (!inputString.matches("\\d+") || Integer.valueOf(inputString) < 1
|| Integer.valueOf(inputString) > 50) {
// No...
System.err.println("Invalid entry (" + inputString + ") for Student "
+ "amount! Try again...");
inputString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(inputString);
String[] student = new String[amount];
int grade[] = new int[amount];
Right away you will notice some obvious changes here. The entire How many students do you have? prompt is contained within a while loop block. If the User does not supply a valid response then that User is asked to try again. The student and grade parallel arrays are declared and initialized only after a valid response for the number of students is provided.
You will also notice that the while loop condition doesn't rely on a integer value but instead it relies on actual string content (regardless of what it is) instead. If the variable is empty ("") then loop again. This is because the Scanner#nextLine() method is used to collect the Users input instead of the Scanner#nextInt() method. The prompt still expects an integer value to be supplied, just a string representation of an integer value and this is validated using the String#matches() method along with a small Regular Expression (regex).
I personally prefer to use the Scanner#nextLine() method for a number of reasons. I personally find it more flexible especially if you want to accept both Alpha and Numerical input from a single prompt. If the prompt above stated:
How many students do you have? (q to quit)
you would just need to add another if statement above the numerical validation code to see if 'q' or 'Q' was supplied, for example:
// If either q or Q is entered then quit application.
if (amountString.matches("[qQ]")) {
System.out.println("Bye-Bye");
System.exit(0);
}
Also, with a good expression passed to the matches() method, there is no need to trap exceptions in order to carry out validations, not that there is anything wrong with this, many people do it, I especially don't however when I have no need to do so.
Side Note: I'm going to state the obvious here and I'm sure you've heard it a hundred times before and you're sick of hearing it but I'm going to tell you again:
Your class methods should start with a lowercase letter (see Java Naming
Conventions).
I know you don't hear the compiler complaining but it does make it a
little more difficult (at times) to read the code. Everyone that reads
your code will appreciate you for it.
Because the student and grade arrays are parallel arrays you would want the minGrade() and maxGrade() methods to return a specific array index value to either the lowest or highest grade so that a referential relationship can be made toward the student that contains that specific grade determined. So, this would be far more useful:
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
With everything in play your code might look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Number Of Students...
String amountString = "";
while (amountString.isEmpty()) {
System.out.print("How many students do you have?: --> ");
amountString = scan.nextLine().trim();
// Is the supplied Number Of Students valid and within
// range (1 to 50 inclusive)?
if (!amountString.matches("\\d+") || Integer.valueOf(amountString) < 1
|| Integer.valueOf(amountString) > 50) {
// No...
System.err.println("Invalid entry (" + amountString + ") for Student "
+ "amount! Try again...");
amountString = ""; // Empty inputString so we loop again.
System.out.println();
}
}
// Valid amount provided.
int amount = Integer.valueOf(amountString);
// Declare and initialize parallel arrays
String[] student = new String[amount];
int grade[] = new int[amount];
// Student Names and Grade...
for (int i = 0; i < amount; i++) {
// Student Name...
String name = "";
while (name.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " name: --> ");
name = scan.nextLine().trim();
/* Is the name valid (contains upper or lower case letters from
A-Z and a single whitespaces separating first and last name?
Whitespace and last name is optional. */
if (!name.matches("(?i)([a-z]+)(\\s{1})?([a-z]+)?")) {
// No..
System.err.println("Invalid Student #" + (i + 1) + " name ("
+ name + ")! Try Again...");
System.out.println();
name = ""; // Empty name so we loop again.
}
}
// Valid Student name provided...
student[i] = name;
// Student Grade...
String gradeString = "";
while (gradeString.isEmpty()) {
System.out.print("Enter student #" + (i + 1) + " grade: --> ");
gradeString = scan.nextLine().trim();
// Is the supplied grade valid and within range (0 to 100 inclusive)?
if (!gradeString.matches("\\d+")
|| Integer.valueOf(gradeString) < 0
|| Integer.valueOf(gradeString) > 100) {
// No...
System.err.println("Invalid entry (" + gradeString + ") for "
+ "Student #" + (i + 1) + " grade! Try again...");
gradeString = "";
System.out.println();
}
}
// Valid Student grade provided...
grade[i] = Integer.valueOf(gradeString);
}
// Display everyone's grade
System.out.println();
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
System.out.println();
//Display who is highest and lowest...
int index = maxGrade(grade, amount);
System.out.println("The highest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
index = minGrade(grade, amount);
System.out.println("The lowest grade in the class was by '" + student[index]
+ "' with a grade of: " + grade[index]);
}
public static int minGrade(int[] arr, int size) {
// Initialize min to have the highest possible value.
int min = Integer.MAX_VALUE;
int returnableIndex = -1;
// loop to find lowest grade in array
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
public static int maxGrade(int[] arr, int size) {
int max = Integer.MIN_VALUE;
int returnableIndex = -1;
// loop to find highest grade in array
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
returnableIndex = i;
}
}
return returnableIndex;
}
If the data are not sorted, it would be better to find both min and max grades in the same loop, after printing the students and their grades.
Then no loop is needed to print min and max grades:
for (int i = 0; i < amount; i++) {
System.out.println(student[i] + " received the final grade of " + grade[i]);
}
int min = grade[0];
int max = grade[0];
for (int i = 1; i < amount; i++) {
if (grade[i] < min) {
min = grade[i];
} else if (grade[i] > max) {
max = grade[i];
}
}
System.out.println("The highest grade in the class was " + max);
System.out.println("The lowest grade in the class was " + min);
If the index of min/max is sought, it would be possible to print the name of the students who get the min and max grades.
public static void main(String[] args) {
int[] grades = new int[]{50, 51, 52, 50, 60, 22, 53, 70, 60, 94, 56, 41};
int[] result = getMinMax(grades);
System.out.println("Min: " + result[0] + ", Max: " + result[1]);
}
public static int[] getMinMax(int[] values) {
int[] result = new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE};
for (int i : values) {
result[0] = i < result[0] ? i : result[0];
result[1] = i > result[1] ? i : result[1];
}
return result;
}
You'll need to handle the case of int[] values being null or empty. You can decide that (Throw an exception, return null... or whatever)
Related
Need to get the index of the largest value in teamScores[] and print the associated string with the matching index from teamNames[]. This is really starting to get on my nerves. I had been able to successfully get the right value for the scores printed but it kept printing the wrong team. When I was trying to troubleshoot I was getting the right team but the wrong score. I am absolutely lost and have no other ideas. Anybody offer some advice? I have to use two separate arrays so I cannot just reduce it to one array. I also have to use a for loop to retrieve the values, so I can't do like I did with the lowScore.
public class SmithJustin_Asgn6 {
public static int highScore(int[] teamScores, int highIndex) {
int max = teamScores[0];
for(int i = 0; i < teamScores.length; i++) {
if(max < teamScores[i]) {
max = teamScores[i];
highIndex = i;
}
}return highIndex;
}
public static int lowScore(int[] teamScores) {
Arrays.sort(teamScores);
int low = teamScores[0];
return low;
}
public static void main(String[] args) {
int highIndex = 0;
Scanner userInput=new Scanner(System.in);
Scanner scoreInput=new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams=scoreInput.nextInt();
int [] teamScores= new int[teams];
String [] teamNames= new String[teams];
for(int i = 0; i < teams; i++) {
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
String teamName=userInput.nextLine();
teamNames[i]=teamName;
System.out.print("Enter Team's score (400-1000): ");
int teamScore=scoreInput.nextInt();
teamScores[i]=teamScore;
System.out.println();
}
highScore(teamScores, highIndex);
lowScore(teamScores);
System.out.println();
System.out.println("The high score is "+ teamScores[highScore(teamScores, highIndex)] +" by team " + teamNames[highScore(teamScores, highIndex)] + " and the low score is "+ lowScore(teamScores) +".");
userInput.close();
scoreInput.close();
}
}
Been trying every way to slice it and I am completely stuck
You can create a class to store team name and its score. Then sort the array of class objects based on a comparator. Also, you don't need to use two Scanner objects.
class Team
{
public int score;
public String name;
}
class SmithJustin_Asgn6 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the number of teams would you like to enter data for: ");
int teams = userInput.nextInt();
Team[] teamArray = new Team[teams];
for(int i = 0; i < teams; i++) {
teamArray[i] = new Team();
userInput.nextLine();
System.out.println("\nTeam "+ (i) +":");
System.out.println();
System.out.print("Enter Team's name: ");
teamArray[i].name = userInput.nextLine();
System.out.print("Enter Team's score (400-1000): ");
teamArray[i].score = userInput.nextInt();
System.out.println();
}
userInput.close();
Arrays.sort(teamArray, new Comparator<Team>() {
#Override
public int compare(Team o1, Team o2) {
return Integer.compare(o1.score, o2.score);
}
});
System.out.println();
System.out.println("The high score is "+ teamArray[teams - 1].score +" by team " + teamArray[teams - 1].name + " and the low score is "+ teamArray[0].score +".");
}
}
As mentioned by #Andrey your Arrays.sort is the main culprit. You need a logic to get the low score index the same as you have done for high score index.
public static int lowScore(int[] teamScores, int lowIndex) {
// Arrays.sort(teamScores);
int low = teamScores[0];
//logic to low score's index
return lowIndex;
}
After you have both the indexes, you can easily get values from respective arrays using them.
In your main method you are calling the same methods multiple times instead of that you can do
int lowIndex = 0;
highIndex = highScore(teamScores, highIndex);
lowIndex = lowScore(teamScores, lowIndex);
System.out.println();
System.out.println("The high score is " + teamScores[highIndex] + " by team " + teamNames[highIndex] + " and the low score is " + teamScores[lowIndex] + ".");
Start learning stream. Its easy and fun ;).
int h1 = IntStream.range(0, teamScores.length)
.reduce((i, j) -> teamScores[i] > teamScores[i] ? i : j)
.getAsInt();
int lowScore = Arrays.stream(teamScores).min().getAsInt();
System.out.println("The high score is " + teamScores[h1] + " by team " + teamNames[h1]+ " and the low score is " + lowScore + ".");
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
The output is taking count, name, income and then again income according to the number of counts and then shows outOfBound error for the count.
Here is the code -
public class Main { // Tax Calculator App
public static long calculateTax(long income1){
long tax = 0;
if (income1 >= 300000) {
tax = income1 * 20 / 100;
} else if (income1 >= 100000 && income1 < 300000) {
tax = income1 * 10 / 100;
} else if (income1 < 100000) {
tax = 0;
System.out.println("Tax Amount = 0 ");
}
return tax;
}
public static void main(String[] args) {
System.out.println("Tax Calculator App");
System.out.println("-----WELCOME-----");
Scanner sc = new Scanner(System.in);
System.out.println("Enter total person count: ");
int count = sc.nextInt();
sc.nextLine();
String[] pName = new String[count];
long[] pIncome = new long[count];
System.out.println("Enter the name: ");
for (int i = 0; i <= count; i++) {
pName[i] = sc.nextLine();
System.out.println("Enter the income: ");
}for (int i = 0; i <= count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName + "Tax: " + tax);
}
}
}
You are using a <= (less than or equals) operator in your for loop. This mean it will reach the person count and attempt to index the pName array by the count.
For example, say the count is 1, the array will be initialized with a size of 1, and it'll access pName[0], then pName[1], which is out of bounds, as the size is one.
You're also referencing the entire array in the printed result, you should be indexing to get the person's name.
Revised code for you is here: https://replit.com/#viomckinney/SOHelp#Main.java (Note: Indentation is not perfect as I just did a quick copy)
As #Violet McKinney and #Henry Twist were saying, your array is out of bounds because of the =.
Also, after updating the loop I checked your output is missing the name. The outcome was a java object.
On your last part of the code:
for (int i = 0; i < count; i++) {
pIncome[i] = sc.nextLong();
sc.nextLine();
long tax = 0;
System.out.println("Name: " + pName[i] + "Tax: " + tax);
}
pName => pName[i]
this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);
What I’m attempting to do is search “gradePsd” array find the highest grade and if there are two grades that are the same value print the name (s) of the students to console.
The problem I’m having is that this method is taking the first index value of the array and printing it because it IS the high value at the first pass and if the second value is larger than the first then it will also print and so on.
So my question is how can I get it to just print the student (s) with the high grade.
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
for (int i = 0; i < gradePsd.length; i++)
{
if (gradePsd[i] >= num)
{
num = gradePsd[i];
nameRtn = NamePsd[i];
}
System.out.print(nameRtn + ", ");
}
}
first find the highest number
then print the students with that number
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd)
{
String nameRtn = "";
int num = gradePsd[0];
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:");
//find the highest number
for (int i = 0; i < gradePsd.length; i++){
if (gradePsd[i] >= num){
num = gradePsd[i];
}
//print students with that number
for (int j = 0; j < NamePsd.length; j++){
if (gradePsd[j] == num)
{
nameRtn = NamePsd[j];
System.out.print(nameRtn + ", ");
}
}
one of possible 1000 solutions.
Initialize num with -1 and take the System.out out of the for loop. But you can only determine one student with your code. You need nameRtn to be a Collection if you want to store more than one name.
Something like this:
public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) {
Collection<String> namesRtn = new ArrayList<String>();
int num = -1;
for (int i = 0; i < gradePsd.length; i++) {
if (gradePsd[i] > num) {
num = gradePsd[i];
namesRtn.clear(); // clear name list as we have a new highest grade
namesRtn.add(NamePsd[i]); // store name in list
} else if (gradePsd[i] == num) {
namesRtn.add(NamePsd[i]); // if a second student has the same grade store it to the list
}
}
System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn);
}
Note: Just a practice problem, not for marks.
This is a practice problem given in a first year Java course:
Design and implement an application that reads an arbitrary number of integers, by the user, that are in the range 0 to 50 inclusive, and counts how many occurrences of each are entered. After all the input has been processed, print all of the values (with the number of occurrences) that were entered one or more times.
In addition, write a method that returns no value which would compute the average of the occurrences of all numbers entered by the user.
This is what I have (I have skipped the "average occurrence" part until I clean this up):
import java.util.Scanner;
public class Main
{
public static Scanner scan = new Scanner(System.in);
public static int[] userIntegers() // this method will build the array of integers, stopping when an out-of-range input is given
{
System.out.println("Enter the number of integers to be recorded: ");
int numInts = scan.nextInt();
int[] userArray = new int[numInts];
int i = 0;
while(i < numInts)
{
System.out.println("Enter an integer between 1-50 inclusive: ");
int userInteger = scan.nextInt();
if(isValidInteger(userInteger))
{
userArray[i] = userInteger;
i++;
}
else if(isValidInteger(userInteger) == false)
{
System.out.println("Try again.");
}
}
return userArray;
}
public static void occurrenceOutput(int[] input) // this method will print the occurrence data for a given array
{
int[] occurrenceArray = new int[51];
int j = 0;
while(j < 51) // iterates through all integers from 0 to 50, while the integer in the array is equal to integer j, the corresponding occurance array element increments.
{
for(int eachInteger : input)
{
occurrenceArray[j] = (eachInteger == j)? occurrenceArray[j]+=1: occurrenceArray[j];
}
j++;
}
int k = 0;
for(int eachOccurrence : occurrenceArray) // as long as there is more than one occurrence, the information will be printed.
{
if(eachOccurrence > 1)
{
System.out.println("The integer " + k + " occurrs " + eachOccurrence + " times.");
}
k++;
}
}
public static boolean isValidInteger(int userInput) // checks if a user input is between 0-50 inclusive
{
boolean validInt = (51 >= userInput && userInput >= 0)? true: false;
return validInt;
}
public static void main(String[] args)
{
occurrenceOutput(userIntegers());
}
}
Can someone point me in a more elegant direction?
EDIT: Thanks for the help! This is where I am at now:
import java.util.Scanner;
public class simpleHist
{
public static void main(String[] args)
{
getUserInputAndPrint();
getIntFreqAndPrint(intArray, numberOfInts);
}
private static int numberOfInts;
private static int[] intArray;
private static int[] intFreqArray = new int[51];
public static void getUserInputAndPrint()
{
// The user is prompted to choose the number of integers to enter:
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Integers: ");
numberOfInts = input.nextInt();
// The array is filled withchInteger = integer; integers ranging from 0-50:
intArray = new int[numberOfInts];
int integer = 0;
int i = 0;
while(i < intArray.length)
{
System.out.println("Enter integer value(s): ");
integer = input.nextInt();
if(integer > 50 || integer < 0)
{
System.out.println("Invalid input. Integer(s) must be between 0-50 (inclusive).");
}
else
{
intArray[i] = integer;
i++;
}
}
// Here the number of integers, as well as all the integers entered are printed:
System.out.println("Integers: " + numberOfInts);
int j = 0;
for(int eachInteger : intArray)
{
System.out.println("Index[" + j + "] : " + eachInteger);
j++;
}
}
public static void getIntFreqAndPrint(int[] intArray, int numberOfInts)
{
// Frequency of each integer is assigned to its corresponding index of intFreqArray:
for(int eachInt : intArray)
{
intFreqArray[eachInt]++;
}
// Average frequency is calculated:
int totalOccurrences = 0;
for(int eachFreq : intFreqArray)
{
totalOccurrences += eachFreq;
}
double averageFrequency = totalOccurrences / numberOfInts;
// Integers occurring more than once are printed:
for(int k = 0; k < intFreqArray.length; k++)
{
if(intFreqArray[k] > 1)
{
System.out.println("Integer " + k + " occurs " + intFreqArray[k] + " times.");
}
}
// Average occurrence of integers entered is printed:
System.out.println("The average occurrence for integers entered is " + averageFrequency);
}
}
You are actually looking for a histogram. You can implement it by using a Map<Integer,Integer>, or since the range of elements is limited to 0-50, you can use an array with 51 elements [0-50], and increase histogram[i] when you read i.
Bonus: understanding this idea, and you have understood the basics of count-sort
To calculate occurences, you can do something like this:
for(int eachInteger : input) {
occurrenceArray[eachInteger]++;
}
This will replace your while loop.