Generate and distribute random numbers fairly in java - java

Hi I have been trying to figure this quiz out
A lottery company shares out prizes to winning contestants every week. Most weeks, more than one contestant wins, in which case they try to share out the prizes as fairly as possible. Their prize distribution office has hired you to write a program that they will use to distribute prizes in the fairest way possible.
The program you write should take two lines of input:
A comma-separated list of this week's prizes' values
A comma-separated names of this week's winners
For example, the input could be:
100,800,200,500,400,1000
Joshua,Mahesh,Lilian
The program should then output the fairest possible distribution of prizes, by displaying one line for each winner, with the values of the prizes allocated to them. For example, given the input above, the output could be:
Joshua:100,400,500
Mahesh:1000
Lilian:800,200
The example above gives a perfect solution, where all winners get the same value of prizes (total value of 1000 each). In many cases, this will not be possible, but all prizes must be distributed and cannot be divided. Part of your job is to decide how you define 'fair' for these cases. For example, given the input
400,400,500,600
Barry,Sheila,Onyango,Wekesa
The following would be acceptable output, because there is no fairer distribution possible:
Barry:400
Sheila:400
Onyango:500
Wekesa:600
I am using java and so far this is what I have come up with
import java.util.Scanner;
import java.util.Arrays;
public class Main {
private static String amounts;
private static String names;
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print(
"Please enter the lottery amounts separated by commas: ");
if (userInput.hasNext()) {
amounts = userInput.next();
// System.out.println("You entered: " + amounts);
}
System.out.print("Please enter the contestants names: ");
if (userInput.hasNext()) {
names = userInput.next();
// System.out.println("You entered: " + names);
}
String amountArray[] = amounts.split(",");
String nameArray[] = names.split(",");
award(nameArray, amountArray);
}
// Method that awards the amounts to the winners
public static void award(String names[], String amounts[]) {
int randomAmount;
int randomName;
for (int i = 0; i < amounts.length; i++) {
randomAmount = (int) (Math.random() * amounts.length);
int usedValue[] = new int[amounts.length];
usedValue[i] = randomAmount;
if (checkValueUsed(randomAmount, usedValue)) {
randomName = (int) (Math.random() * names.length);
int usedName[] = new int[names.length];
System.out.println(names[randomName] + " = "
+ amounts[randomAmount]);
} else {
break;
}
}
}
private static boolean checkValueUsed(int currentState, int[] myArray) {
boolean found = false;
for (int i = 0; !found && (i < myArray.length); i++) {
if (myArray[i] == currentState) {
found = true;
}
}
return found;
}
private void checkUsedValue(int currentState, int[] myArray) {
for (int i = 0; (i < myArray.length); i++) {
if (myArray[i] == currentState) {
}
}
}
}
My idea of fair is to select a random amount and assign it to a random winner.

