How to connect Sequencial Search to an array and Main Menu - java

I am trying to connect the sequential search function to the menu so that it accepts user input and search the tp arrays in apartA() and apartB(). And also how can we connect the report function to the values in Functions apartA() and apartB().
package jachi;
import java.util.Scanner;
public class Jachi {
public static void main(String[] args) {
menu();
}
public static void menu(){
int j,k,choice;
System.out.println("Menu");
System.out.println("1. Register");
System.out.println("2. Update");
System.out.println("3. Report");
System.out.println("4. Search");
Scanner scan=new Scanner(System.in);
choice=scan.nextInt();
switch(choice) {
case 1:
System.out.println("Select Apartment type");
System.out.println("1. Apartment A");
System.out.println("2. Apartment B.");
choice=scan.nextInt();
if (choice==1)
{
apartA();
}
else if (choice==2)
{
apartB();
}
break;
case 2:
System.out.println("Update the student information");
break;
case 3:
System.out.println("Rooms Available");
report();
break;
case 4:
System.out.print("Search for student. Please enter the TP number:");
break;
default:
System.out.println("Incorrect input");
}
}
public static int apartA()
{
final int a = 9;
//Normal Rooms Arrays
int[] tp;
tp = new int[a];
String[] stname;
stname = new String[a];
String[] mob;
mob = new String[a];
int ttt = get.nextInt();
int test = sequencialSearch(ttt);
Scanner get = new Scanner(System.in);
//Data Entry
for (int index = 0; index < a; index++)
{
System.out.println("Student Information");
System.out.println("Enter the student TP NUMBER:");
tp[index] = get.nextInt();
System.out.println("Enter the STUDENT NAME:");
stname[index] = get.nextLine();
System.out.println("Enter the MOBILE NUMBER:");
mob[index] = get.nextLine();
rent();
}
System.out.println("Rooms Full");
/**Report Data, Test for Data presence
*for(a=0;a<=2;a++)
*{
*System.out.println("TP NUMBER: "+tp[a]+"\t NAME: "+stname[a]+"\t MOBILE: "+mob[a]);
*}*/
return a;
}
public static void apartB(){
System.out.println("Select Room Type");
System.out.println("\t1. Normal Room");
System.out.println("\t2. Master Room");
int choice;
final int j = 6;
final int k = 3;
Scanner get = new Scanner(System.in);
choice = get.nextInt();
Scanner get1 = new Scanner(System.in);
if (choice==1)
{
System.out.println("1. Normal Bedroom");
// Normal Bedroom Arrays
String[] tp;
tp = new String[j];
String[] stname;
stname = new String[j];
String[] mob;
mob = new String[j];
//Data Entry
for (int index = 0; index < j; index++)
{
System.out.println("Student Information");
System.out.println("Enter the student TP NUMBER:");
tp[index] = get1.nextLine();
System.out.println("Enter the STUDENT NAME:");
stname[index] = get1.nextLine();
System.out.println("Enter the MOBILE NUMBER:");
mob[index] = get1.nextLine();
rent();
}
if(j<=5)
{
menu();
}
else
{
System.out.println("All Houses Full");
}
}
else if (choice==2)
{
System.out.println("Master bedroon");
//Master Bedroom Arrays
String[] mastertp;
mastertp = new String[k];
String[] mastername;
mastername = new String[k];
String[] mastermob;
mastermob = new String[k];
//Data Entry
for (int index = 0; index < k; index++)
{
System.out.println("Student Information");
System.out.println("Enter the student TP NUMBER:");
mastertp[index] = get1.nextLine();
System.out.println("Enter the STUDENT NAME:");
mastername[index] = get1.nextLine();
System.out.println("Enter the MOBILE NUMBER:");
mastermob[index] = get1.nextLine();
int x,y,z,pay;
x=100;
pay=300;
y=3*pay;
z=x+y;
System.out.println("Charges to be Paid");
System.out.println("Charges Amount");
System.out.println("Utilities charge: rm100");
System.out.println("Three month rental: rm"+y);
System.out.println("Total: rm"+z);
menu();
}
System.out.println("Full House Man");
}
}
public static void rent(){
int x,y,z,pay;
x=100;
pay=300;
y=3*pay;
z=x+y;
System.out.println("Charges to be Paid");
System.out.println("Charges Amount");
System.out.println("Utilities charge: rm100");
System.out.println("Three month rental: rm"+y);
System.out.println("Total: rm"+z);
menu();
}
public static void report(){
int x,y,z;
x=0;
y=x+1;
z=6-y;
System.out.println("Rooms occupied; "+y);
System.out.println("Rooms available; "+z);
menu();
}
public static int sequencialSearch(int Tnumbr){
int index,
element;
boolean found;
index = 0;
element = 0;
found = false;
while(!found && index == Tnumbr){
/* if(array[index] == 9{
* found = true;
* element = index;
* }
* index++;
*/
}
return element;
}
}

