import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
StageA stageA = new StageA();
stageA.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private static void displayMenu() {
System.out.printf("\n **** Ozzey Attraction Menu ****\n");
System.out.printf("A : Add New Attraction\n");
System.out.printf("B : View Attraction\n");
System.out.printf("C : List All Attractions\n");
System.out.printf("D : Sell Ticket\n");
System.out.printf("E : Refund Ticket\n");
System.out.printf("F : Remove Attraction\n");
System.out.printf("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private static void createAttraction() {
System.out.printf("Enter attraction description : ");
String description = sc.nextLine();
System.out.printf("Enter cost of a Ticket : ");
double ticketCost = Double.parseDouble(sc.nextLine());
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
char chosen = sc.nextLine().to Lowercase().charAt(0);
System.out.printf("What is maximum permitted tour group size?\n");
int maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.printf("Enter the agency contact details:\n ");
String contactDetails = sc.nextLine();
int counter = 0;
String[] storedActivities;
String guide, rating;
switch (chosen) {
case 'y':
System.out.printf("How many activity are there?\n");
int activities = Integer.parseInt(sc.nextLine());
while (activities < 1) {
System.out.printf("Please enter valid number of activities great than zero \n");
System.out.printf("How many activity are there?\n");
activities = Integer.parseInt(sc.nextLine());
}
storedActivities = new String[activities];
while (activities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
break;
case 'n':
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
break;
default:
System.out.printf("Please Enter valid answer ");
System.out.printf("Is this a supervised tour ? [Y/N] :\n");
chosen = sc.nextLine().toLowerCase().charAt(0);
break;
}
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
}
private static void processSelection(char selection) {
switch (selection) {
case 'a':
createAttraction();
break;
case 'b':
System.out.println("b");
break;
case 'c':
System.out.println("c");
break;
case 'd':
break;
case 'e':
System.out.println("e");
break;
case 'f':
System.out.println("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
}
public class Attraction {
private String description, contactDetails, guide, rating;
private double ticketCost;
private int maxGroupSize;
private char chosen;
private String storedActivities;
public Attraction(String description, double ticketCost, int maxGroupSize, String contactDetails,
char chosen, String guide, String rating, String storedActivities) {
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.chosen = chosen;
this.guide = guide;
this.rating = rating;
this.activities = storedActivities;
}
}
I cannot get my constructor to work
Attraction attraction = new Attraction(description, ticketCost, maxGroupSize, contactDetails, chosen, guide, rating, storedActivities[counter]);
where every I move it to I cannot get into to work I tried while if statement and changed to a switch statement but I get the same error error I getting cannot resolve variable rating, guide and storedActivities[counter] any help would be appreciated
I can only use a single array and the questions are in order I need to ask them.
The compiler is complaining because there is a risk you will not have initialised your variables by the time you attempt to instantiate your Attraction instance.
The following lines declare your variables but at this point they have not been assigned a value:-
String[] storedActivities;
String guide, rating;
Note that if your code enters either the default or the 'n' case in your switch statement, some of these variables remain unset. You need to fix this before the compiler will be satisfied that it has all the information it needs to create your Attraction object.
Your solution is down to coding preference & needs. You could assign a default value to these parameters, use tail recursion to prevent incorrect answers from the scanner, or provide an alternative constructor if not all details are required.
Hi this would be because your variables are not intialised at the start.
Think about it: The vars rating, guide and storedActivities[] will not be intialised if the chosen = anything other than y or n. The JVM automatically senses this and throws an error automatically.
What I suggest you do is set them to a default size (the array) or a default value, so that this error will not occur. Having the default value also means you could automatically override any incorrect values given by the user.
Related
i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.
I am trying to make this method print one of the four string messages contained within String[] strArr. I have tried doing this by calling the method in the main method, by typing many different forms of simpleArray(); and I have tried filling the parenthesis, writing it several different ways but nothing has worked. I have actually been working on it for days, and usually I give up and move on to a different part of the code.
Though it may seem impractical, I do need the method to be written similarly to the way it is because my project criteria states it must contain one argument and return void.
public static void simpleArray(String[] greetings) {
String[] strArr = {"Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card", "We value your business!"};
int i = (int)(Math.random() * strArr.length);
System.out.println(strArr[i]);
}
here is my main method, where I try to call the custom method in line 6.
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray();
printStartupMessage();
Scanner keyboard = new Scanner(System.in);
Scanner keyboardDouble = new Scanner(System.in);
saveRandomBalance = getRandomBalance();
System.out.println("CHECKING BALANCE**** $" + saveRandomBalance);
System.out.println("Would you like to withdrawl from CHECKING****? Y/N");
String proceedWithWithdrawl = keyboard.nextLine();
while (!proceedWithWithdrawl.equalsIgnoreCase("y") && !proceedWithWithdrawl.equalsIgnoreCase("n")
&& !proceedWithWithdrawl.equalsIgnoreCase("yes") && !proceedWithWithdrawl.equalsIgnoreCase("no"))
{
System.out.println("Invalid response. Enter [Y] or [N].");
proceedWithWithdrawl = keyboard.next();
}
switch(proceedWithWithdrawl)
{
case "N":
case "n":
case "nO":
case "NO":
case "No":
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
break;
case "yeS":
case "YEs":
case "yEs":
case "yES":
case "YeS":
case "YES":
case "Yes":
case "yes":
case "y":
case "Y":
System.out.println("Enter amount to withdrawl: ");
amountToWithdrawl = keyboardDouble.nextDouble();
remainingBalance = saveRandomBalance - amountToWithdrawl;
remainingBalance = Math.round(remainingBalance * 100);
remainingBalance = remainingBalance/100;
if (amountToWithdrawl % 20 == 0 && amountToWithdrawl <= saveRandomBalance)
{
System.out.println("Dispensing...");
System.out.println("ACCOUNT BALANCE: $" + remainingBalance);
System.out.println("$" + amountToWithdrawl + " has been withdrawn from CHECKING****");
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
//CallDollarBill.dollarBill();
}
else if (amountToWithdrawl > saveRandomBalance)
{
System.out.println("Insufficient Balance.");
}
else if (amountToWithdrawl % 20 != 0)
{
System.out.println("Please enter multiples of 20.");
}
//else
//{
// System.out.println("invalid input");
//}
}
}
now, the error it provides is as follows.
firstDraftFinal.java:69: error: method simpleArray in class firstDraftFinal cannot be applied to given types;
simpleArray();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand that part of the problem is probably int i (and strrArr) are integers, but I do not know what to do about this. I hired a tutor, but I ran out of time. I am also aware that the switch statement is not efficient, I will be changing that.
Thank you.
Your current code specifies a parameter that is not used; while it's unclear why you would want to do this, you can simply pass null. However, maybe what you intended was to pass the list of greetings; i.e. see second version below.
class Test {
public static void main(String[] args) {
// Per your current code.
for (int i=0; i<10; i++) simpleArray(null);
System.out.println("");
// What you may be looking for.
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
for (int i=0; i<10; i++) simpleArray2(strArr);
}
public static void simpleArray(String[] greetings) {
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
int i = (int) (Math.random() * strArr.length);
System.out.println(strArr[i]);
}
public static void simpleArray2(String[] greetings) {
int i = (int) (Math.random() * greetings.length);
System.out.println(greetings[i]);
}
}
You have compile error because you didn't pass any arguments to method that require them, just pass to your method any string array, because you don't use passed argument in this method:
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray(new String[0]);
printStartupMessage();
To continue refactor your code you may want to get rid of this argument (pay attention if other parts of code may use it) and rewrite it like this:
public static void printGreetings() {
String[] greetings = {"Welcome To CWU BANK!",
"Thank you for using CWU ATM!",
"Please insert DEBIT card",
"We value your business!"
};
int random = new Random().nextInt(greetings.length);
System.out.println(greetings[random]);
}
I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.
Orphaned Case Error
The following are the tasks which will be done in the program:-
Accept Deposit from a customer and update the balance.
Display the balance.
Compute and deposit the compound interest.
Permit withdrawal and update the balance.
Check for the minimum balance, impose penalty, if necessary and update the balance
I am getting an "orphaned case" error for
case1: S1.Display();
case1: S2.Display();
Please help. This is the Code:
import java.util.*;
class Account
{
String custname;
double accno;
double bal;
Account(String c, double a, double b)
{custname = c;
accno = a;
bal = b;
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
System.out.println("Balance : "+bal);
}
void Deposit()
{double dep;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter the amount your want to deposit:");
dep = sc.nextDouble();
bal = bal + dep;
System.out.println("Updated Details....");
Display();
}
void Withdraw()
{double wth;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount you want to withdraw");
wth = sc.NextDouble();
bal = bal - wth;
System.out.println("Updated details....");
Display();
}
}
class SavAccount extends Account
{ String acctype;
SavAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Savings";
}
void ComInt()
{int months;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the duration of the account in months");
months = sc.NextInt();
double rate, inte;
rate = 0.04;
inte = months *rate * bal;
bal = bal + inte;
System.out.println("Compund Interest : "+inte);
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
ComInt();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
}
}
class CurAccount extends Account
{String acctype;
CurAccount(String c, double a, double b)
{Super(c, a, b);
acctype = "Current";
}
void Penalty()
{
if(bal<5000.00)
{bal = bal - 100.00;
System.out.println("Fine deducted Rs.100/-");
}
}
void Display()
{System.out.println("Account Holder: "+custname);
System.out.println("Account Number "+accno);
Penalty();
System.out.println("Balance : "+bal);
System.out.println("Account Type: "+acctype);
if(bal<=5000.00)
{System.out.println("Warning!! Please maintain balance above Rs.5000/-");
}
}
}
class Accmain
{public static void main(Strings args[])
{SavAccount S1 = new SavAccount("Aniruddha", 134.00, 15000.00)
;
CurAccount S2 = new CurAccount("Tyrel" , 135.00, 6000.00);
int num = 2;
String c = "y";
int n;
double temp;
double accs[] = new double[10];
accs[0] = S1.accno;
accs[1] = S2.accno;
Scanner sc = new Scanner(System.in);
while (c == "y");
{System.out.println("Please enter your Account number:");
temp = sc.nextDouble();
if(accs[0] == temp)
{System.out.println("Welcome "+ S1.custname);
System.out.println("Account Type: "+ S1.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt();
Switch(n)
;
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
else if(accs[1] == temp)
{System.out.println("Welcome "+ S2.custname);
System.out.println("Account Type: "+ S2.acctype);
System.out.println("1.Display");
System.out.println("2.Withdraw");
System.out.println("3.Deposit");
n = sc.nextInt()
;
Switch(n);
{
case 1 : S2.Display();
case 2 : S2.Withdraw();
case 3 : S2.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
}
}
}
}
Several problems.
1) That extra ; in the end made the switch completed right away on that stamtement.
Switch(n); <--
Apparently all the cases became orphans.
If you remove the colon after Switch(n) you would be fine.
Switch(n)
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
2) After that you have another problem. You need to have break after each case. Otherwise your switch executes all the cases even though the match found. To stop that add break after each case
Switch(n)
{
case 1 : S1.Display(); break;
case 2 : S1.Withdraw();break;
...
3) When you write c == "y" That compare references not equality.
you need to use equals() method to check string equality
read How do I compare strings in Java?
4) That line Super(c, a, b); won't compile as S must be lower-case. Java is case sensitive.
The two problems you're hitting are:
Switch(n) // <-- switch is not spelled with a capital 's'
; // <-- remove the semicolon
{
case 1 : S1.Display();
case 2 : S1.Withdraw();
case 3 : S1.Deposit();
default :System.out.println("Bad Choice ");
c = "n";
}
Since the cases appear without any relation to a switch - you're getting the "Orphaned Case Error". Further, when you're done handling each case you should break; otherwise the code will continue executing the following cases as well!
I would also advise you to use a good IDE and auto-indent the code because the way it is currently indented makes it very difficult to see where an if or else clauses ends.
A good IDE (IntelliJ/Eclipse/Netbeans) will also show you all the compilation errors you have, for example Super(c, a, b) - the 's' should not be capitalized, and etc.
This error usually meas that you are trying to use a case keyword outside of a switch statement.
Switch(n)
;
here after switch(n) remvoe the ;
also use break statement after each case operations. else it will keep executing the next case operations.
other minor issues are mentioned in Sures's answer
case 1:System.out.println("1111111111111111");
some example case 1:System no spaces in statement
example case 1:System.out.println("Display the vales");
Ok so, this is whats going on. I'm making a simple simple bank program.
This is what I want to do, notice the variables for my Account class (a1, a2, a3)
This works perfectly fine, but not for what I want to do.
In the switch cases, I want to be able to let the user input the name under the account and be able to edit it.
Now, I know if I were to basically do this:
Account AccountObject = new Account ();
balance.put (sc.nextLine(), AO.addFunds)
Then I would have separate users, but the funds would essentially all be the same. How would I make them separate*
I know once I figure out how to do this, I'll be set to move on to more complicated projects.
import java.util.Hashtable;
import java.util.Scanner;
class Data {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Scanner sc = new Scanner(System.in);
Scanner sa = new Scanner(System.in);
boolean quit = false;
boolean quit2 = false;
// Create account variables
Account a1 = new Account();
Account a2 = new Account();
Account a3 = new Account();
Account a4 = new Account();
Account a5 = new Account();
// Add funds to variables in Hashtable
balance.put(sc.nextLine(), a1.addFunds());
balance.put(sc.nextLine(), a2.addFunds());
balance.put(sc.nextLine(), a3.addFunds());
balance.put(sc.nextLine(), a4.addFunds());
balance.put(sc.nextLine(), a5.addFunds());
do {
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int input = sa.nextInt();
switch (input) {
case 1:
System.out.println(balance.get(sc.nextLine()));
break;
case 2:
System.out.println(balance.put(sc.nextLine(), a1.addFunds()));
break;
case 3:
System.out.println(balance.put(sc.nextLine(), a1.withdrawFunds(sa.nextDouble())));
break;
case 4:
quit = true;
break;
}
} while(!quit);
System.out.println("Exiting menu");
}
}
Account class
import java.util.Scanner;
public class Account {
int balance;
String name;
public double addFunds() {
Scanner sa = new Scanner(System.in);
double amount = sa.nextDouble();
balance += amount;
return balance;
}
public String Acct(String names) {
Scanner sc = new Scanner(System.in);
name = names;
return name;
}
public double withdrawFunds(double amount) {
balance -= amount;
return balance;
}
public String toString() {
return String.format("Balance: %n", balance);
}
}
You should create an Account class, which is model for an account. I suggest you do not handle the user input inside the Account class.
Account class
public class Account {
private String name;
private int balance;
public Account(String name, int startBalance) {
this.name = name;
this.balance = startBalance;
}
public void addFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
this.balance += amount;
}
public void withdrawFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
else if (amount > this.balance) {
throw new IllegalArgumentException("You don't have that, so you cannot grab that.");
}
this.balance -= amount;
}
public String getName() {
this.name;
}
public int getBalance() {
return this.balance;
}
}
Now, if you want, you can create some accounts and add them to an ArrayList<Account>. I do not know why you would use a HashMap: if you have just a list with all Account objects, you have all information you need.
ArrayList<Account> accounts = new ArrayList<Account>();
Scanner sc = new Scanner(System.in);
You can implement your user input like something like:
private static ArrayList<Account> accounts = new ArrayList<Account>();
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
initializeSomeBankAccounts();
displayUI();
}
private static void initializeSomeBankAccounts() {
for (int i = 0; i < 2; i++) {
System.out.print("Insert " + (i > 0 ? "another " : "") + "account name: ");
String name = sc.nextLine();
System.out.print("Insert start balance: ");
int startBalance = sc.nextInt();
sc.nextLine();
// Create a new account using the user input
Account account = new Account(name, startBalance);
// Add the account to our list with accounts.
accounts.add(account);
}
}
public static void displayUI() {
boolean quit = false;
while (!quit) {
// Show a menu with the available actions
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int action = sc.nextInt();
sc.nextLine();
Account account;
// Since we ask the user to insert a right account name, we can
// guarantee that the variable 'account' contains an Account
// object.
switch (action) {
case 1:
account = askAccount();
System.out.println(account.getBalance());
break;
case 2:
account = askAccount();
System.out.print("Amount: ");
int amount = sc.nextInt();
account.addFunds(amount);
break;
case 3:
account = askAccount();
System.out.print("Amount: ");
amount = sc.nextInt();
account.withdrawFunds(amount);
break;
case 4:
quit = true;
break;
}
}
}
private static Account askAccount() {
System.out.println("Which account? ");
Account account = null;
boolean accountFound = false;
// Now the user has to input a valid account name, we're going to
// search for that account name in the list. If it is found, we
// have the whole Account object stored into the variable 'account'.
// Otherwise, if it is not found, then we repeat to ask to insert
// an account name, until a account name is given which is present
// in our list.
while (!accountFound) {
String accountName = sc.nextLine();
account = searchAccount(accountName);
if (account == null) {
System.out.println("Account not found. Insert another account:");
}
else {
accountFound = true;
}
}
return account;
}
/**
* Searches an account from our list of all accounts.
*
* #param name The name to search for.
* #return The account if found, or null otherwise.
*/
private static Account searchAccount(String name) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
return account;
}
}
return null;
}
I also got a few suggestions:
You have some variables which are not used, i.e. quit2. You might want to remove them.
As far as I know, you do not need to have two Scanners; one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner.
You have variables starting with an uppercase character, i.e. AccountObject. In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter.
You are using the class Hashtable, but it is recommended to use HashMap<Key, Value>.