1) This looks like an interview/exam question. I'm not to judge but... really?
2) Your idea of fair is NOT what is intended. By the examples given, fair means all prizes are distributed and each winners total is as close to each other as possible.
3) From the above - this is a known problem. A greedy algorithm is likely to perform well. (I can't really see why not, unless you get very specific on the optimization part of the problem)

For a "fair" distribution you could try something like this:
Randomly order the winners.
For each winner, assign them the current highest available prize; so using your first example, winner one gets 1000, winner two gets 800, winner three gets 500.
If there are prizes left to distribute, for all but the first winner, assign them the current highest available prize that doesn't take them above the prize total of the first winner; winner two would get 200 (matching the 1000 of winner one), winner three gets 400 (to make 900).
Repeat step three until there are no more prizes or no prizes have been allocated; winner three gets 100 to match the 1000 of the other two.
If there are still prizes to allocate, sort the winners in descending order based on total prizes, and start allocating the lowest available prizes to all but the first winner.
Repeat step five until all prizes are allocated.

Related

Return more than one variable from a Java method

Your program must read the id number and gpa and transfer the data into two separate arrays. You can assume there will never be more than 1000 students in the file. Do you know why you must use two separate arrays? You may find it useful in this program to create additional arrays to complete the requirements of the program as described next.
Your program must do two distinctly different things correctly for full credit:
You must create a simple diagram to show how many students fall into each of 8 different categories. This type of diagram is known as a histogram and it is generally useful to show how data is distributed across a range.
For each student in the input file, you must display their S-number, gpa, and class rank. The S-number and gpa will already be in your arrays; however, you must calculate their class rank.
Here is the code I have so far:
public static void main(String[] args) throws Exception
{
Scanner gpadata;
String snum;
double gpa;
int groupNumber;
gpadata = new Scanner(new File("studentdata.txt"));
while (gpadata.hasNext())
{
snum = gpadata.next();
gpa = gpadata.nextDouble();
groupNumber = gpaGroup(gpa);
System.out.println("Student number, GPA, and group number"
+ " is: " + snum +
" " + gpa + " " + groupNumber);
}
}
//Method to categorize students GPA into 1 of 8 groups
public static int gpaGroup(double gpa)
{
//Declare all variables
int gpaGroup;
//Assign GPA a group number
if (gpa >= 0.0 && gpa < 0.5)
gpaGroup = 1;
else if (gpa >= 0.5 && gpa < 1.0)
gpaGroup = 2;
else if (gpa >= 1.0 && gpa < 1.5)
gpaGroup = 3;
else if (gpa >= 1.5 && gpa < 2.0)
gpaGroup = 3;
else if (gpa >= 2.0 && gpa < 2.5)
gpaGroup = 4;
else if (gpa >= 2.5 && gpa < 3.0)
gpaGroup = 5;
else if (gpa >= 3.0 && gpa < 3.5)
gpaGroup = 6;
else
gpaGroup = 7;
//Return int value of group number
return gpaGroup;
}
//Method to find number of students in each group
public static void studentsInGroup(int gpaGroup)
{
//Declare all variables
int gpaGroup1 = 0;
int gpaGroup2 = 0;
int gpaGroup3 = 0;
int gpaGroup4 = 0;
int gpaGroup5 = 0;
int gpaGroup6 = 0;
int gpaGroup7 = 0;
int gpaGroup8 = 0;
//Total students in each GPA group
if (gpaGroup == 1)
gpaGroup1++;
else if (gpaGroup == 2)
gpaGroup2++;
else if (gpaGroup == 3)
gpaGroup3++;
else if (gpaGroup == 4)
gpaGroup4++;
else if (gpaGroup == 5)
gpaGroup5++;
else if (gpaGroup == 6)
gpaGroup6++;
else if (gpaGroup == 7)
gpaGroup7++;
else
gpaGroup8++;
}
Can I modify my method to return more than one variable from a method (in public static void studentsInGroup(int gpaGroup) return values of number of students in each group)? Is this where arrays start to come in? From here I would write another method to round number of students in each category to the nearest ten, then use this to write a method for creating a histogram etc etc.
I have been trying my hardest to understand the concepts, but I have been struggling lately. This is one of my last assignments for the semester and I'd like to keep my A, and also understand what I'm doing.
Can I modify my method to return more than one variable from a method (in public static void studentsInGroup(int gpaGroup) return values of number of students in each group)?
Yes, you can. You can create an object that contains two variables. However, the instructions suggest a different solution.
Inside your loop, read the id and gpa, and immediately stick them in two separate arrays.
Here is a fragment:
snums = [];
gpas = [];
while (gpadata.hasNext())
{
snum = gpadata.next();
gpa = gpadata.nextDouble();
snums.append(snum);
gpas.append(gpa);
}
ensure you are doing the following. I'm not giving away any code here. Also not sure why they want you to use array only!?!
Breakdown your requirement and see what you need to achieve.
Start with reading each line from file
each line is separated by " " and has id_number and gpa
from the requirement, the file will not contain more than 1000 students(1000 lines). You may declare this as a static class level variable static String[] idnum_array = new String[1000]; and another array for gpa which is Double[]
read each line and then separate by using String.split(" ") method. The first variable is your id number and 2nd will be your gpa. you follow ?
maintain a separate counter to increment the array position each time you set these values in the two arrays you created in step 3.
Integer i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] splitString = line.split(" ");
idnum_array[i] = String.valueOf(splitString[0]);
gpa_array[i] = Double.valueOf(splitString[1]);
i++;
}
Do you agree that if we do idnum_array[7] to return it's corresponding gpa result from gpa_array[7] for that student ?
How you choose to count the number of people in a certain group is upto you.
I would do the following
create a static class level variable static Integer[] group_array = new Integer[]{0,0,0,0,0,0,0,0}; // there are only 8 groups!
loop my gpa_array
have an if/else inside the loop to check which group it falls in
increment the value at that index by 1. group_array[index]++;
In the end I will have an array of 8 elements which will correspond to the 8 groups. [0,200,300,200,0,300,0,0,0]
You should end up with nearly 4 methods similar to this.
1. readDataFromFile(String fileName)
2. groupGPAIntoCategory()
3. drawHistogram()
4. calculateRank()
I would personally create a Student object from the very beginning.
It's just cleaner and readable. Make sure you have your try catch block to print your exceptions and always comment!

