Java passing of methods - java

HI My prof said this about my code
Please Help me I do not get what he wanted me to do with my code
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
Please Help me I do not get what he wanted me to do with my code
This is an address book containing 3 classes and this is one of the class that i really had a problem with
import java.util.Scanner;
public class AddressBookApp {
private static Scanner dataReader;
private static AddressBook book;
// TODO Address Book App
public static void main(String[] args) {
book = new AddressBook(10);
dataReader = new Scanner(System.in);
boolean lContinue = true;
while (lContinue) {
switch (Character.toUpperCase(menu())) {
case '1': addBookEntry(); break;
case '2': deleteEntry(); break;
case '3': viewAllEntries(); break;
case '4': editEntry(); break;
case '5': searchEntryByName(); break;
case '6': searchEntryByRecord(); break;
case 'X':
lContinue = false;
break;
default:
System.out.println("\nInvalid Menu option");
}
}
System.out.println("\nEnd of program...");
}
public static char menu() {
char choice;
System.out.println("\nAddressBook Menu");
System.out.println("1. Add Entry");
System.out.println("2. Delete Entry");
System.out.println("3. View all Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Search Entry By Name");
System.out.println("6. Search Entry By Record Number");
System.out.println("X. Exit Program");
System.out.print("\nSelect Menu Option: ");
choice = dataReader.nextLine().charAt(0);
return choice;
}
public static AddressBookEntry getEntryDetails(AddressBookEntry entry) {
if( entry == null ) {
entry = new AddressBookEntry();
}
System.out.print("\nName : "); entry.setName(dataReader.nextLine());
System.out.print("Address : "); entry.setAddress(dataReader.nextLine());
System.out.print("Phone No.: "); entry.setTelNo(dataReader.nextLine());
System.out.print("Email : "); entry.setEmailAdd(dataReader.nextLine());
return entry;
}
public static void addBookEntry() {
AddressBookEntry entry = getEntryDetails(null);
if( entry != null ) {
book.addAddressBookEntry(entry);
}
}
public static void editEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
getEntryDetails(AddressBookEntry)
- System.out.println("Name: " + addent.getName());
- System.out.println("Edit Name: ");
- String name = datainput.next();
- addent.setName(name);
- System.out.println("Edit Address: ");
- String address = datainput.next();
- addent.setAddress(address);
- System.out.println("Edit EmailAdd: ");
- String emailAdd = datainput.next();
- addent.setEmailAdd(emailAdd);
- System.out.println("Edit TelNo: ");
- String telNo = datainput.next();
- addent.setTelNo(telNo);
displayEntry(addent, recnumb);
// TODO: edit a single record entry
//System.out.println("\nUnder construction....");
}
public static void searchEntryByRecord() {
try {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
System.out.println("Name: " + addent.getName());
System.out.println("Address:" + addent.getAddress());
} catch (Exception NullPointerException) {
// TODO Auto-generated catch block
return;
}
// TODO: search an entry using its record no.
// display "record not found" if such record does not exist.
// Display all its entry.
// Hint: use the method "findAddressBookEntryByRecordNo()"
// from the AddressBook class
//System.out.println("\nUnder construction....");
}
public static void deleteEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number to delete: ");
int recnumb = datainput.nextInt();
if (book.deleteAddressBookEntry(recnumb)) {
System.out.println("Deleted successfully.");
} else {
System.out.println("Record not found");
}
}
// TODO: delete an entry using its record no.
// display "record not found" if such record does not exist.
// Hint: use the method "deleteAddressBookEntry()"
// from the AddressBook class
// display a single record
public static void displayEntry(AddressBookEntry entry, int recNo) {
System.out.println("\nRecord No. " + recNo);
System.out.println("Name : " + entry.getName());
System.out.println("Address : " + entry.getAddress());
System.out.println("Phone No.: " + entry.getTelNo());
System.out.println("Email : " + entry.getEmailAdd());
}
// Search all entries containing name search criteria
public static void searchEntryByName() {
System.out.print("\nSearch[Name]: ");
// ensure no extraneous space and search criteria all in lowercase
String name = dataReader.nextLine().trim().toLowerCase();
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
for( int i = 0; i < list.length; i++ ) {
// compare search criteria with every entry
if(list[i]!=null && list[i].getName().toLowerCase().contains(name)) {
displayEntry(list[i],i+1);
}
}
System.out.println("No more records follow...");
}
public static void viewAllEntries() {
int validRecords = 0;
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
if( list.length == 0) {
System.out.println("\nList empty...");
}
for( int i = 0; i < list.length; i++ ) {
if( list[i] != null ) {
displayEntry(list[i],++validRecords);
}
}
System.out.println("No more entries to follow...");
}
}

Remove all lines which start with "-" and use this instead:
getEntryDetails( addent );

Related

How can i get back to main menu and entering any panel after exiting from admin panel?

