I have to make a program using inheritance and I want to print out what I have inputted. But when I run the program, no error founded, it just gives me an empty blank space. What is wrong with my code? Did I make a mistake in calling the variable?
This is my main code:
package labweek7;
import java.awt.Menu;
import java.util.Scanner;
import java.util.Vector;
public class Main {
Vector<String> menu =new Vector<>();
Scanner scan = new Scanner(System.in);
//Employee emp;
Employee emp = new EmployeeFullTime(null, 0, null, null);
Employee emps = new EmployeePartTime(null, 0, null, null);
EmployeeFullTime ft = new EmployeeFullTime(null, 0, null, null);
EmployeePartTime pt = new EmployeePartTime(null, 0, null, null);
public Main() {
int choice = 0;
int pay;
int time;
int salary;
do{
System.out.println("ABC EMPLOYEE DATA");
System.out.println("=================");
System.out.println("1. Add Employee");
System.out.println("2. View Employee");
System.out.println("3. Resign");
System.out.println("4. Exit");
System.out.print("Choice: ");
choice = scan.nextInt();
scan.nextLine();
switch(choice){
case 1:
String name = "";
do{
System.out.print("Input employee name[must be more than 3 characters]: ");
name = scan.next();
}while(! (name.length()>=3));
emp.empName.add(name);
int age;
do{
System.out.print("Input employee age[>=17]: ");
age = scan.nextInt();
}while(!(age>=17));
emp.empAge.add(age);
String role = "";
do{
System.out.print("Input employee role[Assistant | Programmer](Case Sensitive): ");
role = scan.next();
}while(!(role.equals("Assistant") || (role.equals("Programmer"))));
emp.empRole.add(role);
String type = "";
do{
System.out.print("Input employee type[PartTime | FullTime](Case Sensitive): ");
type = scan.next();
}while(!(type.equals("PartTime")|| type.equals("FullTime")));
emp.empType.add(type);
if(type.equals("PartTime")){
emp = new EmployeePartTime(name, age, role, type);
do{
System.out.print("Input pay per hour[>=10000]: ");
pay = scan.nextInt();
}while(!(pay>=10000));
pt.pays.add(pay);
do{
System.out.print("Input working hour per week[>0]: ");
time = scan.nextInt();
}while(!(time>0));
pt.hours.add(time);
}
else{
emps = new EmployeeFullTime(name, age, role, type);
do{
System.out.print("Input base salary[>=10000]: ");
salary = scan.nextInt();
}while(!(salary>=10000));
ft.salary.add(salary);
}
String status = "active";
System.out.println("Success insert employee data");
System.out.println("");
System.out.println("Please any key to continue...");
scan.nextLine();
break;
case 2:
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
}
else
{
view();
}
}
}while(choice!=4);
}
void view(){
//for(int i=0; i<menu.size(); i++){
System.out.println("Employee no.");
if(emp.empType.equals("FullTime")){
System.out.println("Full Time Employee");
System.out.println("===================");
System.out.println("Status: ");
for(int j=0; j<emps.empName.size(); j++){
// if(emps == null){
// }
// else{
System.out.println("Name: " + emps.empName.get(j));
// }
//System.out.println("Name: " + emps.empName.get(j));
}
for(int m=0; m<emp.empAge.size(); m++){
System.out.println("Age: " + emps.empAge.get(m));
}
for(int n=0; n<emps.empRole.size(); n++){
System.out.println("Role: " + emps.empRole.get(n));
}
for(int o=0; o<ft.salary.size(); o++){
System.out.println("Base salary per month: " + ft.salary.get(o));
}
System.out.println("");
}
else
{
System.out.println("Part Time Employee");
System.out.println("===================");
// System.out.println("Status: " );
// System.out.println("Name: " + emp.empName.get(i));
// System.out.println("Age: " + emp.empAge.get(i));
// System.out.println("Role: " + emp.empRole.get(i));
// System.out.println("Pay per hour: "+pt.pays.get(i));
// System.out.println("Working hour per week: "+pt.hours.get(i));
// System.out.println("Salary per month: "+ pt.pays.get(i) * pt.hours.get(i));
//
}
System.out.println("\n\n");
System.out.println("Press any key to continue...");
}
void resign(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main();
}
}
This is my parent class:
package labweek7;
import java.util.Vector;
public abstract class Employee {
public String name;
public int age;
public String role;
public String type;
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
public Employee(String name, int age, String role, String type) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.role = role;
this.type = type;
}
}
This is my child class 1 :
package labweek7;
import java.util.Vector;
public class EmployeePartTime extends Employee{
int pay;
int hour;
Vector<Integer> pays = new Vector<>();
Vector<Integer> hours = new Vector<>();
public EmployeePartTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
This is my child class 2 :
p
ackage labweek7;
import java.util.Vector;
public class EmployeeFullTime extends Employee{
int gaji;
Vector<Integer> salary = new Vector<>();
public EmployeeFullTime(String name, int age, String role, String type) {
super(name, age, role, type);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
Did I make mistake in the for loop? Why does my code not printing the inputted items? Any help is appreciated. Thank You.
I have debugged your code in my eclipse work-space.
I'm able to insert the employee data successfully as shown below:
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 1
Input employee name[must be more than 3 characters]: asfds
Input employee age[>=17]: 14
Input employee age[>=17]: 18
Input employee role[Assistant | Programmer](Case Sensitive): Assistant
Input employee type[PartTime | FullTime](Case Sensitive): PartTime
Input pay per hour[>=10000]: 20000
Input working hour per week[>0]: 12
Success insert employee data
But after selecting second option for View Employee I was getting empty output.
ABC EMPLOYEE DATA
=================
1. Add Employee
2. View Employee
3. Resign
4. Exit
Choice: 2
There is no employee data in the list
After debugging it a bit more I came across a condition in Main()
boolean ans = emp.empName.isEmpty();
if(ans == true){
System.out.println("There is no employee data in the list");
} else {
view();
}
The emp.empName is empty here. All Vectors are empty which belong to Employee class.
Vector<String> empName = new Vector<>();
Vector<Integer> empAge = new Vector<>();
Vector<String> empRole = new Vector<>();
Vector<String> empType = new Vector<>();
As a workaround I just changed emp.empName.isEmpty() to emp.name.isEmpty() to resolve the problem. I hope this helps you in identifying the problem.
Related
I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}
I'm still a beginner so cut me some slack.
I have 5 class but only 2 are needed for my question. This is a question in my assignment so no need to be too particular. I have been tasked to make a java terminal system to store and display lecturer (part time and full time), lecturers address, and classes information.
My code will check if there is a part time lecturer to display (this includes the address object since it is part of the lecturer information) . If not, it will prompt the user to enter the part time lecturer details. When entering the part time details I am not sure on how to enter the address without recreating the object.
here is my codes
This is part time class
public class PartTime extends Lecturer{
private double hourlyRate;
private int hoursWorked;
//classR = class resposible
private ClassInfo classR;
PartTime(){
classR = new ClassInfo();
}
PartTime(String staffNo, String name, int contactNo, int noClasses, Address add, double hourlyRate, int hoursWorked, ClassInfo classR){
super(staffNo, name, contactNo, noClasses, add);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
this.classR = classR;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public int getHoursWorked(){
return this.hoursWorked;
}
public void setHourlyRate(double newHourlyRate){
this.hourlyRate = newHourlyRate;
}
public void setHoursWorked(int newHoursWorked){
this.hoursWorked = newHoursWorked;
}
public void displayClassR(){
System.out.println("Class No : "+ classR.getClassNo());
System.out.println("Subject Name : "+ classR.getSubjectName());
System.out.println("Number Of Students : "+ classR.getNoStudents());
System.out.println("Start Date : "+ classR.getStartDate());
System.out.println("End Date : "+ classR.getEndDate());
}
}
This is lecturer class
public class Lecturer{
private String staffNo, name;
private int contactNo, noClasses;
private final Address add;
Lecturer(){
add = new Address();
}
Lecturer(String staffNo, String name, int contactNo, int noClasses, Address add){
this.staffNo = staffNo;
this.name = name;
this.contactNo = contactNo;
this.noClasses = noClasses;
this.add = add;
}
public String getStaffNo(){
return this.staffNo;
}
public String getName(){
return this.name;
}
public int getContactNo(){
return this.contactNo;
}
public int getNoClasses(){
return this.noClasses;
}
public void displayAdd(){
System.out.println("Unit Number : "+ add.getUnitNo());
System.out.println("Street Name : "+ add.getStreetName());
System.out.println("City : "+ add.getCity());
System.out.println("Postcode : "+ add.getPostcode());
}
public void setStaffNo(String newStaffNo){
this.staffNo = newStaffNo;
}
public void setName(String newName){
this.name = newName;
}
public void setContactNo(int newContactNo){
this.contactNo = newContactNo;
}
public void setNoClasses(int newNoClasses){
this.noClasses = newNoClasses;
}
public void setAdd(String newUnitNo, String newStreetName, String newCity, int newPostcode){
add.setUnitNo(newUnitNo);
add.setStreetName(newStreetName);
add.setCity(newCity);
add.setPostcode(newPostcode);
}
}
You can ignore the menu part
import java.io.*;
class Main{
static Scanner scan = new Scanner(System.in);
static Address add = new Address();
static ClassInfo classI = new ClassInfo();
static FullTime ft = new FullTime();
static PartTime pt = new PartTime();
static String staffNo, name, classNo, subjectName, startDate, endDate, unitNo, streetName, city;
static int contactNo, noClasses, hoursWorked, noStudents, postcode, select;
static double annualSalary, hourlyRate;
public static void main(String[] args){
//menu looping
do{
System.out.println("=======================");
System.out.println("| Main Menu |");
System.out.println("| Select an option |");
System.out.println("| 1. Lecturer |");
System.out.println("| 2. Class Info |");
System.out.println("| 3. File Actions |");
System.out.println("| 0. Exit |");
System.out.println("=======================");
select = scan.nextInt();
switch(select){
case 1:
lecturerMenu();
break;
case 2:
classInfoMenu();
break;
case 3:
fileMenu();
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Error please select again");
}
}while(select !=0);
}
Eventually it will make its way to the part where the user adds part time lecturer data. the set is incomplete as i didnt know how to do the addresspart
public static void newPartTime(){
System.out.println("Enter Part Time Lecturer Details");
System.out.print("Enter Staff Number: ");
scan.nextLine();
staffNo = scan.nextLine();
System.out.print("Enter Name: ");
name = scan.nextLine();
System.out.print("Enter Contact Number: ");
contactNo = scan.nextInt();
System.out.print("Enter Hourly Rate: ");
hourlyRate = scan.nextDouble();
System.out.print("Enter Hours Worked: ");
hoursWorked = scan.nextInt();
System.out.println("Enter Address");
System.out.print("Enter Unit Number: ");
scan.nextLine();
unitNo = scan.nextLine();
System.out.print("Enter Street Name: ");
streetName = scan.nextLine();
System.out.print("Enter City: ");
city = scan.nextLine();
System.out.print("Enter Postcode: ");
postcode = scan.nextInt();
scan.nextLine();
if(classI == null){
System.out.println("There is no class available. Please add a new class");
newClassInfo();
}else{
pt.setStaffNo(staffNo);
pt.setName(name);
pt.setContactNo(contactNo);
pt.setNoClasses(noClasses);
pt.set
}
}
}
Normally I would do this for my declaration:
static FullTime ft = new FullTime(var1, var1 ,var3, address);
Am I able to recreate the object or should I just add a method for set address in part time?
You could create an Object of the address class and set values to that and then set the object into your part time object.
I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!
In my program, I want to transfer credits between two person. All of the info I have added in the arrayList. Each person is given an ID.
To make transaction, user have to enter ID.
The withdraw amount enterd by the user must be subtracted from the particular account and eventually that amount must be added with another particular account, depending on the ID chosen by user. How to do that?
Basically, I don't know how to check the amount/credit with the matching ID, and then performing arithmetic task within that specific person's amount.
Actually the part I am concentrating on is switch (option2) in my code.
This is my code I am working on.
AboutPerson:
public static void main(String[] args) {
String name;
int id;
int option1;
int option2;
double credit;
int withdraw_id;
double withdraw_amount;
double dep_id;
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "3. Transfer credits\n"//need help here
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
case 3:
//transfer credit
System.out.println("To transfer credit between two persons enter 1");//working with this one
System.out.println("To transfer credit within the same persons enter 2");//not focusing on that now
option2 = input.nextInt();
input.nextLine();
switch (option2) {
case 1:
System.out.println("Enter the ID of the person you want to withdraw amount from: ");
withdraw_id = input.nextInt();
System.out.println("Enter withdraw amount: ");
withdraw_amount = input.nextDouble();
//subtract that credit from that account
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
//the amount has been withdrawn will be deposited
//add that credit
System.out.println("Done!\tTo print them out out choose option 2");
break;
}
}
}
}
PersonInfo:
package aboutperson;
public class PersonInfo {
private String name;
private int id;
private double credit;
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(double credit) {
this.credit = credit;
}
#Override
public String toString() {
return name + "\t\t" + id + "\t\t" + credit;
}
}
First add getCredit and getID methods to PersonInfo:
public double getCredit() {
return this.credit;
}
public int getID() {
return this.id;
}
And then simply exchange it between the two accounts:
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
input.nextLine();
System.out.println("Enter your ID: ");
withdraw_id = input.nextDouble();
input.nextLine();
System.out.println(": ");
withdraw_amount = input.nextDouble();
input.nextLine();
PersonInfo fromPerson = null;
PersonInfo toPerson = null;
//find PersonInfo objects from list:
for (PersonInfo pi : info) {
if (pi.getID() == dep_id) {
toPerson = pi;
break;
}
}
for (PersonInfo pi : info) {
if (pi.getID() == withdraw_id) {
fromPerson = pi;
break;
}
}
if (fromPerson == null || toPerson == null) {
System.out.println("Wrong IDs."); //maybe do something more user friendly here
break;
}
if (withdraw_amount > fromPerson.getCredit()) {
System.out.println("notify of error");
break;
}
fromPerson.setCredit(fromPerson.getCredit() - withdraw_amount);
toPerson.setCredit(toPerson.getCredit() + withdraw_amount);
System.out.println("Done!\tTo print them out out choose option 2");
Instead of storing PersonInfo in List, use Map where you can use key as id and value as PersonInfo itself. so it will be like:
Map<Integer, PersonInfo> info = new HashMap<Integer, PersonInfo>();
...
personInfo.setCredit(input.nextDouble());
perdonIdInfoMap.put(personInfo.getId(), personInfo);
Then when you have two id's get the info from map like:
personInfoFrom = perdonIdInfoMap.get(id1);
personInfoTo = perdonIdInfoMap.get(id2);
//now deduct from one and add to other like personInfoFrom.setCredit(personInfoFrom.getCridit() + personInfoTo.getCredit());
You can iterate over the list and check:
for(PersonInfo person: info){
if(person.getId().equals(searchedId)){
/* here you can do operation on that person*/
/* Printing the balance */
System.out.println("Balance: " + person.getCredit());
/* Adding or subtracting money*/
person.setCredit(person.getCredit() + ammount);
/* Other stuff*/
}
}
Or you could use a Map as SMA suggested
I have created a simple program which outputs student details. Ideally I would like to give the user an option to add both courses. Will this require a lot of messing about changing code? If not can someone help?
class Student
{
public static void main(String[]args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which course do you want to add the student to? .......Literacy or Numeracy ");
courseName = input.next();
TheStu [x] = new Stu (surName, foreName, age, telephone, courseName);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled on the " + TheStu[y].getcourseType() + " Course.");
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String courseType;
Stu (String s, String f, int a, int p, String c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseType = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String getcourseType()
{
return courseType;
}
}
If you want something pretty basic, you could change your courses into a String array so you could store both courses. Also when asking the user to input a course name, you could have an ALL option, so you automatically register the student for all courses. See below for a slightly modified version of your code :
import java.util.Scanner;
class Student
{
public static void main(String[] args)//The main method; starting point of the program.
{
Scanner input = new Scanner(System.in);
String surName, foreName, courseName;
String[] courses = new String[]{};
int age,telephone;
System.out.println("\t\t\t***********************************************");
System.out.println("\t\t\tWelcome to the Mobile College's Student Records");
System.out.println("\t\t\t***********************************************");
System.out.println("\nHow many students would you like to add?");
int noStudents = input.nextInt();
Stu [] TheStu = new Stu [noStudents];
for (int x = 0; x < noStudents; x++)
{
System.out.println("Please enter Surname: ");
surName = input.next();
System.out.println("Please enter Forename: ");
foreName = input.next();
System.out.println("Please enter Age: ");
age = input.nextInt();
System.out.println("Please enter Telephone No. ");
telephone = input.nextInt();
System.out.println("Which courses do you want to add the student to? .......Literacy or Numeracy or both ");
courseName = input.nextLine();
// change to either upper case or lower case for easy treatment
courseName = courseName.toUpperCase();
// Also verify that the user entered a valid course name
if(courseName.equals("LITERACY")){
courses = new String[]{"LITERACY"};
} else if(courseName.equals("NUMERACY")){
courses = new String[]{"NUMERACY"};
} else if(courseName.equals("BOTH")){
courses = new String[]{"LITERACY", "NUMERACY"};
} else{
System.out.println("Error : You entered an invalid option.... \n This student won't be registered for any courses");
}
TheStu [x] = new Stu (surName, foreName, age, telephone, courses);
}
for (int y = 0; y < noStudents; y++)
{
System.out.println("\t\t\t***********************************************");
System.out.println ("\t\t\tName: " + TheStu[y].getfName() + " " + TheStu[y].getsName());
System.out.println ("\t\t\tAge: " + TheStu[y].getstuAge());
System.out.println ("\t\t\tTelephone No. 0" + TheStu[y].getphone());
System.out.println ("\t\t\tEnrolled in the following courses : ");
courses = TheStu[y].getcourseTypes();
for(int i = 0; i < courses.length; i++){
System.out.println(courses[i]);
}
if(courses.length < 1){
System.out.println("No Courses");
}
System.out.println("\t\t\t***********************************************");
}
}// end of class
}
class Stu
{
private String sName;
private String fName;
private int stuAge;
private int phone;
private String[] courseTypes;
Stu (String s, String f, int a, int p, String[] c)
{
sName = s;
fName = f;
stuAge = a;
phone = p;
courseTypes = c;
}
String getsName()
{
return sName;
}
String getfName()
{
return fName;
}
int getstuAge()
{
return stuAge;
}
int getphone()
{
return phone;
}
String[] getcourseTypes()
{
return courseTypes;
}
}
I tried as much as possible not to make any serious changes to your code as i assume you're a beginner, but there are a lot of changes you could make to improve your code. Happy Coding :)
When you ask for the course name, keep asking until they have entered in a sentinal value. Inside Stu keep an List<String> courseTypes. Store the entered courses in courseTypes. Also, you may want to add a set value to some of the fields in Stu. What if their phone number changes?