Selecting randomly from a string array

I have run into a little problem. I have a homework exercise where i need to 'randomly' select a string from a string array. The goal of the exercise is to make a code which choses a random (inserted) name. My code:
public void run() {
int userSelection = -1;
int userAmount = 0;
String[] users = new String[userAmount];
int[] amountChosen = new int[userAmount];
while (userSelection != 0) {
drawMenu();
System.out.println();
//user selecting the menu choice
System.out.print("Make a selection from the menu: ");
userSelection = userInput();
System.out.println();
//forcing the user to give one of the allowed values
while (userSelection < 0 || userSelection > 4) {
System.out.print("That is invalid input. try again: ");
userSelection = userInput();
}
//adding users
if (userSelection == 1) {
System.out.print("How many users do we have?");
userAmount = userInput();
users = new String[userAmount];
amountChosen = new int[userAmount];
addUsers(users, userAmount); //returns user array with names
System.out.println();
}
//selecting random user
else if (userSelection == 2) {
int playerSelect = (int) (Math.random()*userAmount);
amountChosen[playerSelect]++;
System.out.println(users[playerSelect] + " was chosen!");
System.out.println();
}
//display the amount the users were chosen
else{
System.out.println("******** Turns ********");
for (int i = 0; i < userAmount; i++){
System.out.println("* " + "[" + amountChosen[i] + "] " + users[i]);
}
System.out.println("***********************");
System.out.println();
}
}
}
As you can see i now have a totally random userselection. For keeping tabs on how often a player is chosen i already made the 'int[] amountChosen' array. The goal is to "select a random player, also make it chose the player that is chosen the fewest times" so basicly it needs to select the string with the lowest amountChosen. (Also: I am aware my code may be a little bit messy and weird in some places. I just started learning java)
Thank you for response!
I won't give out the answer to your assignment. But, here is a naive implementation of what you are trying to achieve:
private void someMethod() {
String[] strArray = {"foo", "bar", "foobar"};
Random random = new Random();
System.out.println(strArray[random.nextInt(strArray.length)]);
}
Explanation:
You take a random number between 0 and the length of your string array using Random and then just use this as an index to query your string array.
If I understand correctly, you want to pick randomly one of all players having the lowest amount chosen?
Use a Map<String, Integer> with the amounts;
Filter the map with all players with the lowest amount;
Use Random.nextInt(amountOfLowest).
You could use Java Streams.
Hints: • use map.entrySet().stream() to stream over the map elements • use values(), unboxed() and min() to get the lowest value • use filter(), map() and collect() to collect a list of all players with the lowest amount • use List.get(new Random().nextInt(...)) to select a player.

Calling local variables in other static methods?