Ok that is a lot of code, lets try breaking it into simpler classes.
first would be Apartment. Lets have a class for apartment and put all the utility methods like report() and search() into it.
The apartment class can be something like:
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
class Apartment{
/** Integer: roomid, String StrudentId **/
HashMap<Integer, String> rooms = new HashMap<Integer, String>();
public Apartment(){
}
public Integer sequentialSearch(String tpNumber){
/** Returns null if student is absent **/
for(Integer roomId : rooms.keySet())
{
if(tpNumber.equals(rooms.get(roomId)))
return roomId;
}
return null;
}
public void report(){
System.out.println("ROOM_NUM\tSTUDENT_ID");
for(Integer roomId : rooms.keySet())
{
System.out.println(roomId +"\t" + rooms.get(roomId));
}
}
}
Now in your Main class Jachi you can create and use the apartments like:
Apartment apartA = new Apartment();
apartA.sequentialSearch("SOME_STUDENTID_HERE");
apartA.report();
Apartment apartB = new Apartment();
apartB.sequentialSearch("SOME_STUDENTID_HERE");
apartB.report();
You can also create Arrays of apartments now. Rest is left for you to explore.

Related

Why does my program crash when i excute method "O"?

package trainbooking;
import java.util.Scanner;
public class Trainbooking {
static final int SEATING_CAPACITY = 8;
public static void displayMenu() {
System.out.println("WELCOME TO OUR BOOKING SYSTEM");
System.out.println("A) Add a customer to seat");
System.out.println("V) View all the seats");
System.out.println("E) Display Empty seats");
System.out.println("D) Delete customer from seat");
System.out.println("F) Find the seat for a given customers name");
System.out.println("S) Store program data in to file");
System.out.println("L) Load program data from file");
System.out.println("O) View seats Ordered alphabetically by name");
System.out.println("Q) Exit the application\n");
}
public static void V(String[]seats) {
for (int i = 0; i < seats.length; i++) {
System.out.println(seats[i]);
}
}
public static void A(String[]seats) {
Scanner input = new Scanner(System.in);
System.out.println("What is the name of the customer you want to add? ");
String customerName = input.next();
System.out.println("What seat number do you want this customer to have?");
int seatNumber = input.nextInt();
seats[seatNumber] = customerName;
System.out.println("Thank you, your record was submitted.");
}
public static void E() {
// System.out.println("Empty seats");
//for(int i=0;<seats.length;i++){
// System.out.println("current seat"+ " is ressrved by" + seats[i]);
// }
}
public static void D() {}
public static void F() {}
public static void S() {}
public static void L() {}
public static void O() {
int name;
String temp;
Scanner input = new Scanner(System.in);
System.out.print("Enter all of the pessenger names below; ");
name = input.nextInt();
String names[] = new String[name];
Scanner b1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for (int i = 0; i < name; i++) {
names[i] = b1.nextLine();
}
for (int i = 0; i < name; i++) {
for (int j = i + 1; j < name; j++) {
if (names[i].compareTo(names[j]) > 0) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Following pessenger names have been Sorted in Order:");
for (int i = 0; i < name - 1; i++) {
System.out.print(names[i] + ",");
}
System.out.print(names[name - 1]);
}
}
public static void main(String[]args) {
String[]seats = new String[SEATING_CAPACITY];
Scanner in = new Scanner(System.in);
char choice;
do {
displayMenu();
System.out.println("Enter a choice or press q to quit the application");
choice = in.next().toUpperCase().charAt(0);
switch (choice) {
case 'A':
A(seats);
break;
case 'V':
V(seats);
break;
case 'E':
E();
break;
case 'D':
D();
break;
case 'F':
F();
break;
case 'S':
S();
break;
case 'L':
L();
break;
case 'O':
O();
break;
default:
System.out.println("You have entered the wrong choice. Please try again!");
}
} while ((choice != 'Q'));
System.out.println("Thank you for using our system.");
}
}
You are probably expecting a String/Text input at this function.
But what you do is the following:
You call the function Scanner.nextInt() which tries to read an Integer/Number value from the console.
What you should do instead of input.nextInt() use input.nextLine() and it shouldn't crash anymore.

cannot resolve or is not a field error

I am trying to search an arraylist of objects for an ID code, but I am stuck.
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1:
addTransaction(argList);
break;
case 2:
;// Search Transaction
break;
case 3:
;// Filter Withdraws and Deposits
break;
case 4:
;// Display transactions
break;
case 5:
System.out.println("End");
break;
default:
System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription) ); }
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.argId.get(i).contains(searchId)){
System.out.println("Yes");
}
}
}
}
My second file contains this
public class Transaction {
int id;
char type;
double amount;
String description;
public Transaction(int argId, double argAmount,char argType, String
argDescription){
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public void getId(int id){
}
public void getAmount(double amount){
}
public void getType(char type){
}
public void getDescription(String description){
}
}
And i get the error message: argId cannot be resolved or is not a field on line 58. I think my error is that argId is not part of the ArrayList, and i need to find the right tern to search the ID codes in the ArrayList.
Thanks
Earlier, before you edited your question, you had wrong getter methods.
Instead of
public void getId(int id){
}
you should write this:
public int getId() {
return id;
}
Declare your fields in Transaction class as private.
Then change your other getters in the similar way.
About your actual question, you can use for-each loop:
public static void searchTransactions(ArrayList<Transaction> argList) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for (Transaction transaction : argList) {
if (transaction.getId() == searchId) {
System.out.println("Yes");
break;
}
}
}
}
If you insist for i loop, change it this way:
for (int i = 0; i < argList.size(); i++) {
if(argList.get(i).getId() == searchId){
System.out.println("Yes");
break;
}
}
ArgId is a property of the objects in the list, not a property of the list itself which is why the compiler is giving you an error.
Looks like a typo:
You have:
argList.argId.get(i).contains(searchId)
try using:
argList.get(i).argId.contains(searchId)
argList is a collection, then you get object, read argId and check if it contains searchId
I would suggest to encapsulate class Transaction:
public class Transaction {
private int id;
private char type;
private double amount;
private String description;
public Transaction(int argId, double argAmount, char argType, String argDescription) {
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public int getId() {
return id;
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
Then main class will look in this way:
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1: ; addTransaction(argList);
break;
case 2: ;// Search Transaction
break;
case 3: ;// Filter Withdraws and Deposits
break;
case 4: ;// Display transactions
break;
case 5: System.out.println("End");
break;
default: System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription)
);
}
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.get(i).getId()==searchId){
System.out.println("Yes");
}
}
}
}

