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");
}
}
}
}
Related
I am creating in the console a program that adds new students but i wish to check if the max capacity of students is reached or not.
I am learning Java on my own so sorry if my code is not as it should be.
I would appreciate your feedback if you have suggestions.
Main
boolean abort = false;
boolean unlocked = false;
//Student[] students = new Student[School.MAX_studentEntered];
ArrayList<Student> students= new ArrayList<>();
Scanner option = new Scanner(System.in);
while (!abort){ //for as long as the value is not abort the loop will run
System.out.println("Unlock Admin(1) New Student(2) Show Students(3) Statistics (4) ");
System.out.print("Input: ");
int input = option.nextInt();
switch (input){
case 0:{
abort = true;
break;
}
case 1:{
System.out.println("Admin");
unlocked = true;
break;
}
//problem is case 2
case 2: {
System.out.println("Create a student");
int time = 0;
while (time<=School.MAX_studentEntered) {
Scanner st = new Scanner(System.in);
System.out.print("Name: ");
String name = st.nextLine();
System.out.print("Age: ");
int age = st.nextInt();
Student student = new Student();
student.setName(name);
student.setAge(age);
students.add(student);
time++;
if(unlocked){
System.out.print("Create another student? (yes/no): ");
Scanner ans= new Scanner(System.in);
String answer = ans.nextLine();
if (!answer.equals("yes")) {
break;
}
else {
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
continue;
}
}
}
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
break;
}
}
break;
}
Class Student
public class Student {
String name;
int age;
public Student(){
School.studentEntered++;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){ //void - save the value
this.age = age;
}
public String getName(){ //return - show the value
return name;
}
public int getAge(){
return age;
}
}
School Class
public class School {
static int studentEntered = 0;
static final int MAX_studentEntered=3;
public School(){
// it is automaticlly created when the class is created
// it does not need a void or return
studentEntered++;
}
}
I expect the program to stop adding new students in the arrayList if the capacity (MAX_studentEntered) is reached and to print an error after the break
public class Attraction {
String description;
private String contactDetails;
private String guide;
private String rating;
private final double noTicketsSold = 0;
private int maxGroupSize;
private int amountActivities;
private double ticketCost;
private int uniqueID;
private static int count;
private char chosen;
private String[] storedActivities;
private static int id_counter = 0;
private final int MAX_NUM_ATTRACTIONS = 5;
private static int[] attractions;
public Attraction(int MAX_NUM_ATTRACTIONS) {
id_counter++;
attractions = new int[MAX_NUM_ATTRACTIONS];
count = 0;
}
public int getUniqueID() {
return this.uniqueID;
}
public void recordAttraction() {
if (count == attractions.length) {
System.out.println("Attractions are full");
return;
}
if (count < attractions.length) {
attractions[count] =
count++;
}
}
public Attraction(char chosen, String description, double ticketCost, int maxGroupSize, String contactDetails,
int amountActivities, String[] storedActivities) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.amountActivities = amountActivities;
this.storedActivities = storedActivities;
}
public Attraction(char chosen, String description, double ticketCost, String guide, String rating) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.guide = guide;
this.rating = rating;
}
public void displayAllDetails() {
System.out.printf("\nID : %d%n", getUniqueID());
System.out.printf("Description : %s%n", description);
System.out.printf("Ticket cost : $%.2f%n", ticketCost);
System.out.printf("Tickets sold : %.0f%n", noTicketsSold);
if (chosen == 'y') {
System.out.println("Activity :");
int i = 0;
while (amountActivities > i) {
System.out.println(" : " + storedActivities[i]);
i++;
}
System.out.printf("Max Attendees : %d%n", maxGroupSize);
System.out.printf("Agency : %s%n", contactDetails);
}
if (chosen == 'n') {
System.out.printf("Instruction guide : %s%n", guide);
System.out.printf("Difficulty : %s%n", rating);
}
}
}
import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
private Attraction attractions = null;
public static void main(String[] args) {
StageA a = new StageA();
a.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private void displayMenu() {
System.out.println("\n **** Ozzey Attraction Menu ****");
System.out.println("A : Add New Attraction");
System.out.println("B : View Attraction");
System.out.println("C : List All Attractions");
System.out.println("D : Sell Ticket");
System.out.println("E : Refund Ticket");
System.out.println("F : Remove Attraction");
System.out.println("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private void createAttraction() {
String description;
double ticketCost;
char chosen;
int maxGroupSize;
String contactDetails;
int amountActivities;
System.out.print("\nEnter attraction description : ");
description = sc.nextLine();
System.out.print("Enter cost of a Ticket : ");
ticketCost = Double.parseDouble(sc.nextLine());
System.out.println("Is this a supervised tour ? [Y/N] :");
chosen = sc.nextLine().toLowerCase().charAt(0);
switch (chosen) {
case 'y':
System.out.println("What is maximum permitted tour group size?");
maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.println("Enter the agency contact details: ");
contactDetails = sc.nextLine();
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
while (amountActivities < 1) {
System.out.println("Please enter valid number of activities great than zero");
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
}
String[] storedActivities = new String[amountActivities];
int counter = 0;
while (amountActivities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
attractions = new Attraction(chosen, description, ticketCost, maxGroupSize, contactDetails,
amountActivities, storedActivities);
break;
case 'n':
String guide;
String rating;
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
attractions = new Attraction(chosen, description, ticketCost, guide, rating);
break;
default:
System.out.print("Please Enter valid answer ");
System.out.println("Is this a supervised tour ? [Y/N] :");
}
}
private void processSelection(char selection) {
switch (selection) {
case 'a':
attractions.recordAttraction();
createAttraction();
break;
case 'b':
System.out.printf("b");
break;
case 'c':
System.out.printf("c");
break;
case 'd':
System.out.printf("d");
break;
case 'e':
System.out.printf("e");
break;
case 'f':
System.out.printf("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
Hi all i stuck a part of my project for school i have to create a single array in my Attraction class called int[] attractions that can have a max of 5 stored createAttraction() from my stageA class.
When they choose 'a' in my switch statement this were i add createAttraction(); when user has created five attraction in will then tell the user its full and no more can be added. i tried a couple of things but i stuck any help wont be appreciated.
Note: this is the way project has to be setup.
Here are few things you should change in your code :
Change the constructor in attractions class, since you have already set final variable as 5 and if it is fixed, you do not need constructor with parameter: MAX_NUM_ATTRACTIONS
You need to initialise attraction object in StageA class :
private Attraction attractions = null; => private Attraction attractions = new Attraction()
Decide when you want to increment counter variable, when you dorecordAttraction or actually creating one and count should be checked greater or equal to attractions length/ MAX_NUM_ATTRACTIONS
return a value from method record Attraction to decide if you have to proceed with createAttraction or not
I am creating project that allows users to create, delete etc bank accounts. I have been struggling with case 3 (remove method). I want the user to enter the account ID which will remove it from the treemap. How should the method be laid out?
package mainsample;
import java.util.*;
public class MainSample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
BankProcess bankProcess = new BankProcess();
TransactionProcess transactionProcess = new TransactionProcess();
Bank bank = new Bank();
BankAccount bankAccount = new BankAccount();
int input;
int selection;
while (true) {
System.out.println("");
System.out.println("######## MENU ########");
System.out.println("[1] Create an account");
System.out.println("[2] Print all existing accounts");
System.out.println("[3] Delete an account");
System.out.println("[4] Deposit");
System.out.println("[5] Withdraw");
System.out.println("[6] Print transactions");
System.out.println("[0] Exit");
System.out.println("######################");
System.out.println("Please choose one of the following: ");
selection = scan.nextInt();
switch (selection) {
case 0:
System.out.println("Exit Successful");
System.exit(0);
break;
case 1:
System.out.println("'[1] Create an account' has been selected.");
System.out.print("Account Id: ");
int accountId = scan.nextInt();
scan.nextLine();
System.out.print("Holder Name: ");
String holderName = scan.nextLine();
System.out.print("Holder Address: ");
String holderAddress = scan.nextLine();
System.out.print("Opening Balance: ");
double openingBalance = scan.nextDouble();
System.out.print("Open Date: ");
String openDate = scan.next();
bankAccount = new BankAccount(accountId, holderName, openingBalance, holderAddress, openDate);
bank.setAccounts(bankProcess.openNewAccount(bank.getAccounts(), bankAccount));
System.out.println("Successfully Added.");
break;
case 2:
System.out.println("'[2] Display all existing accounts' has been selected");
System.out.println("-----------------------------------------------------");
bank.getAccounts().forEach((i, b) - > System.out.println(b));
System.out.println("-----------------------------------------------------");
break;
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
int accountNo = scan.nextInt();
bank.removeAccounts(bankProcess.removeAccount(bank.getAccounts(), bankAccount));
break;
case 4:
System.out.println("[4] Deposit has been selected");
System.out.println("Enter account ID: ");
int accountNumber = scan.nextInt();
System.out.println("Enter deposit amount: ");
double depositAmount = scan.nextDouble();
transactionProcess.deposit(bankAccount, depositAmount);
System.out.println(depositAmount + " has been deposited.");
break;
case 5:
System.out.println("[5] Withdraw has been selected");
System.out.println("Enter account ID: ");
int accountNu = scan.nextInt();
System.out.println("Enter withdraw amount: ");
double withdrawAmount = scan.nextDouble();
transactionProcess.withdraw(bankAccount, withdrawAmount);
System.out.println(withdrawAmount + " has been withdrawed.");
break;
case 6:
System.out.println("[6] Print Transaction has been selected");
System.out.println("Enter account ID: ");
int accountN = scan.nextInt();
break;
default:
System.out.println("Your choice was not valid!");
}
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class BankAccount {
private int accountId;
private String holderName;
private String holderAddress;
private String openDate;
private double currentBalance;
private List < Transaction > transactions = new ArrayList < Transaction > ();
//Provide Blank Constructor
public BankAccount() {}
//Constructor with an arguments.
public BankAccount(int accountNum, String holderNam, double currentBalance, String holderAdd, String openDate) {
this.accountId = accountNum;
this.holderName = holderNam;
this.holderAddress = holderAdd;
this.openDate = openDate;
this.currentBalance = currentBalance;
}
// Always Provide Setter and Getters
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
public String getHolderAddress() {
return holderAddress;
}
public void setHolderAddress(String holderAddress) {
this.holderAddress = holderAddress;
}
public String getOpenDate() {
return openDate;
}
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
public double getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public List < Transaction > getTransactions() {
return transactions;
}
public void setTransactions(List < Transaction > transactions) {
this.transactions = transactions;
}
public void addTransaction(Transaction transaction) {
if (transactions.size() >= 6) { // test if the list has 6 or more transactions saved
transactions.remove(0); // if so, then remove the first (it's the oldest)
}
transactions.add(transaction); // the new transaction is always added, no matter how many other transactions there are already in the list
}
public String toString() {
return "\nAccount number: " + accountId + "\nHolder's name: " + holderName + "\nHolder's address: " + holderAddress + "\nOpen Date: " + openDate + "\nCurrent balance: " + currentBalance;
}
}
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class Bank {
private TreeMap < Integer, BankAccount > bankAccounts = new TreeMap < Integer, BankAccount > ();
public TreeMap < Integer, BankAccount > getAccounts() {
return bankAccounts;
}
public void setAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
public BankAccount getAccount(Integer accountNumber) {
return bankAccounts.get(accountNumber);
}
public void removeAccounts(TreeMap < Integer, BankAccount > accounts) {
this.bankAccounts = accounts;
}
}
package mainsample;
import java.util.*;
/**
*
* #author Khalid
*/
public class BankProcess {
// return the Updated list of BankAccounts
public TreeMap < Integer, BankAccount > openNewAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
//Get the List of existing bank Accounts then add the new BankAccount to it.
bankAccounts.put(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
public TreeMap < Integer, BankAccount > removeAccount(TreeMap < Integer, BankAccount > bankAccounts, BankAccount bankAccount) {
bankAccounts.remove(bankAccount.getAccountId(), bankAccount);
return bankAccounts;
}
}
you have to get bankAccount first by accountNo you are getting from console because your removeAccount method in BankProcess expects BankAccount object for removal.
try this
case 3:
System.out.println("[3] Delete an account has been selected");
System.out.println("Enter the account ID: ");
int accountNo = scan.nextInt();
bankAccount = bank.getAccount(accountNo); // get bankAccount from account id
bank.removeAccounts(bankProcess.removeAccount(bank.getAccounts(), bankAccount));
break;
I'm getting a ClassCastException at:
RVBooking rvbooking = (RVBooking) bookingList.get(iweight);
I want to store the user's weightvehicle input and invoke the recordWeight() method. Sorry if i am not explaining this clearly. Thanks in advance.
Stack Trace
FerryBookingSystem [Java Application]
bookingSystem.FerryBookingSystem at localhost:51019
Thread [main] (Suspended (exception ClassCastException))
FerryBookingSystem.recordVehicleWeight() line: 144
FerryBookingSystem.main(String[]) line: 191
C:\Program Files\Java\jre7\bin\javaw.exe (16/05/2013 12:42:10 AM)
BookingException
class BookingException extends Exception{
String message;
String IDs;
public BookingException(String message){
this.message = message;
}
public BookingException(String message, String IDs){
this.message = message;
this.IDs = IDs;
}
public String getIDs(){
return IDs;
}
public String getMessage(){
return message;
}
}
FerryBookingSystem Class
public class FerryBookingSystem {
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
private static ArrayList<RVBooking> rvbookingList = new ArrayList<RVBooking>();
private static Scanner userInput = new Scanner (System.in);
public static int bookingIDExists(String IDs){
if (bookingList.size() == -1){
return -1;
}
for (int i = 0; i < bookingList.size(); i++){
if(bookingList.get(i).getbookingID().equals(IDs)){
return i;
}
}
return -1;
}
public static int rvbookingIDExists(String IDs){
if (rvbookingList.size() == -1){
return -1;
}
for(int i = 0; i < rvbookingList.size(); i++){
if(rvbookingList.get(i).getbookingID().equals(IDs)){
return i;
}
}
return -1;
}
public static boolean recordVehicleWeight(){
String booking_ID;
double weight = 0;
int iweight = 0;
System.out.print("Please enter the booking ID: ");
booking_ID = userInput.nextLine();
if(bookingIDExists(booking_ID) != -1){
if(rvbookingIDExists(booking_ID) != 1){
RVBooking rvbooking = (RVBooking) bookingList.get(iweight);
System.out.print("Please enter the weight of the vehicle: ");
weight = userInput.nextDouble();
iweight = (int)weight;
rvbooking.recordWeight(iweight);
return true;
}
else{
System.out.println("Error - cannot record weight for vehicle booking!");
return false;
}
}
else{
System.out.println("The booking ID does not exist, Please try again.");
return false;
}
}
public static void main (String [] args) throws IOException{
char user;
do{
System.out.println("**** Ferry Ticketing System ****");
System.out.println(" A - Add Vehicle Booking");
System.out.println(" B - Add Recreational Vehicle Booking");
System.out.println(" C - Display Booking Summary");
System.out.println(" D - Update Insurance Status");
System.out.println(" E - Record Recreational Vehicle Weight");
System.out.println(" F - Compile Vehicle Manifest");
System.out.println(" X - Exit");
System.out.print("Enter your selection: ");
String choice = userInput.nextLine().toUpperCase();
user = choice.length() > 0 ? choice.charAt(0) : '\n';
if (choice.trim().toString().length()!=0){
switch (user){
case 'A':
addVehicleBooking();
break;
case 'B':
addRecreationalVehicleBooking();
break;
case 'C':
displayBookingSummary();
break;
case 'D':
updateInsuranceStatus();
break;
case 'E':
recordVehicleWeight();
break;
case 'F':
break;
case 'X':
break;
default:
break;
}
}
}while(user!='X');
}
}
You are trying to cast RVBooking type to object from VehicleBooking list
Looks like your bookingList is meant to store objects of type VehicleBooking, and you are trying to cast that object to RVBooking while getting from the list
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
unless RVBooking is super class of VehicleBooking, VehicleBooking cannot be cast to RVBooking
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.