I'm building a university management system where admin can log in, add student, department, 2ndly there is a faculty panel and lastly, there is a student panel where they can set course. But I've been facing some problems after adding a new student through the admin panel. The problem is if want to exit from the admin panel the whole program close. Is there any solution that if I exit from admin panel I should get back to main menu where i can enter in any panel again. there is one more problem if i tried to remove a student from registered it shows not found. Can anyone help me through this problem?
Here is my code MainActivity.java
import java.util.Scanner;
import mainpanel.*;
import interfacepart.*;
//import transactionpart.*;
public class MainActivity{
public static void main(String args[]){
boolean flag = true;
Student[] student1 = new Student[2000];
Scanner sc = new Scanner(System.in);
Admin a = new Admin("Admin", "1234");
System.out.println("**********Welcome to University Management*******");
//do {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Adming Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int choose = sc.nextInt();
sc.nextLine();
if(choose == 1){
Scanner ac = new Scanner(System.in);
System.out.println("**********Welcome to Admin panel*******");
System.out.println("Please enter the userName: ");
String user = sc.nextLine();
System.out.println("Please enter the password: ");
String password = sc.nextLine();
if("Admin".equals(user) && "1234".equals(password)){
do{
System.out.println("Login successful");
System.out.println ( "**** 1. add students and department *****");
System.out.println ( "**** 2. remove students *****");
System.out.println ( "**** 3. student Information *****");
//System.out.println ( "**** n 5, print student *****");
System.out.println ( "**** 4, exit the system *****");
int sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Enter the number of student you want to add: ");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i<num; i++) {
if (student1[i] == null) {
System.out.println("Enter the deptname: ");
String depntName = sc.nextLine();
System.out.println("Enter the deptId: ");
String depntId = sc.nextLine();
System.out.println("Enter the totalCredit: ");
int totalCredit = sc.nextInt();
sc.nextLine();
Department cs = new Department(depntName, depntId, totalCredit);
Scanner mc = new Scanner(System.in);
System.out.println("Enter the StudentName: ");
String StudentName = mc.nextLine();
System.out.println("Enter the StudentId: ");
String StudentId = mc.nextLine();
System.out.println("Enter the StudentAge: ");
String StudentAge = mc.nextLine();
System.out.println("Enter the email: ");
String email = mc.nextLine();
System.out.println("Enter the bloodGroup: ");
String bloodGroup = mc.nextLine();
System.out.println("Enter the phoneNumber: ");
String phoneNumber = mc.nextLine();
System.out.println("Enter the Address: ");
String Address = mc.nextLine();
mc.nextLine();
Student s1 = new Student(StudentName,StudentId,StudentAge,email,bloodGroup,phoneNumber,Address);
student1[i] = s1;
a.addNewRegister(student1[i]);
a.addNewDepartment(cs);
student1[i].SetAdmin(a);
student1[i].SetDeparment(cs);
cs.addNewRegister(student1[i]);
//break;
}
else{
System.out.println ( "Number of students in full");
break;
}
}
break;
case 2:
boolean isStudentRegistered = false;
System.out.println("Please Enter the Id you want to remove: ");
Scanner newCheck = new Scanner(System.in);
String stdId = newCheck.nextLine();
for(Student total : student1){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}if(!isStudentRegistered){
System.out.println("No student found");
}
break;
case 3:
for(int i=0; i<1; i++){
a.showRegisteredInfo();
break;
}
break;
case 4:
System.exit(0);
//flag = false;
//break;
//continue;
break;
default:
break;
}
}while (true);
} else {
//flag = true;
System.out.println ( "Login failed please re-enter:");
}
}
else if(choose == 3){
Scanner std = new Scanner(System.in);
System.out.println ( "Welcome to Student Panel*******");
System.out.println("Please enter the StudentId: ");
String userId = std.nextLine();
System.out.println("Please enter the password: ");
String password = std.nextLine();
do{
for(Student total : student1){
if(total != null){
if(total.getId() == userId){
System.out.println("*********Welcome to university Portal***");
//isStudentRegistered = true;
total.showInfo();
}else{
System.out.println("You are not registered yet");
}
}
}
}while(true);
}
else{
System.out.println ( "Login failed please re-enter:");
}
/*} while (true);
}*/
}
}
Admin.java
package mainpanel;
public class Admin{
protected String userName;
protected String passWord;
Student[] addNewStudent;
Department[] department;
Courses[] courses;
int totalRegisterCount;
int totalDepartmentCount;
int totalCourseCount;
public Admin(){
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public Admin(String userName, String passWord){
this.userName = userName;
this.passWord = passWord;
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public void SetUserName(String userName){
this.userName = userName;
}
public String GetUserName(){
return userName;
}
public void SetpassWord(String passWord){
this.userName = userName;
}
public String GetPassword(){
return passWord;
}
public void addNewRegister(Student NewStudent){
addNewStudent[totalRegisterCount++] = NewStudent;
}
//public void removeNewStudent(Student removeNewStudent){
//}
public void addNewDepartment(Department dept){
department[totalDepartmentCount++] = dept;
}
public void addNewCourse(Courses crs){
courses[totalCourseCount++] = crs;
}
public void showDepartmentInfo(){
for(int i=0; i<totalDepartmentCount; i++){
department[i].showInfo();
}
}
public void showRegisteredInfo(){
for(int i=0; i<totalRegisterCount; i++){
addNewStudent[i].showInfo();
//addNewStudent[i].AllCourseInfo();
}
}
public void searchStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total.showInfo();
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
/*
public void removeStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
*/
}
//courses[num].showInfo();
/*public void showCourseInfo(){
for(int i=0; i<totalCourseCount; i++){
courses[i].showInfo();
}
}
*/
Approach 1 - Not recommended
You can either have a loop surrounding the core functionality of your application and break out of any internal loops to go back to the beginning of the core loop.
Approach 2 - Recommended
You could refrain from using a core loop and refactor your code such that each menu interaction is a separate function.
Each function would present the user with a specific menu and depending on the user's input another function would be called for the next menu. Generally speaking, you would not require any loops to keep the application running.
This would reduce the complexity and confusion of your code and make it much easier to expand the application with new features without needing to concern yourself with where to place code within the loop.
I recommend reading up on SOLID design principles to get an idea of how best to structure code. Here is an example article. This answer and example code is not meant to be a full representation of SOLID design and I would recommend that you strongly consider using interfaces and separate classes for each distinct part of the system and not having all the code in the MainActivity class.
An example of a function-based approach would be as follows.
I mainly focussed on the Main Menu and Admin Menu. The principle can be applied across the entire application.
Scanner sc = new Scanner(System.in);
private void displayMainMenu() {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Admin Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1:
displayAdminLoginMenu();
break;
case 2:
displayFacultyLoginMenu();
break;
case 3:
displayStudentLoginMenu();
break;
default:
// Display the main menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayMainMenu();
break;
}
}
private void displayAdminLoginMenu() {
// Perform login operation here
// After successful login display admin options menu
displayAdminOptionsMenu();
}
private void displayFacultyLoginMenu() {
}
private void displayStudentLoginMenu() {
}
private void displayAdminOptionsMenu() {
System.out.println("**** 1. add students and department *****");
System.out.println("**** 2. remove students *****");
System.out.println("**** 3. student Information *****");
System.out.println("**** 4, return to main menu *****");
System.out.println("**** 5, exit the system *****");
int input = sc.nextInt();
switch (input) {
case 1:
// Call function for option 1.
break;
case 2:
// Call function for option 2.
break;
case 3:
// Call function for option 3.
break;
case 4:
displayMainMenu();
break;
case 5:
exitApplication();
break;
default:
// Display the admin menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayAdminOptionsMenu();
break;
}
}
private void exitApplication() {
System.exit(0);
}
These are not necessarily the only options available, but they are what I could think of at the moment.

Search arraylist of objects does not work

I have been encountering a specific problem where only the first item in Arraylist is included when it comes to iterating each element in Arraylist (to search/to remove). That means that the second until n-1 iteams won't be found whenever I try to iterate.
Edited: currently improving my code.
You could try the following program. It is perfectly working only when adding the first record of the order: I can remove and search its values. However, when adding the second order: I can not remove and search its values, rather it is not found.
Source code
import java.util.*;
import java.io.*;
public class TestOrders {
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchElementException {
File afile = new File("order.txt");
FileOutputStream outFile = new FileOutputStream("order.txt");
ObjectOutputStream outStream = new ObjectOutputStream(outFile);
FileInputStream inFile = new FileInputStream("order.txt");
ObjectInputStream inStream = new ObjectInputStream(inFile);
//Create an arraylist of order
ArrayList<Order> theorder = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Order");
System.out.println("Please choose an option (1-5): ");
int choice = 0;
try {
while (choice != 5) {
//A list of options
System.out.println("\n1. Add a new order: ");
System.out.println("2. Search an order: ");
System.out.println("3. Compute sum of all orders:");
System.out.println("4. Remove an order: ");
System.out.println("5. Exit: ");
//prompt user
System.out.print("Pick a number: ");
if (scan.hasNextInt()) {
choice = scan.nextInt();
}
switch(choice) {
case 1:
addNewOrder(outStream, theorder);
break;
case 2:
searchOrder(outStream, inStream, theorder);
break;
case 3:
computeSum(afile, theorder);
break;
case 4:
removeOrder(outStream, inStream, theorder);
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Please enter from (1-5)");
}
}
} catch (IOException | InputMismatchException ex) {
System.out.println(ex);
} finally {
if (choice == 5) {
scan.close();
outStream.close();
inStream.close();
}
}
}
public static void addNewOrder(ObjectOutputStream outStream, ArrayList<Order> theorder) throws IOException {
Scanner input = new Scanner(System.in);
Order anorder = new Order();
System.out.print("Enter the order ID: ");
anorder.setOrderID(input.nextInt());
input.nextLine();
System.out.print("Enter the customer name: ");
anorder.setCustomerName(input.nextLine());
System.out.print("Enter the order (meal/drink): ");
anorder.setOrderType(input.nextLine());
System.out.print("Enter the order price: ");
anorder.setPrice(input.nextDouble());
if(theorder.size() <= 1000) {
theorder.add(anorder);
outStream.writeObject(anorder);
System.out.println("Order information saved.\n");
} else {
System.out.println("There is not enough space.");
}
}
public static void searchOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
Order o = new Order();
System.out.println("Please enter a customer ID: ");
int custID = input.nextInt();
for (Order or : theorder) {
if(or.getOrderID() == custID) {
System.out.println(or.toString());
break;
} else {
System.out.println("No matching record found");
break;
}
}
}
public static void computeSum(File aFile, ArrayList<Order> theorder) throws FileNotFoundException, IOException {
double sum = 0;
for (Order o : theorder) {
sum += o.getPrice();
}
sum = (double) Math.round(sum*100)/100;
System.out.println("The total sum of price for " + theorder.size() + " orders is " + sum);
}
public static void removeOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) {
Iterator<Order> iterator = theorder.iterator();
Scanner input = new Scanner(System.in);
System.out.println("Enter the order ID to remove: ");
int custID = input.nextInt();
while (iterator.hasNext()) {
Order anorder = iterator.next();
if(anorder.getOrderID() == custID) {
theorder.remove(anorder);
System.out.println(anorder.toString());
break;
} else {
System.out.println("Not found\n");
break;
}
}
for (Order o : theorder) {
System.out.println(o.toString());
}
}
}
Order class
import java.util.*;
import java.io.*;
public class Order implements Serializable {
private int orderID;
private String customerName;
private String orderType;
private double price;
public Order() {
}
public Order(int orderID, String customerName, String orderType, double price) {
this.orderID = orderID;
this.customerName = customerName;
this.orderType = orderType;
this.price = price;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOrderType() {
return this.orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return this.orderID + " " + this.customerName + " " + this.orderType + " " + this.price + "\n";
}
}
This part is where I am struggling. I had tried using iterator but it got the same result, second item cannot be iterated/found.
for (Order o : theorder) {
if(o.getOrderID() == orderIDSearch) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
What should I do to fix this problem? is there any way it can be solved?
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
There are several problems here:
First, removal of an element of a collection whilst iterating across the collection requires a different technique than you are using. Generally, modifying a collection in the midst of iteration will result in a ConcurrentModificationException.
Second, are multiple matches expected? If there is at most one match, the continue should be a break.
Third, one would expect the code to continue to following elements when a current element is not a match. That is, the break should be a continue, or better yet, should be removed entirely.
Fourth, its not clear that theorder.remove(orderIDSearch) will do anything, unless the collection type has a remove operation which takes a key value instead of an element value. For basic collection types (List, Set), the call won't do anything.
Here are two rewrites:
If the iterator supports remove:
Iterator<Order> orders = theorder.iterator();
boolean found = false;
while ( !found && orders.hasNext() ) {
if ( orders.next().getOrderID() == orderIDSearch ) {
found = true;
}
}
if ( found ) {
orders.remove();
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
If the iterator does not support remove, then:
boolean found = false;
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
found = true;
break;
}
}
if ( found ) {
theorder.remove(orderIDSearch);
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
Note that this relies on remove accepting a key as the parameter value.
You are breaking the loop in for search in else condition.
Why would you do that.. Remove the else part

Looping with ArrayList

I have this code that involves task to do with the ArrayList names
that includes functions like adding elements in the ArrayList, displaying the elements of the ArrayList, deleting an element in an ArrayList, editing an element in an ArrayList.
My question is when I add a new name in the ArrayList, when the code loops back and I want to view the elements in the ArrayList, it turns out empty.
import java.util.ArrayList;
import java.util.Scanner;
public class mainRunner {
public static void main(String[] args) {
String con;
do {
menuCaller();
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
} while (con.equalsIgnoreCase("y"));
}
public static void menuCaller() {
int choice;
ArrayList names = new ArrayList();
int firstIndex =0;
Scanner scan = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scaned = new Scanner(System.in);
System.out.println("Menu"
+"\n[1] Add Name"
+ "\n[2] Display All Record"
+ "\n[3] Delete a Record"
+ "\n[4] Edit a R1ecord "
+ "\n[5] Exit");
choice = scaned.nextInt();
if (choice == 1) {
System.out.println("***ADDING NAMES***");
System.out.println("Enter the name of the Student");
String addName = scan.next();
names.add(addName);
System.out.println("Record Added !!!");
}
else if (choice == 2) {
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
}
else if (choice == 3) {
System.out.println("***Delete A Record***");
System.out.print("Enter a number to be deleted: ");
int numDelete = scan.nextInt();
names.remove(numDelete);
System.out.println("Record Deleted");
}
else if (choice == 4) {
System.out.println("***Edit Record***");
System.out.println("***Database Content**");
System.out.println("------------------------");
System.out.println("Record # | Name ");
for (int index = firstIndex; index < names.size(); ++index) {
System.out.println("--------------------");
System.out.println(" " + index + " | " +names.get(index));
}
System.out.println("Enter the Name to be Edited");
String nameEdited = scan.next();
if (names.indexOf(nameEdited) >= 0) {
System.out.print("Change to: ");
String nameChange = scan2.next();
names.set(names.indexOf(nameEdited), nameChange);
}
else {
System.out.println("Record Not Existing");
}
}
else if (choice == 5) {
System.out.println("Thank you for using the Program");
System.exit(choice);
}
else {
System.out.println("Wrong Choice");
}
}
}
Each time you call menuCaller, you're creating a new list.
Perhaps you should create it in the main method and pass the reference into menuCaller:
public static void main(String[] args) {
String con;
List<String> names = new ArrayList<>();
do{
menuCaller(names);
System.out.println("Do you want to continue[Y/N]");
Scanner confirm = new Scanner(System.in);
con = confirm.nextLine();
}while(con.equalsIgnoreCase("y"));
}
public static void menuCaller(List<String> names) {
...
// (No declaration of names here - it's a parameter now...)
...
}

Trying to sort objects in an arraylist by a property but the objects don't always sort properly

I have four classes but they're just templates so I'll only post my main class (I have overridden toString for each). The sort method is at the bottom. Everything else is fine (more or less) with my code, but when I create the objects in the array and then go to sort them (by a string value called uid) sometimes one or two of them will be out of order. How can I fix this?
Here's the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
enum ClassStanding{FRESHMAN,SOPHOMORE,JUNIOR,SENIOR,UNKNOWN,MASTERS_STUDIES,PHD_STUDIES};
enum Major{CS,CEG,EE,ISE,BME,ME,MET,UNKNOWN};
enum StudentType{UNDERGRADUATE,GRADUATE,UNDECLARED};
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<>();
int counter;
boolean continueInput;
int contCounter;
do {
do {
System.out.print("Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: ");
switch (stdin.next().toLowerCase()) {
case "add":
add(stdin, studentList);
counter = 0;
break;
case "remove":
remove(studentList, stdin);
counter = 0;
break;
case "list":
list(studentList);
counter = 0;
break;
case "save":
String fileName = getFileName(stdin);
save(fileName, studentList);
counter = 0;
break;
case "sort":
counter = 0;
sort(studentList);
break;
default:
System.out.println("Improper input, please enter only ADD, REMOVE, LIST, or SAVE.");
counter = 1;
}
} while (counter == 1);
do {
System.out.print("\nDo you want to continue? Yes or no: ");
switch (stdin.next().toLowerCase()) {
case "yes":
contCounter = 0;
continueInput = true;
break;
case "no":
contCounter = 0;
continueInput = false;
break;
default:
contCounter = 1;
continueInput = false;
System.out.print("\nPlease only enter 'yes' or 'no'.");
}
} while (contCounter == 1);
} while (continueInput);
} // end main method
public static void add(Scanner stdin, ArrayList<Student> studentList) {
String firstName;
String lastName;
String uid;
StudentType studentType;
ClassStanding studentClassStanding;
Major major;
double overallGPA;
double majorGPA;
String majorProfessor;
boolean thesisOption;
System.out.print("Please enter the student's first name: ");
String tempName = stdin.next();
firstName = checkName(tempName);
System.out.print("Please enter the student's last name: ");
tempName = stdin.next();
lastName = checkName(tempName);
System.out.println("Please enter the student's UID in the format 'U####' or 'U#####': ");
String tempUID = stdin.next();
uid = checkUID(tempUID).toUpperCase();
int count;
do {
System.out.print("Please enter the student's status as UNDECLARED, UNDERGRADUATE, or GRADUATE: ");
switch (stdin.next().toUpperCase()) {
case "UNDECLARED":
studentType = StudentType.UNDECLARED;
studentClassStanding = setStudentClassStanding(studentType);
count = 0;
Student student = new Student(firstName, lastName,
uid, studentType, studentClassStanding);
studentList.add(student);
break;
case "UNDERGRADUATE":
studentType = StudentType.UNDERGRADUATE;
major = setMajor();
studentClassStanding = setStudentClassStanding(studentType);
System.out.println("Enter the student's overall GPA below.");
overallGPA = setGPA();
System.out.println("Enter the student's major GPA below.");
majorGPA = setGPA();
count = 0;
UnderGraduate underGraduate = new UnderGraduate(firstName, lastName, uid, studentType,
studentClassStanding, major, overallGPA, majorGPA);
studentList.add(underGraduate);
break;
case "GRADUATE":
studentType = StudentType.GRADUATE;
studentClassStanding = setStudentClassStanding(studentType);
majorProfessor = setMajorProfessor();
thesisOption = setThesisOption();
count = 0;
Graduate graduate = new Graduate(firstName, lastName, uid, studentType,
studentClassStanding, majorProfessor, thesisOption);
studentList.add(graduate);
break;
default:
System.out.println("Please enter either Undeclared, Undergraduate, or Graduate only.");
count = 1;
}
} while (count == 1);
} // end add method
public static String checkName(String tempName) {
int a = 1;
String name1;
Scanner scanner = new Scanner(System.in);
do {
name1 = tempName; // hold the value of firstName in name1
for (int i = 0; i < tempName.length(); i++) { // loop to check input consists of letters (is a name)
if (!Character.isLetter(tempName.charAt(i))) { // if non-letters detected, ensure this was intentional
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
tempName = scanner.nextLine();
if (tempName.equalsIgnoreCase("continue")) { // if user enters "continue", use original input
a = 0;
tempName = name1; // pass name1 value to firstName
break;
} else {
a = 1; // continue prompting for firstName
}
} else { // accept input
a = 0;
}
}
} while (a == 1); // loop to ensure proper input
return tempName;
} // end checkName method
public static String checkUID(String tempUID) {
Scanner scan = new Scanner(System.in);
int a;
do {
if (tempUID.charAt(0) == 'U' || tempUID.charAt(0) == 'u') {
if (tempUID.length() == 6 || tempUID.length() == 5) {
a = 0;
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} else {
a = 1;
System.out.print("Please ensure input is in the form of U#### or U#####. Please re-enter the UID: ");
tempUID = scan.next();
}
} while (a == 1);
return tempUID;
} // end checkUID method
public static ClassStanding setStudentClassStanding(StudentType studentType) {
Scanner scan = new Scanner(System.in);
int count;
ClassStanding studentTempClassStanding = null;
do {
if (studentType == StudentType.UNDECLARED || studentType == StudentType.UNDERGRADUATE) {
System.out.print("Please enter the student's class standing as either Freshman, Sophomore, Junior, Senior, or Unknown: ");
switch (scan.next().toUpperCase()) {
case "FRESHMAN":
studentTempClassStanding = ClassStanding.FRESHMAN;
count = 0;
break;
case "SOPHOMORE":
studentTempClassStanding = ClassStanding.SOPHOMORE;
count = 0;
break;
case "JUNIOR":
studentTempClassStanding = ClassStanding.JUNIOR;
count = 0;
break;
case "SENIOR":
studentTempClassStanding = ClassStanding.SENIOR;
count = 0;
break;
case "UNKNOWN":
studentTempClassStanding = ClassStanding.UNKNOWN;
count = 0;
break;
default:
System.out.println("Please enter only Freshman, Sophomore, Junior, Senior, or Unknown.");
count = 1;
}
} else {
System.out.print("Please enter the student's class standing as either 'Masters' for Masters Studies or 'PhD' for PhD Studies: ");
switch (scan.next().toUpperCase()) {
case "MASTERS": studentTempClassStanding = ClassStanding.MASTERS_STUDIES; count = 0; break;
case "PHD": studentTempClassStanding = ClassStanding.PHD_STUDIES; count = 0; break;
default: System.out.println("Please enter only 'Masters' or 'PhD'.");
count = 1;
}
}
} while (count == 1);
return studentTempClassStanding;
} // end setStudentClassStanding method
public static Major setMajor() {
Major tempMaj = null;
Scanner s = new Scanner(System.in);
int c;
do {
System.out.print("Please enter the student's major as either CS, CEG, EE, ISE, BME, ME, MET, or Unknown: ");
switch (s.next().toUpperCase()) {
case "CS":
tempMaj = Major.CS;
c = 0;
break;
case "CEG":
tempMaj = Major.CEG;
c = 0;
break;
case "EE":
tempMaj = Major.EE;
c = 0;
break;
case "ISE":
tempMaj = Major.ISE;
c = 0;
break;
case "BME":
tempMaj = Major.BME;
c = 0;
break;
case "ME":
tempMaj = Major.ME;
c = 0;
break;
case "MET":
tempMaj = Major.MET;
c = 0;
break;
case "UNKOWN":
tempMaj = Major.UNKNOWN;
c = 0;
break;
default:
System.out.println("Please enter only the specified values. ");
c = 1;
}
} while (c == 1);
return tempMaj;
} // end setMajor method
public static double setGPA() {
Scanner s = new Scanner(System.in);
double gpa;
int a;
do {
try {
System.out.print("Please enter the student's GPA: ");
gpa = s.nextDouble();// read in the gpa
if (gpa < 0.0 || gpa > 4.0) { // ensure the gpa is in the correct range
System.out.println("Invalid input, please enter a positive value between 0.0 and 4.0.");
a = 1;
} else {
a = 0;
}
} catch (InputMismatchException ex) { //catch any exceptions, prompt for correct input
a = 1;
gpa = 0.0;
System.out.println("Sorry, please enter a double value.");
s.nextLine(); // skip the last input
}
} while (a == 1 || gpa < 0.0 || gpa > 4.0); //loop while gpa is negative or incorrect input is received
return gpa;
} // end setGPA method
private static String setMajorProfessor() {
Scanner s = new Scanner(System.in);
String prof;
System.out.print("Please enter the name of the major professor: ");
String tempName = s.nextLine();
prof = checkName(tempName);
return prof;
} // end setMajorProfessor method
private static boolean setThesisOption() {
Scanner s = new Scanner(System.in);
boolean thesis = false;
int a;
do {
System.out.print("Please enter 'yes' if a thesis will be written, otherwise enter 'no': ");
switch (s.next().toUpperCase()) {
case "YES": thesis = true; a = 0; break;
case "NO": thesis = false; a = 0; break;
default: System.out.println("Please enter only 'yes' or 'no'."); a = 1;
}
} while (a == 1);
return thesis;
} // end setThesisOption method
private static void list(ArrayList<Student> studentList) {
for (int i = 0; i < studentList.size(); i++) {
System.out.println(studentList.get(i).toString());
}
} // end list method
public static String getFileName(Scanner stdin) {
System.out.print("Please enter the file name: "); // Prompt for input
String fileString = stdin.next();
return fileString; // Pass the fileString var to the main method
}//end of getFileName method
private static void save(String fileName, ArrayList<Student> studentList) {
int a; // create a counter
Scanner stdin = new Scanner(System.in);
do {
try {
PrintWriter writer = new PrintWriter(fileName); // Create a printwriter
for (int i = 0; i < studentList.size(); i++) {
writer.print(studentList.get(i).toString() + "\n"); //Print the arraylist to file
}
writer.close(); //Close the printwriter and save the file
a = 0;
} catch (FileNotFoundException ex) { // Catch any exceptions
System.out.println("The file could not be found, please re-enter the file name: "); // get new file name if an exception is thrown
fileName = stdin.nextLine();
a = 1;
}
} while (a == 1); // loop while exceptions are thrown
System.out.println("All information has been saved at " + fileName); // output that the arraylist has been saved in the specified file
// Make the following its own method
System.out.print("Would you like to read the contents of the file? Yes or no: ");
int b;
do {
switch (stdin.next().toLowerCase()) {
case "yes": readFromFile(fileName); b = 0; break;
case "no": b = 0; break;
default: System.out.println("Please enter only yes or no."); b = 1;
}
} while (b == 1);
} // end save method
private static void remove(ArrayList<Student> studentList, Scanner stdin) {
System.out.print("Please enter the UID of the student to be removed: ");
String tempUID = stdin.next();
String uidRemove = checkUID(tempUID);
for (int i = 0; i < studentList.size(); i++) {
if ((studentList.get(i).getUid()).equalsIgnoreCase(uidRemove)) {
studentList.remove(i);
}
}
System.out.println("The student with UID " + uidRemove + " has been removed.");
} // end remove method
private static void sort(ArrayList<Student> studentList) {
String uidLessU1;
String uidLessU2;
for (int i = 0; i < studentList.size(); i++) {
uidLessU1 = (studentList.get(i).getUid()).substring(1, studentList.get(i).getUid().length());
for (int j = 0; j < studentList.size(); j++) {
uidLessU2 = (studentList.get(j).getUid()).substring(1, studentList.get(j).getUid().length());
if (Integer.parseInt(uidLessU1) < Integer.parseInt(uidLessU2)) {
Student hold = studentList.get(i);
studentList.set(i, studentList.get(j));
studentList.set(j, hold);
}
}
}
} // end sort method
private static void readFromFile(String fileName) {
System.out.println("The contents of " + fileName + " as read from NotePad: ");
try {
Scanner fileReader = new Scanner(new File(fileName)); //Create a scanner
while (fileReader.hasNextLine()) { //Loop to read the file
String fromFile = fileReader.nextLine();
System.out.println(fromFile); //Output the file contents
}
} catch (FileNotFoundException ex) { //Catch any exceptions
System.out.println("Exception caught");
}
} // end readFromFile method
} // end main class
A sample of the problem would be (at this point I've already entered all the values instantiating the objects):
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: sort //calls the sort method
Do you want to continue? Yes or no: yes
Please enter what you want to do-ADD, REMOVE, SORT, LIST, or SAVE: list // calls the list method and prints out the arraylist
Student p o whose UID is U1111 is a
UNDECLARED student doing JUNIOR work.
Student s r whose UID is U2222 is a
UNDECLARED student doing JUNIOR work.
Student s w whose UID is U3333 is a
UNDECLARED student doing JUNIOR work.
Student s u whose UID is U7777 is a //why is this out of place?
UNDECLARED student doing JUNIOR work.
Student w e whose UID is U4444 is a
UNDECLARED student doing JUNIOR work.
Student p u whose UID is U44444 is a
UNDECLARED student doing JUNIOR work.
Student po iu whose UID is U77777 is a
UNDECLARED student doing JUNIOR work.
Just make Student implement Comparable and then you can do
Collections.sort(studentList);

Java: Switch default overriding try-catch

Package mylib:
Library class:
package mylib;
import java.util.*;
class Library {
public static void main(String[] args) {
boolean isInfinite = true;
int book_index;
Scanner input = new Scanner(System.in);
Book[] myBooks = new Book[3]; // Create an array of books
// Initialize each element of the array
myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);
do {
// Print book listing
System.out.println("\n***** BOOK LISTING *****");
for(int i = 0; i < myBooks.length; i++) {
Book book = myBooks[i];
System.out.println("[" + (i + 1) + "] " + book.sTitle + "\nAuthor: " +
book.sAuthor + "\nPages: " + book.iPages + "\nStatus: " + book.sStatus);
System.out.print("\r\n");
}
// Select library action
System.out.println("***** SELECT ACTION *****");
System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
"\nI - Return a book" + "\nX - Exit program");
System.out.print("\nEnter command: ");
String sAction = input.nextLine();
try {
switch(sAction.toUpperCase()) { // Converts input to uppercase
// Borrow a book
case "B":
System.out.println("\n***** BORROW A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].borrowBook(); // Call method from another class
break;
// Reserve a book
case "R":
System.out.println("\n***** RESERVE A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].reserveBook(); // Call method from another class
break;
// Return a book
case "I":
System.out.println("\n***** RETURN A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].returnBook(); // Call method from another class
break;
// Exit the program
case "X":
System.out.println("\nTerminating program...");
System.exit(0);
break;
default:
System.out.println("\nINVALID LIBRARY ACTION!");
break;
}
}
catch(ArrayIndexOutOfBoundsException err) {
System.out.println("\nINVALID BOOK INDEX!");
}
catch(InputMismatchException err) {
System.out.println("\nINVALID INPUT!");
}
} while(isInfinite);
}
}
Book class:
package mylib;
class Book {
int iPages;
String sTitle, sAuthor, sStatus;
public static final String AVAILABLE = "AVAILABLE",
BORROWED = "BORROWED", RESERVED = "RESERVED";
// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
this.sTitle = sTitle;
this.sAuthor = sAuthor;
this.iPages = iPages;
this.sStatus = Book.AVAILABLE; // Initializes book status to AVAILABLE
}
// Constructor accepts no arguments
public Book() {
}
// Borrow book method
void borrowBook() {
if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
sStatus = Book.BORROWED;
System.out.println("\nBORROW SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Reserve book method
void reserveBook() {
if(sStatus.equals(Book.AVAILABLE)) {
sStatus = Book.RESERVED;
System.out.println("\nRESERVE SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Return book method
void returnBook() {
if(sStatus.equals(Book.AVAILABLE)) {
System.out.println("\nBOOK IS ALREADY AVAILABLE!");
}
else if(sStatus.equals(Book.RESERVED)) {
System.out.println("\nBOOK IS ALREADY RESERVED!");
}
else {
sStatus = Book.AVAILABLE;
}
}
}
When I enter an invalid book index, say 4, the error is caught and it prints "INVALID BOOK INDEX!"
However, when I enter a char or string for the book index, it prints "INVALID LIBRARY ACTION!" when it should be printing "INVALID INPUT!"
The default clause appears to override the catch?
Your sAction variable is always a String, since Scanner.nextLine() returns String.
Therefore, your default statement is triggered, and it's reasonable to assume the InputMismatchException catch will never execute.
See also the other Scanner "next" methods if you'd like to fine-tune your input acceptance.
Example:
while (true) { // your infinite loop - better use a while-do instead of a do-while here
String sAction = input.nextLine(); // we assign sAction iteratively until user "quits"
// No try-catch: ArrayIndexOutOfBoundsException is unchecked and you shouldn't catch it.
// If it bugs, fix the code.
// No InputMismatchException either, as you don't need it if you use nextLine
// your switch same as before
}
Since the try-catch is for the int book_chosen and not for the String sAction, removing any of the catch-statement throws either OutOfBounds or InputMismatch error when I enter an int greater than 3 (OutOfBounds) or a char/string (InputMismatch) for the int book_chosen (Enter book index: ).
I have observed it is catching the errors when both catch statements are present, but not displaying the appropriate message. Since all are "invalid" inputs anyway, I found my way around it by just changing all the error prompts to INVALID INPUT!
Library class:
package mylib;
import java.util.*;
class Library {
static int book_index;
static Scanner input = new Scanner(System.in);
static void getIndex() {
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
}
public static void main(String[] args) {
// Create an array of books
Book[] myBooks = new Book[3];
// Initialize each element of the array
myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);
while(true) {
// Print book listing
System.out.println("\n***** BOOK LISTING *****");
for(int i = 0; i < myBooks.length; i++) {
Book book = myBooks[i];
System.out.println("[" + (i + 1) + "] " + book.sTitle +
"\nAuthor: " + book.sAuthor + "\nPages: " +
book.iPages + "\nStatus: " + book.sStatus);
System.out.print("\r\n");
}
// Select library action
System.out.println("***** SELECT ACTION *****");
System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
"\nI - Return a book" + "\nX - Exit program");
System.out.print("\nEnter command: ");
String sAction = input.nextLine();
try {
switch(sAction.toUpperCase()) {
// Borrow a book
case "B":
System.out.println("\n***** BORROW A BOOK *****");
getIndex();
myBooks[book_index-1].borrowBook();
break;
// Reserve a book
case "R":
System.out.println("\n***** RESERVE A BOOK *****");
getIndex();
myBooks[book_index-1].reserveBook();
break;
// Return a book
case "I":
System.out.println("\n***** RETURN A BOOK *****");
getIndex();
myBooks[book_index-1].returnBook();
break;
// Exit the program
case "X":
System.out.println("\nTerminating program...");
System.exit(0);
break;
default:
System.out.println("\nINVALID INPUT!");
break;
}
}
catch(ArrayIndexOutOfBoundsException err) {
System.out.println("\nINVALID INPUT!");
}
catch(InputMismatchException err) {
System.out.println("\nINVALID INPUT!");
}
}
}
}
Book class:
package mylib;
class Book {
int iPages;
String sTitle, sAuthor, sStatus;
public static final String AVAILABLE = "AVAILABLE",
BORROWED = "BORROWED", RESERVED = "RESERVED";
// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
this.sTitle = sTitle;
this.sAuthor = sAuthor;
this.iPages = iPages;
this.sStatus = Book.AVAILABLE;
}
// Constructor accepts no arguments
public Book() {
}
// Borrow book method
void borrowBook() {
if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
sStatus = Book.BORROWED;
System.out.println("\nBORROW SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Reserve book method
void reserveBook() {
if(sStatus.equals(Book.AVAILABLE)) {
sStatus = Book.RESERVED;
System.out.println("\nRESERVE SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Return book method
void returnBook() {
if(sStatus.equals(Book.AVAILABLE)) {
System.out.println("\nBOOK IS AVAILABLE!");
}
else if(sStatus.equals(Book.RESERVED)) {
System.out.println("\nBOOK IS RESERVED!");
}
else {
sStatus = Book.AVAILABLE;
System.out.println("\nRETURN SUCCESSFUL!");
}
}
}

Categories