Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm working on my final project for class where we are making a class to store employees, ID#, and salary ranges, then create methods and arrays that add to the class. So far, I have it set up to add new employees, and print all employees, but I am kind of confused how to get these two prompts:
Retrieve specific employee’s data - prompts user for the employee id and displays the corresponding employee’s data: id, name, and salary
Retrieve employees with salaries based on range - prompts user for the lowest and highest salary and displays all employees with salaries in that range. Display each employee on separate line with all information - name, id, and salary
How would I incorporate that into this following code?
import java.util.ArrayList;
import java.util.Scanner;
public class FP {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<EmployeeData> companyData = new ArrayList<>();
// Boolean loop and while loop to restart the program in all cases but 3
boolean loopAgain = true;
while (loopAgain) {
System.out.println("Main Menu:");
System.out.println("1: Load New Employee Data");
System.out.println("2: Print Employee Data");
System.out.println("3: Exit");
int answer = in.nextInt();
switch (answer) {
// Case 1 to be called on when user selects "1"
case 1: {
System.out.println("Load New Employee Data:");
System.out.println("Please enter the number of new Employees to be added to
the sytem.");
System.out.println();
int loop = in.nextInt();
//For loop to add the number to class EmployeeData
for (int i =0; i < loop; i++) {
companyData.add(new EmployeeData());
}
} break;
// Case 2 to be called on when user selects "2"
case 2: {
// for loop to display the employees information after being entered by the user
for (EmployeeData x : companyData) {
x.printData();
}
} break;
// Case 2 to be called on when user selects "3" breaking the loop and ending the program
case 3: loopAgain = false; break;
}
}
}
}
// Class to store information for user input of employee data
class EmployeeData {
// String variable for names
String name;
// Int variables for ID and Salary
int id, salary;
public EmployeeData() {
// scan options and prompts for user input to be stored in class Employee Data
Scanner in = new Scanner(System.in);
System.out.println();
System.out.println("Enter Employee Name: ");
System.out.println();
String name = in.nextLine();
System.out.println();
System.out.println("Enter Employee ID:");
System.out.println();
int id = in.nextInt();
System.out.println();
System.out.println("Enter Employee Salary: ");
System.out.println();
int salary = in.nextInt();
// callable and modified variables stored for case 2
this.name = name;
this.id = id;
this.salary = salary;
}
// print section to be shown to user when case 2 is selected
public void printData() {
System.out.println();
System.out.println("Employee: " + this.name);
System.out.println();
System.out.println("ID: " + this.id);
System.out.println();
System.out.println("Salary: " + this.salary);
System.out.println();
}
}
For case 4:
System.out.println("Please enter the id.");
System.out.println();
int id = in.nextInt();
boolean find = false;
for (EmployeeData employeeData : companyData) {
if (employeeData.id == id) {
find = true;
// todo print info
break;
}
}
if (!find) {
// todo print something
}
For case 5:
System.out.println("Please enter the min salary.");
System.out.println();
int min = in.nextInt();
System.out.println("Please enter the max salary.");
System.out.println();
int max = in.nextInt();
for (EmployeeData employeeData : companyData) {
if (employeeData.salary <= max && employeeData.salary >= min) {
// todo print info on one line
}
}
In addition, it is not a good practice to do scan operate in constructor when you load data, move it outside:
case 1:
for (int i =0; i < loop; i++) {
EmployeeData employeeData = new EmployeeData();
// todo scan and set value
companyData.add(employeeData);
}
And to make the program more complete, you should make some extra checks, such as that the ID cannot be repeated when load data.
Related
In a project for school, I'm required to make a menu system with the following options:
Load employees’ data - prompts user for the number of employees to be loaded and then prompts for each employee name, id (5 digit number), and annual salary
Add new employee - prompts user for an employee data, name, id, and annual salary
Display all employees - displays each employee’s data to the console, one employee per line
Retrieve specific employee’s data - prompts user for the employee id and displays the corresponding employee’s data: id, name, and salary
Retrieve employees with salaries based on range - prompts user for the lowest and highest salary and displays all employees with salaries in that range. Display each employee on separate line with all information - name, id, and salary
Exit
Each menu choice must be it's own be its own method, and he prefers we use arrays instead of lists, which is why I allotted 100 spaces. Here is what I have so far. Menu options 1, 2, and 6 run without breaking the program. But anything where things have to be displayed seems to break. My best guess is that there is an issue with passing and updating the array "employees" between all of the methods.
package practice;
import java.util.Arrays;
import java.util.Scanner;
public class Project {
public static Employee[] loadData() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("How many employees would you like to add?"); //Determines how many employees to create
Employee[] employees = new Employee[100];
int numberEmployees = scanint.nextInt();
for (int i = 0; i < numberEmployees; i++) {
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter Salary: ");
int empSalary = scanint.nextInt();
employees[i+1] = new Employee(empName, empID, empSalary); //Add employee to array
}
return employees;
}
public static Employee addEmployee() {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
System.out.println("Enter name: ");
String empName = scanstr.nextLine();
System.out.println("Enter ID: ");
int empID = scanint.nextInt();
System.out.println("Enter salary: ");
int empSalary = scanint.nextInt();
return new Employee(empName, empID, empSalary);
}
public static void displayEmployees(Employee[] employees) {
for (int i = 0; i < employees.length; i++) {
if (employees[i] != null) {
System.out.println(Arrays.toString(employees));
//System.out.println("Employee Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
}
}
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
public static void salaryRange(Employee[] employees, int salaryMinimum, int salaryMaximum) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].salary >= salaryMinimum && employees[i].salary <= salaryMaximum) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("No employees within salary range");
}
}
}
public static void main(String[] args) {
Scanner scanint = new Scanner(System.in);
Scanner scanstr = new Scanner(System.in);
int menuChoice = 0;
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
Employee[] employees = new Employee[100];
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
else if (menuChoice == 2) {
employees[0] = addEmployee();
}
else if (menuChoice == 3) {
displayEmployees(employees);
}
else if (menuChoice == 4) {
System.out.println("Enter 5 digit employee ID: ");
int id = scanint.nextInt();
specificEmployee(employees, id);
}
else if (menuChoice == 5) {
System.out.println("Enter minimum of salary range: ");
int salaryMinimum = scanint.nextInt();
System.out.println("Enter maximum of salary range");
int salaryMaximum = scanint.nextInt();
salaryRange(employees, salaryMinimum, salaryMaximum);
}
else if (menuChoice == 6) {
break;
}
else {
System.out.println("Invalid Choice");
}
}
scanint.close();
scanstr.close();
}
Any help would be appreciated!!!!!
There are a few problems in your code:
while (menuChoice != 6) {
System.out.println("\tMenu:");
System.out.println("1. Load Employee Data");
System.out.println("2. Add New Employee");
System.out.println("3. Display All Employees");
System.out.println("4. Retrieve Specific Employee Data");
System.out.println("5. Retrieve Employees Within Salary Range");
System.out.println("6. Exit");
menuChoice = scanint.nextInt();
**Employee[] employees = new Employee[100];**
int amountEmployees;
if (menuChoice == 1) {
employees = loadData();
}
You have declared the employees array inside the while loop, so each time you read an input you are creating a new one. This totally defeats the purpose of storing employees in an array and later retrieving them, which also makes the assignment redundant if menuChoice == 1. You must think about where you should declare your array.
public static void specificEmployee(Employee[] employees, int id) {
for (int i = 0; i < employees.length; i++) {
if (employees[i].id == id) {
System.out.println("Name: " + employees[i].name + " ID: " + employees[i].id + " Salary: " + employees[i].salary);
}
else {
System.out.println("ID not recognized");
}
}
}
When you declare an array, the values by default are null, unless you assign them some values. Here, you are iterating the entire array and checking for employee id. You should consider what would happen if the employee at a particular index in the array is null. You must have checks for such cases.
A similar problem is in one of the other methods that you have created. I will let you debug that on your own.
And as suggested by #NomadMaker - Your second menu item only sets element 0 of the array. You can't add two or more employees.
I would suggest, you try to dry run your code and if you find it tough, try debugging it in an ide.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
For example, we have 5 courses available: comp2011, comp2012, comp2013, comp2014, comp2015.
When adding or dropping a course, you need to specify the student's name (you may assume it is unique) and the course that is going to be added/dropped.
For adding a course, if the student has already enrolled in at least one course, the system will append the newly added course to his/her course record. But if it is the first time the student is trying to add courses, the system will create a record for him/her and state that this is the first course of this student (see sample output below)...
The system should support listing the courses that the student has enrolled in.
The system should support some basic validation check: Students cannot add the same course two times nor drop a course that is not enrolled.
When dropping the last course, there will be nothing in the student course list, but the system should still keep the empty file for him/her so that when another course is added, it knows that this is not the first time.
How Can I Make the Array that is going to support all my methods at once knowing that I made a method for adding, dropping, listing and quitting.(Quiting is not having an array)
This is where I am at now:
import java.util.*;
public class codeTraining {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
switch (AddDrop) {
case "A" -> A();
case "D" -> D();
case "L" -> L();
case "Q" -> Q();
default -> System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
}
public static void Q() {
System.out.println("Quit...");
}
}
You could use a hashmap for this problem, as it will allow you to quickly and easily look up the courses of students. It's declared as a global variable outside all of the methods, which means it can be accessed by any of them.
import java.util.*;
public class codeTraining {
//Hashmap contains names that are mapped to lists of courses
static HashMap<String, ArrayList<String>> map =
new HashMap<String, ArrayList<String>>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
//added breaks to the switch statement
switch (AddDrop) {
case "A": A(); break;
case "D": D(); break;
case "L": L(); break;
case "Q": Q(); break;
default: System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
//if the map contains the name already
if (map.containsKey(name)) {
//if the student already had the course in its list
if (map.get(name).contains(course)) {
System.out.println("The student is already taking this course");
return;
} else {
//adding the course to the list that's mapped
//to the student's name in the hashmap
map.get(name).add(course);
}
}
//if student isn't in the system
else {
//create a new arraylist with the new course in it
ArrayList<String> courses = new ArrayList<String>();
courses.add(course);
//add a map between the student's name and his course list
map.put(name, courses);
}
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
//checks if name in system
if (map.containsKey(name)) {
if (map.get(name).contains(course)) {
//removing if list had the course in it
map.get(name).remove(course);
} else {
System.out.println("This student isn't taking that course");
return;
}
} else {
System.out.println("This student isn't in the system");
return;
}
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
if (map.containsKey(name)) {
//printing out courses for specified student
ArrayList<String> courses = map.get(name);
for (int i = 0; i < courses.size(); i++) {
System.out.print(courses.get(i) + " ");
}
} else {
System.out.println("This student isn't in the system");
}
}
public static void Q() {
System.out.println("Quit...");
}
}
I added some comments in case you were new to hashmaps. Basically, map.put(key, value) will add a mapped pair to the list so that when you call map.get(key), it will return whatever value you put it to. I hope this helps, and feel free to ask if you're confused.
import java.util.ArrayList;
import java.util.Scanner;
/*Create a program that keeps track of specific information for Students. The information stored should be the following:
First Name, Last Name, Major, GPA, UIN, NetID, Age, Gender,
For this simple program we will only need to store 10 students in an ArrayList.
Your students should be stored in an object called Student.
You should be able to add, display and remove Students in the ArrayList.
You will submit 2 files for grading: Lab4.java and Student.java*/
public class Lab4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Student> newStudents = new ArrayList<Student>();
// ArrayList<Student> newStudents = new ArrayList<Student>(10); tried this as well, but doesn't work.
System.out.println("Welcome to the Student Interface!.");
System.out.println("Please select a number from the options below \n");
while (true) {
// Give the user a list of their options
System.out.println("1: Add a student to the list.");
System.out.println("2: Remove a student from the list.");
System.out.println("3: Display all students in the list.");
System.out.println("0: Exit the student interface.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice) {
case 1:
addStudents(newStudents);
break;
case 2:
removeStudent(newStudents);
break;
case 3:
displayStudent(newStudents);
break;
case 0:
System.out.println("Thank you for using the student interface. See you again soon!");
System.exit(0);
}
}
}
public static void addStudents(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
boolean student_added = false;
// TODO: Add a student that is specified by the user
System.out.println("Please enter first name: ");
String firstName = input.next();
System.out.println("Please enter last name: ");
String lastName = input.next();
System.out.println("Please enter major: ");
String Major = input.next();
System.out.println("Please enter GPA: ");
String GPA = input.next();
System.out.println("Please enter UIN: ");
String UIN = input.next();
System.out.println("Please enter NetID: ");
String NetID = input.next();
System.out.println("Please enter Age: ");
String Age = input.next();
System.out.println("Please enter Gender: ");
String Gender = input.next();
for (int i = 1; i < 5; i++) { // ( I have also tried i<newStudents.size(). Didn't work.Thank you in advance!)
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetID, Age, Gender));
student_added = true;
break;
}
if (student_added) {
System.out.println("Student Added");
System.out.println();
} else {
System.out.println("\n Student Interface is full!");
}
}
private static void displayStudent(ArrayList<Student> newStudents) {
// TODO Auto-generated method stub
for (Student e : newStudents) {
System.out.println(e);
}
}
private static void removeStudent(ArrayList<Student> newStudents) {
Scanner input = new Scanner(System.in);
System.out.println("Please, enter the UIN to remove the Student: ");
String uin = input.nextLine();
for (Student e : newStudents) {
if (e.getUIN().equals(uin)) {
newStudents.remove(e);
System.out.println("Student removed");
break;
}
else {
System.out.println("Sorry, no such student with this " + uin + " " + "number exist");
}
}
}
}
The Student instance is being added to the list, and there is no check for if the size of the array is larger or equal to 10. You are checking the value of the i variable, which is created when you enter the for loop.
The for loop isn't the right tool for this job in this case.
Instead, do a check for newStudents.size(), and if that does not exceed the maximum value, add the student to the list.
For example:
if (newStudents.size() <= 10) { // check the size of the array [see note 1]
newStudents.add(new Student(firstName, lastName, Major, GPA, UIN, NetId, Age, Gender));
System.out.println("Student added\n");
} else {
System.out.println("\n Student interface is full!");
}
Note 1: As an aside, it'd be best if 10 was a constant at the top of the program (defined like public static const MAX_STUDENTS = 10;) to make the code more maintainable. See this question about what a magic number is.
So I have this program that builds a School using dynamic arrays instead of using Array List. I have the methods created and tested, everything works except I'm trying to get the UI to work.
The UI is supposed to take user input to build the array of Students. Normal students versus CS students. The problem is, when I enter in how many students I want to enter into the school either regular or CS students, it stops after I enter in the amount of students I request to enroll.
I want the ability to say enroll 5 students, then go back and be asked if I want to enroll more, drop a student, or do any of the other options listed on the main menu. That's my problem. Every time I try to add in a for loop or switch the if/else if statements around compilation errors abound. This is the entire code that I have created:
import java.util.Arrays;
import java.util.Scanner;
public class School {
private Student[] theStudents;
public School() {
this.theStudents = new Student[0];// needs to start out as empty
}
/*
* next two methods would allow a user to add or drop a student into the
* student array for the school ??Also with Enroll student, should be able
* to assign a class to the student, i.e. Calculas, history, etc??
*/
public void enrollStudent(Student newStudent) {
Student totalStudents[] = new Student[theStudents.length + 1];
for (int i = 0; i < theStudents.length; i++) {
totalStudents[i] = theStudents[i];
}
totalStudents[theStudents.length] = newStudent;
theStudents = totalStudents;
}
public void dropStudent(String dropStudent) {
boolean checkForName = false;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getName().equals(dropStudent)) {
theStudents[i] = null;
checkForName = true;
}
}
if (checkForName == true) {
Student totalStudents[] = new Student[theStudents.length - 1];
for (int i = 0; i < totalStudents.length; i++) {
if (theStudents[i] == null) {
totalStudents[i] = theStudents[theStudents.length - 1];
} else {
totalStudents[i] = theStudents[i];
}
}
theStudents = totalStudents;
}
if (checkForName == false) {
System.out.println("The Student does not exist in the school");
}
}
// add Test Score for a student
public void addTestScore(String newStudent, double testScore) {
for (int i = 0; i < theStudents.length; i++) {
if (newStudent.equals(theStudents[i])) {
theStudents[i].addTestScore(testScore);
}
}
}
/*
* count the number of students in a given class, not the school
*/
public int countClassSize(String course) {
// Need to access how the course names are stored for the school to
// count this size.
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
count = count + 1;
}
}
return count;
}
/*
* get average average score of the student array The student array is made
* up of Regular students and CompSciStudents. The average should take the
* average of both the average score for Students and average score of
* CompSciStudents and return the average average.
*/
public double averageAverageScore(String course) {
double avgAvgTest = 0;
for (int i = 0; i < theStudents.length; i++) {
if (theStudents[i].getClassName().equals(course)) {
avgAvgTest += theStudents[i].getTestAvg();
}
}
return avgAvgTest / this.countClassSize(course);
}
/*
* add a programming language to only CS students at the school Will need to
* use the instanceof for proper type casting
*/
public void addProgrammingLanguage(String studentName, String programLanguage) {
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
tempStudent.learnedLanguage(programLanguage);
}
}
}
/*
* Count the number of students in the school that know a certain
* programming language, again will need to typecast properly
*/
public int numberThatKnowLanguage(String programLanguage) {
int count = 0;
for (int i = 0; i < theStudents.length; i++) {
if (this.theStudents[i] instanceof CompSciStudent) {
CompSciStudent tempStudent = (CompSciStudent) this.theStudents[i];
String knowThisLanguage = programLanguage;
tempStudent.learnedLanguage(knowThisLanguage);
count += 1;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String dropStudent, course;
System.out.println("Welcome to the School. Please select\n" + " Option 1 to enroll a regular student,"
+ "Option 2 to enroll a CompSci student, \n" + "Option 3 to drop a student, \n"
+ "Option 4 to add test score or programming language, or \n" + "Option 5 to perform class analytics.");
int Operation = input.nextInt();
/*
* Simple UI to add and drop students, will need to set the operation to
* call the add and drop students to fit them to the Student body array
* will need to make these two options loop until the user is satisfied
* with the size of the student body
*/
if (Operation == 1) {
System.out.println("Enter the # of regular students that you want to add to the school.");
int addStudents = input.nextInt();
// Possibly create some type of input array to
// make it easier to enter the students' names. for(<type> <var
// name> : <array name>)
System.out.println("Please enter the name and course of the student you are enrolling:");
for (int i = 0; i < addStudents; i++) {
String newRegularStudent = (String) input.next();
course = input.next();
System.out.println("Enter next student's name and then the course's name that he is enrolling in.");
}
} else if (Operation == 2) {
System.out.println("Enter the # of CompSci students that you want to add to the school.");
int addStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name and course of the student you are enrolling:");
String newCompSciStudent = (String) input.next();
course = input.next();
}
else if (Operation == 3) {
System.out.println("Enter the # of students that you want to drop from the school.");
int dropStudents = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
System.out.println("Please enter the name of the student you wish to drop from the school:");
dropStudent = (String) input.next();
/*
* After the first two operations, will need to build to the UI to
* call the other five methods, will need to make it into a
* while/for loop so user can continue to add information as needed.
*/
}
else if (Operation == 4) {
System.out.println("Enter the # for what you want to add to a student's records."
+ "Enter 1 to enter a test score\n " + "Enter 2 to enter a programming language, enter 2.");
int optionNum1 = input.nextInt();
/*
* Possibly create some type of input array to make it easier to
* enter the students' names
*/
if (optionNum1 == 1) {
} else if (optionNum1 == 2) {
}
}
else if (Operation == 5) {
System.out.println("This is the analytics section of this program.\n");
System.out.println("Enter the # for which of the following analytics options that you want performed: "
+ "Enter 1 to count the # of students for a particular class,\n "
+ "Enter 2 to calculate the average average score for all students take a particular course, or\n "
+ "Enter 3 to count the # of CompSciStudents.");
int optionNum2 = input.nextInt();
if (optionNum2 == 1) {
System.out.println("Enter the course name that you\n" + " want to know the # of students for.");
course = input.next();
Student classSize;
}
else if (optionNum2 == 2) {
System.out.println(
"Enter the course name that you want to \n" + "calculate the average average test value for.");
course = input.next();
Student testAvg;
}
else if (optionNum2 == 3) {
System.out.println("Count the # of CompSciStudents who know a particular programming\n"
+ " language by entering that language name now.");
String programLanguage = input.next();
CompSciStudent csStudent = null;
csStudent.knowsLanguage(programLanguage);
}
}
input.close();
}
}
You cannot change the size of an array in Java at runtime. The size of your array therefore will always be zero since you wrote:
this.theStudents = new Student[0];
I would suggest you to use:
ArrayLists<type> list = new ArrayLists<type>();
If you do now know how to use ArrayLists you can follow this tutorial.
I created a method that returns a row of arrays via user input. I managed to display the set of inputted number on the same class using System.out.println by assigning each value in userDigits.
My question is, how can I pass the same value in another class?
public class LottoTicket extends Ticket {
public int NUM_DIGITS = 5;
public int[] userDigits = new int[NUM_DIGITS];
#Override
public void buyTicket() {
Scanner input = new Scanner(System.in);
int number = 0;
double amount = 0;
System.out.println("-------=======LOTTO TICKET SCREEN=======--------");
System.out.println("");
System.out.println("There are three Types (Prima, Ambo and Terro)");
System.out.print("Please select one (P, A, T): ");
String lotteryOption = input.next();
switch (lotteryOption) {
case "P": {
break;
}
case "A": {
break;
}
case "T": {
amount = getAmount(amount);
getUserData(userDigits);
int ticketSold;
ticketSold = +1;
int tik = ticketSold +1;
System.out.println(amount);
System.out.println("Your numbers are: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " ");
System.out.println("Ticket/s Sold: " + tik);
System.out.println("Thank you for playing");
Ticket.pressAnyKeyToContinue();
LotteryApplication.loginScreen();
break;
}
default: {
System.out.println("Invalid Input. Please try again.");
System.out.println("");
buyTicket();
break;
}
}
}
#Override
public double getAmount(double amount) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter amount of money: ");
amount = input.nextDouble();
//input.close();
return amount;
}
#Override
public int getUserData(int[] userInput) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a number from 1 to 90: ");
userDigits[0] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[1] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[2] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[3] = input.nextInt();
System.out.print("Choose a number from 1 to 90: ");
userDigits[4] = input.nextInt();
//key.close();
//Returns last value of array
return userDigits[4];
}
//public int userDigits[];
public static void printTicket(){
// System.out.println(getUserData.userDigits[4]);
// for (int i = 0; i < array.length)
}
}
Well, in this case, since you defined userDigits as public, you can do it easily - it is accessible to any class that has a visibility to your instance of LottoTicket. With the current setup you could do something like this:
// you need to instantiate LottoTicket somewhere in your app
LottoTicket ticket = new LottoTicket();
// get the input from user
ticket.buyTicket();
// at this point you can access the numbers and pass them to some other method like this
checkNumbers(ticket.userDigits);
The example posted above needs you to provide a method checkNumbers that has, for example, the following signature:
public void checkNumbers(int[] numbers) {
// the comparison code goes here...
Also, this is somewhat unrelated to your question, but I'd like to point out two issues with your current code:
defining class fields as public is done rather rarely, more common approach is to define these as private and provide methods for getting/setting the field values; this restricts the operation on these fields to only those you allow - having public field allows anyone who has a visibility to that field to perform basically any operations, which is usually not what you want
you call buyTicket() from default in case user didn't select valid lottery type; in extreme cases this could lead to StackOverflowError - better approach would be to use a loop that keeps asking user for input until a valid one is provided
Hope this helps at least a bit.
You can easily pass input array to method of another class arguments.
class PassValue{
public static void display(int[] elements){
Anotherclass obj= new Anotherclass();
obj.display2(elements);
}
}
class Anotherclass{
public void display2(int[] values){
do whatever you want
}
}