java.util.IllegalFormatConversionException: d != java.lang.String

I have problem when print output list of people by using ArrayList
package data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Manager {
List<Person> p = new ArrayList();
Scanner sc = new Scanner(System.in);
public void addStudent() {
String id;
String name;
int yob;
double point1;
double point2;
System.out.println("Input student id:");
id = sc.nextLine();
System.out.println("Input student name:");
name = sc.nextLine();
System.out.println("Input yob:");
yob = Integer.parseInt(sc.nextLine());
System.out.println("Input point 1:");
point1 = Double.parseDouble(sc.nextLine());
System.out.println("Input point 2:");
point2 = Double.parseDouble(sc.nextLine());
p.add(new Student(id,name,yob,point1,point2));
}
public void addEmployee() {
String id;
String name;
int yob;
double salaryRatio;
double salary;
System.out.println("Input employee id:");
id = sc.nextLine();
System.out.println("Input employee name:");
name = sc.nextLine();
System.out.println("Input employee yob:");
yob = Integer.parseInt(sc.nextLine());
System.out.println("Input salary ratio:");
salaryRatio = Double.parseDouble(sc.nextLine());
System.out.println("Input salary:");
salary = Double.parseDouble(sc.nextLine());
p.add(new Employee(id, name, yob,salaryRatio, salary));
}
public void addCustomer() {
String id;
String name;
int yob;
String companyName;
double bill;
System.out.println("Input customer id:");
id = sc.nextLine();
System.out.println("Input customer name:");
name = sc.nextLine();
System.out.println("Input customer yob:");
yob = Integer.parseInt(sc.nextLine());
System.out.println("Input compnay name:");
companyName = sc.nextLine();
System.out.println("Input bill:");
bill = Double.parseDouble(sc.nextLine());
p.add(new Customer(id,name,yob,companyName,bill));
}
public void addWho() {
int choice;
do {
System.out.println("1.Add Student");
System.out.println("2.Add Employee");
System.out.println("3.Add Customer");
System.out.println("4.Back to menu");
System.out.println("==============");
System.out.println("Choice:");
choice = Integer.parseInt(sc.nextLine());
switch(choice) {
case 1:
addStudent();
break;
case 2:
addEmployee();
break;
case 3:
addCustomer();
break;
case 4:
break;
}
}
while(choice != 4);
}
public void printPersonById() {
Collections.sort(p, Comparator.comparing(Person::getId));
for (int i = 0; i < p.size(); i++) {
System.out.println(p.get(i));
}
}
Student,Employee, and Customer are sub classes of class Person.When I try to print list,it has an error:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
How can I fix it?
Try this in your code:
System.out.println("Input yob:");
yob = sc.nextInt();
System.out.println("Input point 1:"); point1 =sc.nextDouble();
System.out.println("Input point 2:"); point2 = sc.nextDouble();
p.add(new Student(id,name,yob,point1,point2));
use System.out.println(p.get(i).someMethodOrVariableOfPerson); instead of System.out.println(p.get(i));
like below
public void printPersonById() {
Collections.sort(p, Comparator.comparing(Person::getId));
for (int i = 0; i < p.size(); i++) {
System.out.println("id :"+p.get(i).id);
System.out.println("name :"+p.get(i).name);
}
}
you can not directly print Person class object in out.println() method.
out.println() allow only string value

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);