I am supposed to write a program that selects a random number between user given constraints, and asks the user to input guesses as to what this number is. The program gives feedback to the user as to whether or not the number is higher or lower than the user's guesses. The number of guesses, the number of games, the total guesses used throughout all of the games, and the lowest number of guesses used in one game are recorded.
These results are printed. The functions that responsible for running the game (playGame()) and the functions responsible for printing these results (getGameResults()) must be in two separate methods.
My problem is, I am not sure how to get the local variables that are modified throughout the course of the method playGame() to the getGameResults() method.
getGameResults() is intended to be called in another method, continuePlayTest(), which tests the user's input to determine whether or not they wish to continue playing the game, so I don't think that calling getGameResults() will work, otherwise this test will not work either. Unless I call continuePlayTest() in playGame(), but continuePlayTest() calls playGame() in its code so that would complicate things.
We can use ONLY the concepts that we've learned. We cannot use any concepts ahead.
So far, we've learned how to use static methods, for loops, while loops, if/else statements and variables. Global variables are bad style, so they cannot be used.
CODE:
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean whileTest = false;
gameIntroduction();
Scanner console = new Scanner(System.in);
playGame(console);
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
//Takes the user's input and compares it to a randomly selected number.
public static void playGame(Scanner console) {
int guesses = 0;
boolean playTest = false;
boolean gameTest = false;
int lastGameGuesses = guesses;
int numberGuess = 0;
int totalGuesses = 0;
int bestGame = 0;
int games = 0;
guesses = 0;
games++;
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
Random number = new Random();
int randomNumber = number.nextInt(MAXIMUM) + 1;
while (!(gameTest)){
System.out.print("Your guess? ");
numberGuess = console.nextInt();
guesses++;
if (randomNumber < numberGuess){
System.out.println("It's lower.");
} else if (randomNumber > numberGuess){
System.out.println("It's higher.");
} else {
gameTest = true;
}
bestGame = guesses;
if (guesses < lastGameGuesses) {
bestGame = guesses;
}
}
System.out.println("You got it right in " + guesses + " guesses");
totalGuesses += guesses;
continueTest(playTest, console, games, totalGuesses, guesses, bestGame);
}
public static void continueTest(boolean test, Scanner console, int games, int totalGuesses, int guesses, int bestGame) {
while (!(test)){
System.out.print("Do you want to play again? ");
String inputTest = (console.next()).toUpperCase();
if (inputTest.contains("Y")){
playGame(console);
} else if (inputTest.contains("N")){
test = true;
}
}
getGameResults(games, totalGuesses, guesses, bestGame);
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
System.out.println("Overall results:");
System.out.println("\ttotal games = " + games);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double)Math.round(guesses/games) * 100)/100);
System.out.println("\tbest game = " + bestGame);
}
}
If you cannot use "global" variables, I guess your only option is passing parameters when calling the method. If you don't know how to declare and use methods with parameters, I don't know another answer.
EDIT/ADD
After you specified your question, circumstances and posted your code I got a working solution including comments.
public class Guess {
public static int MAXIMUM = 100;
public static void main(String[] args) {
boolean play = true; // true while we want to play, gets false when we quit
int totalGuesses = 0; // how many guesses at all
int bestGame = Integer.MAX_VALUE; // the best games gets the maximum value. so every game would be better than this
int totalGames = 0; // how many games played in total
Scanner console = new Scanner(System.in); // our scanner which we pass
gameIntroduction(); // show the instructions
while (play) { // while we want to play
int lastGame = playGame(console); // run playGame(console) which returns the guesses needed in that round
totalGames++; // We played a game, so we increase our counter
if (lastGame < bestGame) bestGame = lastGame; // if we needed less guesses last round than in our best game we have a new bestgame
totalGuesses += lastGame; // our last guesses are added to totalGuesses (totalGuesses += lastGame equals totalGuesses + totalGuesses + lastGame)
play = checkPlayNextGame(console); // play saves if we want to play another round or not, whats "calculated" and returned by checkPlayNextGame(console)
}
getGameResults(totalGames, totalGuesses, bestGame); // print our final results when we are done
}
// Prints the instructions for the game.
public static void gameIntroduction() {
System.out.println("This process allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println(MAXIMUM + " and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
System.out.println();
}
// Takes the user's input and compares it to a randomly selected number.
public static int playGame(Scanner console) {
int guesses = 0; // how many guesses we needed
int guess = 0; // make it zero, so it cant be automatic correct
System.out.println("I'm thinking of a number between 1 and " + MAXIMUM + "...");
int randomNumber = (int) (Math.random() * MAXIMUM + 1); // make our random number. we don't need the Random class with its object for that task
while (guess != randomNumber) { // while the guess isnt the random number we ask for new guesses
System.out.print("Your guess? ");
guess = console.nextInt(); // read the guess
guesses++; // increase guesses
// check if the guess is lower or higher than the number
if (randomNumber < guess)
System.out.println("It's lower.");
else if (randomNumber > guess)
System.out.println("It's higher.");
}
System.out.println("You got it right in " + guesses + " guesses"); // Say how much guesses we needed
return guesses; // this round is over, we return the number of guesses needed
}
public static boolean checkPlayNextGame(Scanner console) {
// check if we want to play another round
System.out.print("Do you want to play again? ");
String input = (console.next()).toUpperCase(); // read the input
if (input.contains("Y")) return true; // if the input contains Y return true: we want play another round (hint: don't use contains. use equals("yes") for example)
else return false; // otherwise return false: we finished and dont want to play another round
}
// Prints the results of the game, in terms of the total number
// of games, total guesses, average guesses per game and best game.
public static void getGameResults(int totalGames, int totalGuesses, int bestGame) {
// here you passed the total guesses twice. that isnt necessary.
System.out.println("Overall results:");
System.out.println("\ttotal games = " + totalGames);
System.out.println("\ttotal guesses = " + totalGuesses);
System.out.println("\tguesses/games = " + ((double) (totalGuesses) / (double) (totalGames))); // cast the numbers to double to get a double result. not the best way, but it works :D
System.out.println("\tbest game = " + bestGame);
}
}
Hope I could help.
Is it a problem passing the variables between functions? ex:
public static void getGameResults(int games, int totalGuesses, int guesses, int bestGame) {
// implementation
}
Another option, assuming this is all in one class, is using private static memeber variables. They aren't global. Then again, they might be considered 'global' by your teacher for this assignment.
Given that you've only learnt how to use static methods, your only option is to pass the information from function to function via its arguments.

Arrays counting

If my program gives the user about a team's championship history, for example, if the user enters Chelsea, my program will say, "They have won it in 2012,2010,2007,2008" (using parallel array list already provided and has to be used).
How would i display, from that result, the number of times they have won . So if that information is correct, i want my program to say, "Chelsea has won it 4 times".
This is what i have so far:
public static void showWinner(short years[], String winners[]){
Scanner kd = new Scanner (System.in);
String name;
System.out.println("Which teams result would you like to see?: " );
name = kd.next();
for (int i = 0; i < winners.length; i++) {
if (winners[i].equals(name)){
System.out.println(years[i]);
}
}
Try this: I am assuming that winners array and years array has mapping in which year which team won. I suggest you to use Map for this purpose. It will be more understandable and efficient.
int count = 0;
for (int i = 0; i < winners.length; i++){
if (winners[i].equals(name)){
count ++;
System.out.println(years[i]);
}
}
System.out.println(name + " has won it" + count + "times");

Beginner Java (getting class assignment to compile)

This is a lab I am working for for a CSE 201. The program is supposed to read information about students and their scores from a file, and output the name of each student with all his/her scores and the total score, plus the average score of the class, and the name and total score of the students with the highest and lowest total score.
The exact assignment can be seen here.
I'm having a little trouble getting it to compile, especially with the variable "students".
Any help would be great.
/*
* The program will read information about students and their
* scores from a file, and output the name of each student with
* all his/her scores and the total score, plus the average score
* of the class, and the name and total score of the students with
* the highest and lowest total score.
*/
import java.util.Scanner;
public class Lab7
{
public static void main(String[] args)
{
// Input file name
Scanner in = new Scanner(System.in);
String filename = getFileName(in);
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
// Input all students records and create Student array and
// integer array for total scores
int[] totalScores = new int[students.length];
for(int i = 0; i < students.length; i++){
for(int j = 1; j < 4; j++){
totalScores[i] += students[i].getScore(j);
}
}
// Compute total scores and find students with lowest and
// highest total score
int maxIndex = 0, minIndex = 0;
for(int i = 0; i < students.length; i++){
if(totalScores[i] > totalScores[maxIndex]){
maxIndex = i;
}else if(totalScores[i] < totalScores[minIndex]){
minIndex = i;
}
}
// Compute average total score
int average = 0;
for(int i = 0; i < totalScores.length; i++){
average += totalScores[i];
}
average /= students.length;
// Output results
outputResults(students, totalScores, maxIndex, minIndex, average);
}
// Given a Scanner in, this method prompts the user to enter
// a file name, inputs it, and returns it.
private static String getFileName(Scanner in)
{
System.out.print("Enter input file name: ");
return in.nextLine();
}
// Given the number of students records n to input, this
// method creates an array of Student of the appropriate size,
// reads n student records using the FileIOHelper, and stores
// them in the array, and finally returns the Student array.
private static Student[] getStudents(int n)
{
Student[] student = new Student[n];
for(int i = 0; i < student.length; i++){
student[i] = FileIOHelper.getNextStudent();
}
return student;
}
// Given an array of Student records, an array with the total scores,
// the indices in the arrays of the students with the highest and
// lowest total scores, and the average total score for the class,
// this method outputs a table of all the students appropriately
// formatted, plus the total number of students, the average score
// of the class, and the name and total score of the students with
// the highest and lowest total score.
private static void outputResults(
Student[] students, int[] totalScores,
int maxIndex, int minIndex, int average
)
{
System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal");
System.out.println("--------------------------------------------------------");
for(int i = 0; i < students.length; i++){
outputStudent(students[i], totalScores[i], average);
System.out.println();
}
System.out.println("--------------------------------------------------------");
outputNumberOfStudents(students.length);
outputAverage(average);
outputMaxStudent(students[maxIndex], totalScores[maxIndex]);
outputMinStudent(students[minIndex], totalScores[minIndex]);
System.out.println("--------------------------------------------------------");
}
// Given a Student record, the total score for the student,
// and the average total score for all the students, this method
// outputs one line in the result table appropriately formatted.
private static void outputStudent(Student s, int total, int avg)
{
System.out.print(s.getName() + "\t");
for(int i = 1; i < 4; i++){
System.out.print(s.getScore(i) + "\t");
}
System.out.print(total + "\t");
if(total < avg){
System.out.print("-");
}else if(total > avg){
System.out.print("+");
}else{
System.out.print("=");
}
}
// Given the number of students, this method outputs a message
// stating what the total number of students in the class is.
private static void outputNumberOfStudents(int n)
{
System.out.println("The total number of students in this class is: \t" + n);
}
// Given the average total score of all students, this method
// outputs a message stating what the average total score of
// the class is.
private static void outputAverage(int average)
{
System.out.println("The average total score of the class is: \t" + average);
}
// Given the Student with highest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the highest score.
private static void outputMaxStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the maximum total score of: \t" + score);
}
// Given the Student with lowest total score and the student's
// total score, this method outputs a message stating the name
// of the student and the lowest score.
private static void outputMinStudent(
Student student,
int score
)
{
System.out.println(student.getName() + " got the minimum total score of: \t" + score);
}
}
First of all: it's always useful to actually pay attention to the compiler error. Java's compier errors are very clear and useful most of the time, and tell you exactly what's wrong once you're learned to understand them. And generally, it's much easier for people here on SO to help you if you include the actual text of an error rather than saying "I have trouble getting it to compiler"
This is the first obviously wrong line:
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
A variable declaration in Java consists of (slightly simplified):
The type of the variable
its name
optionally an assignment of an initial value
In the above line, you start with type int, but the next part Student[students] makes no sense - it looks like an array instantiation, certainly not a name. What you probably meant is:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
i.e. the type is Student[] (an array of Student objects), the name is 'students', and it's assigned the return value of the getStudents() method. An int is not involved anywhere (you don't have to specify the size of the array here, since it is created inside the getStudents() method).
The size of your array cannot be specified on the lefthand side.
The student array declaration should look like this:
int noOfStudents = FileIOHelper.getNumberOfStudents(filename);
//create an array of students of the given length
Student[] students = new Student[noOfStudents];
This part looks to be an issue:
// Input number of students
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
You probably want to first get the number of students, then use that variable to call getStudents. Also, if you want the array to be called students it should not be in the brackets.
Student[] students = .....
The line where you're having trouble is the very first line at the top of main():
int Student[students] = getStudents(FileIOHelper.getNumberOfStudents(filename));
I always recommend reading through a problematic line with the same mindset as a compiler: it doesn't know anything except what you've told it, top to bottom, left to right.
So let's start at the beginning:
int
I know what an int is! You want to declare one! Awesome! Moving on...
Student
What the heck is a Student? I don't see anywhere in the code that would tell me what that is! As a human, I can infer that it's supposed to be the name of a class, since class names are always capitalized in Java, but it's not declared so the compiler cannot be sure. Is it perhaps supposed to be the name of this class (instead of Lab7)?
More importantly, if it is a class then you have just named two datatypes in a row: int and Student. Which type did you intend to use? Presumably if you want a list of Students, the int is not relevant at all. If you want the number of students, then just the int is relevant.
Moving on:
students
What the heck is a students? I again don't see anywhere in the code that would tell me what that is!
Let's back away for a moment. What are you really trying to do here? You're trying to obtain an array of all the students in the file. The getStudents() function presumably achieves that. (It may be buggy, but that's not our problem at the moment. We're just calling it here, so we will assume that it works.)
But how are you supposed to know how big to make the array if you haven't yet read it? Conveniently, you don't have to know! You can simply write:
Student[]
You are instantiating the array down in getStudents(), and there you've correctly given it a size. Here in main() you're simply declaring it, and no size is necessary.
Okay, so can you just write:
Student[] = getStudents(FileIOHelper.getNumberOfStudents(filename));
No, 'cause your variable doesn't have a name. How about something like this:
Student[] students = getStudents(FileIOHelper.getNumberOfStudents(filename));
I suspect that's what you intended, but since you got stuck somewhere along the way it's important to be able to get "unstuck," and mentally walking through what the compiler sees is a useful way to do that.

Categories

Resources