Give one array to mutltiple methods [closed] - java

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.

Related

How to call certain information from a user input array [closed]

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.

variables are not created even though I declared them Correctly [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I am trying to Creating a library management system which is capable of issuing books to the students.
Book should have info like:
1. Book name
2. Book Author
3. Issued to
4. Issued on
User should be able to add books, return issued books, issue books
When I am executing the below code and choosing option 1 as choice I am not able to give input to the bName String and author String
am I doing something wrong, I am new to java please help me
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Scanner;
/*
Creating a library management system which is capable of issuing books to the students.
Book should have info like:
1. Book name
2. Book Author
3. Issued to
4. Issued on
User should be able to add books, return issued books, issue books
*/
class BookInfo
{
protected String name,author,issuedTo,issuedOn;
public BookInfo(String bName,String bAuthor) {
this.addBook(bName,bAuthor);
}
public String getBookName()
{
return name;
}
public String getAuthor()
{
return author;
}
public String getIssuedOn()
{
return issuedOn;
}
public String getIssuedTo()
{
return issuedTo;
}
public void addBook(String name,String author)
{
this.name=name;
this.author=author;
}
public void issueBook(String name)
{
this.issuedTo=name;
LocalDateTime t=LocalDateTime.now();
DateTimeFormatter dTF=DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss");
this.issuedOn=t.format(dTF);
}
public void returnIssuedBooks()
{
issuedTo=null;
issuedOn=null;
}
}
public class Main {
public static void main(String[] args){
ArrayList<BookInfo> l1 = new ArrayList<>();
int choice;
String bName;
String name;
String author;
boolean isTrue = true;
Scanner obj = new Scanner(System.in);
System.out.println("welcome to the Library Management System");
while (isTrue) {
System.out.println("choose from the options below :");
System.out.println("press 1 for adding the book");
System.out.println("press 2 for issuing the book");
System.out.println("press 3 for returning the issued book");
System.out.println("press 4 to exit");
choice = obj.nextInt();
try {
switch (choice) {
case 1:
System.out.println("enter the name of the book :");
bName = obj.nextLine();
System.out.println("enter the author of the book");
author = obj.nextLine();
l1.add(new BookInfo(bName,author));
break;
case 2:
System.out.println("enter the name of the book to issue");
bName = obj.nextLine();
System.out.println("enter your name :");
name = obj.nextLine();
for (BookInfo obj2 : l1) {
if (obj2.getBookName().equals(bName)) {
obj2.issueBook(name);
}
}
break;
case 3:
System.out.println("enter the name of the book you want to return");
bName = obj.nextLine();
for (BookInfo obj2 : l1) {
if (obj2.getBookName().equals(bName)) {
obj2.returnIssuedBooks();
}
}
break;
case 4:
isTrue = false;
break;
default:
throw new Exception();
}
}catch(Exception e)
{
System.out.println("enter the correct input");
}
}
}
}
this is the following output
welcome to the Library Management System
choose from the options below :
press 1 for adding the book
press 2 for issuing the book
press 3 for returning the issued book
press 4 to exit
1
enter the name of the book :
enter the author of the book
That's because of the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline.
There are two options to resolve this issue,
1. Read the input through Scanner.nextLine and convert your input to the proper format you need
Scanner obj = new Scanner(System.in);
int choice = Integer.parseInt(obj .nextLine());
2. Add Scanner.nextLine call after each Scanner.nextInt
Scanner obj = new Scanner(System.in);
int choice = = obj.nextInt();
obj.nextLine();

How can I display the values that I input using instantiation?

How to modify the code in else if so that whatever I input in if will be displayed in the condition 2?
import java.util.*;
public class REPORTS
{
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname,Studentcourse,Studentlevel,equipmentname,reservationdate,returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
EQUIPMENT equip;
RESERVATION reserve;
Scanner in = new Scanner(System.in);
int x = choices();
if(x==1)
{
System.out.println("Enter Student ID:");
Studentid=in.nextInt();
in.nextLine();
System.out.println("Enter Student Name:");
Studentname=in.nextLine();
System.out.println("Enter Student Course:");
Studentcourse=in.nextLine();
System.out.println("Enter Student Level:");
Studentlevel=in.nextLine();
stud.setID(Studentid);
stud.setName(Studentname);
stud.setCourse(Studentcourse);
stud.setLevel(Studentlevel);
}
else if(x==2)
{
stud.display();
}
}
I'm thinking of using a looping but I dont know how to properly loop in order for me to fetch the data that is input by the user in the if statement.
I changed my if else to switch and tried a while loop. But the program runs endlessly and instead of displaying what I input it keeps asking for student name:
while(x!=7)
{
switch(x)
{
case 1:
{
stud.getData();
choices();
break;
}
case 2:
{
stud.display();
break;
}
}
}
A few starting points:
public static void main(String[]args)
{
int Studentid,equipid,quantity,studentid,equipid1;
String Studentname, Studentcourse, Studentlevel, equipmentname,
reservationdate, returndate;
STUDENT stud=new STUDENT(1234,"abc","abc","abc");
...
Rename your STUDENT class to Student. Also, you don't need all these local variables, they just make your code harder to read.
Provide a default constructor for Student
public static void main(String[]args)
{
Student stud=new Student(); // call the default constructor, don't enter bogus data
Scanner in = new Scanner(System.in);
int x = choices();
while (x != 7) {
switch(x) {
case 1:
System.out.println("Enter Student ID:");
stud.setID(in.nextInt());
in.nextLine();
System.out.println("Enter Student Name:");
stud.setName(in.nextLine());
System.out.println("Enter Student Course:");
stud.setCourse(in.nextLine());
System.out.println("Enter Student Level:");
stud.setLevel(in.nextLine());
break;
case 2: stud.display(); break;
}
// this must be inside the loop!!
x = choices();
}
}

Taking user input using an employee class, storing it into an array and displaying in main method- Java

I am new to programming and have spent last number of days trying to take user input, store it in an arraylist and then output the specific details. I would really appreciate someone shining some light on where I'm going wrong. I cant seem to be able to access the input from the employee class and store it in the arraylist in the main Method.
Thanks.
public class OctEmployeeArray{
public void menu(){
boolean breakOut= false;
while(breakOut == false){
System.out.println("=====================================");
System.out.println("=====================================");
System.out.println("EMPLOYEE HOLIDAY ENTITLEMENT PROGRAM");
System.out.println("Please chose the appropriate option: ");
System.out.println("=====================================");
System.out.println("=====================================");
System.out.println("1) Enter new employee details:");
System.out.println("2) Display the employee average age:");
System.out.println("3) Display information on specific employee:");
System.out.println("4) Display all database accounts:");
System.out.println("5) Exit the program:");
System.out.println("=====================================");
Scanner in = new Scanner(System.in); //scanner assigned to 'in'
String choice = in.nextLine(); //user input stored in choice
switch (choice){
case "1": System.out.println("You chose the 'add employee' input");
Employee e1= new Employee();
e1.addEmployee();
break;
case "2":
System.out.println("You chose the b input");
break;
case "3":
System.out.println("You chose the c input");
//searchspecficEmployee();
break;
case "4":
System.out.println("You chose the 'display all' input");
//displayAll();
break;
case "5":
System.out.println("You chose to Exit.");
breakOut= true;
break;
default:
System.out.println("The input is not accurate");
break;
}
}
}
public class Employee {
private String staffName;
private int staffNumber;
private int staffAge;
private int yearStarted;
private String role;
public Employee(String staffName, int staffAge, int yearStarted, int staffNumber, String role){
this.staffName= staffName;
this.staffNumber= staffNumber;
this.staffAge= staffAge;
this.yearStarted= yearStarted;
this.role= role;
}
public Employee(){
}
public int getAge(){
return staffAge;
}
public String getName(){
return staffName;
}
public int getStaffNum(){
return staffNumber;
}
public int getStartYear(){
return yearStarted;
}
public Employee addEmployee(){//this asks the new employee questions, saves them in a employee object called e
Scanner in= new Scanner(System.in);
//Employee d= new Employee();
System.out.println("Please enter your Full name:");
String name = in.nextLine();
System.out.println("Please enter your age:");
int age= Integer.parseInt(in.nextLine());
System.out.println("Please enter your staff number:");
int staffNum= Integer.parseInt (in.nextLine());
System.out.println("Please enter year of current employment:");
int startYear=Integer.parseInt(in.nextLine());
System.out.println("Please enter role employment:");
String role=in.nextLine();
Employee e= new Employee(name, age, startYear, staffNum, role);// puts all the varibles and puts them inside e and returns it
return e;
}
}
public static void main(String[] args) {
ArrayList<Employee> alist= new ArrayList();// arraylist created to save employee objects
OctEmployeeArray o= new OctEmployeeArray();// object created for access to main menu
o.menu();//display main menu
Employee em= new Employee();// create employee object to access add employee method
alist.add(em.addEmployee);
for(Employee count : alist){
System.out.println(count.getName());
System.out.println(count.getStaffNum());
}
}
}
You are creating a new Employee instance inside the addEmployee() method. That's not wrong. But the fact this method is inside the Employee class is semantically nonsense (sorry) - and i think it's also why it doesn't work (It's a coincidence. Unfortunately a lot of semantic nonsense does work.).
What you should do is to remove the addEmployee() method from the Employee class and move it to the class holding your Employee array. Don't create new Employee instances inside the Employee class.

add method continues to add even when it exceeds the arraylist's size

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.

Categories