Show a java console menu again after switch finishes

I am trying to write a java console menu but i can't render it in the console. Here is the code i wrote so far.
package com.registrar;
import java.util.*;
class GUIMenu {
private Course[] courses = new Course[100];
private Person[] persons = new Person[1000];
public void display_menu() {
System.out.println("****************MENU*****************");
System.out.println("[1] Add Course\n[2] Add Student to Course \n[3] Verify Registration \n[4] Remove Student \n[5] Add Persons");
System.out.println("**************************************");
System.out.println("Selection: ");
}
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt();
switch (input){
case 1:
Scanner sc = new Scanner(System.in);
System.out.println("Enter Course Name: ");
String name = sc.nextLine();
System.out.println("Enter Course ID:");
Integer cID = sc.nextInt();
System.out.println("Enter Instructor ID:");
Integer pn = sc.nextInt();
for(int i = 0; i < persons.length; i ++){
System.out.println(persons[i]);
}
for(int i = 0; i<persons.length; i++){
if(persons[i] !=null){
if(persons[i].getId().intValue() == pn){
System.out.println("Record Found");
p = persons[i];
}
else
System.out.println("Record Not Found");
}
}
Course c = new Course(name, cID);
if(p!=null){
Instructor ins = new Instructor(p);
c.setInstructor(ins);
}
System.out.println(c + " has been created");
for(int i = 0; i < courses.length; i ++){
if(courses[i] == null){
courses[i] = c;
break;
}
}
new GUIMenu();
case 2:
for(int i = 0; i < courses.length; i ++){
if(courses[i] != null)
System.out.println(courses[i]);
}
break;
case 3:
System.out.println ( "You picked option 3" );
break;
case 4:
System.out.println ( "You picked option 4" );
break;
case 5:
Scanner pers = new Scanner(System.in);
System.out.println("Enter Person Name: ");
String pname = pers.nextLine();
System.out.println("Enter Person ID:");
Integer oiID = pers.nextInt();
Person per = new Person(pname, oiID);
for(int i = 0; i < persons.length; i ++){
if(persons[i] == null){
persons[i] = per;
break;
}
}
display_menu();
default:
System.err.println("Unrecognized option");
}
}
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu();
a.display_menu();
}
}
I am trying that after a selection on the menu the code returns the menu again after completing the code associated with that particular selection. What i am doing wrong? I dont see the menu at all displaying.
What i am doing wrong?
Look at the code: This is where it starts:
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu(); // This is executed first...
a.display_menu();
}
let's have a look at it
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt(); // this is where it's waiting for your input.
...
Looking at the flow of your code, it is pretty clear why the menu is not shown.
EDIT:
You are looking for something like this:
public void runApplication() {
// init Scanner
boolean nextRound = true;
while(nextRound) {
displayMenu();
int input = sc.nextInt();
switch(input) {
case 1: // do stuff
break;
case 2: // this is the exit command
nextRound = false;
break;
// more cases
default:
// undefined input
}
}
}
So you use your constructor only for constructor relevant code and later call the runApplication() method.

Categories