In my CIS 220 Java Application 2 class, we have just went over the use of objects and classes with constructors and such. The whole goal of this assignment is to utilize a class and its methods to get the user employee data. I feel I've more or less finished the whole thing, but there is one last part. The data must be validated, as explained in this screenshot link http://puu.sh/7vzeI.jpg
I would assume employee ID needs to be 9 characters long as a string. The pay rate and hours worked must be doubles. Sadly I have no idea what sort of code I need in order to validate it in the class. I figured it was a while loop but it didn't seem to work.
Here is the main java method:
public class Project3 {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
Employee worker1 = new Employee();
worker1.getEmployeeName();
worker1.getEmployeeNum();
worker1.getPayRate();
worker1.getEmployeeHours();
System.out.println("Employee Name: " + worker1.printEmployeeName());
System.out.println("Employee ID: " + worker1.printEmployeeNum());
System.out.println("Pay Rate: $" + worker1.printPayRate());
System.out.println("Hours Worked: " + worker1.printHoursWorked());
worker1.getNetPay();
}
}
These are the methods in a class titled "Employee" which are used by main:
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// Method that prompts the user to enter their hours worked, then returns it as the reference
public double getEmployeeHours()
{
System.out.println("Enter the number of hours worked(a numeric value between 0.0 and 100.0): ");
hoursWorked = console.nextDouble();
return hoursWorked;
}
// Method that prompts the user to enter their employee ID, then returns it as the reference
public String getEmployeeNum ()
{
System.out.println("Please enter the employee's ID: ");
employeeNum = console.nextLine();
return employeeNum;
}
// Method that prompts the user to enter their pay rate, then returns it as the reference
public double getPayRate()
{
System.out.println("Please enter the employee's pay rate (a numeric value): ");
payRate = console.nextDouble();
return payRate;
}
Please forgive me if the format of this question is hideous, as I am still quite new to stack overflow.
I think you may not be clear on the concept of return methods. There is no point in making a return method if you are not going to use the returned value at any point. For example
public String getEmployeeName()
{
System.out.println("Please enter the employee's name: ");
employeeName = console.nextLine();
return employeeName;
}
// in the other class
worker1.getEmployeeName();
You never assign the String "worker1.getEmployeeName()" to anything so making this a return statement is useless. What I would do is that I would remove the getter methods aka "worker1.printEmployeeName()" and do this instead:
String name = worker1.printEmployeeName();
System.out.println("Employee Name: " + name);
Then in the method "printEmployeeName()" I would add my checks to see if the input was valid or not. like so:
(I don't think the name could have an invalid input except for maybe if it was null, so I will use the number instead.)
Okay so to validate the information I would do this:
public String getEmployeeNum ()
{
while(true)
{
System.out.println("Please enter the employee's ID: ");
try{
employeeNum = console.nextInt(); //this should be getting an integer not the line
}catch(Exception e){
employeeNum = 0;
}
if(String.valueOf(employeeNum).length() == 9)
return String.valueOf(employeeNum); // this will break you out of your loop and return the value
else{
System.out.println("Invalid input...");
continue;
}
}
}
Now I'll try an explain the code above
Because we are using "console.nextInt();" in order to check if what the user enters is not a string, a double or anything else that is not a integer I used a try catch statement. If you are unfamiliar with how the try catch works, it basically checks if there is an error with the code in the " try{ } " part and if there is do what is in the "catch(Exception e) { } " block. I could go in to more detail on it but that explains it enough for now. So if there is a problem with the input or we find an "error" with it we set the employeeNum to "0" (You'll see why in the next part).
Then we move on to the if statement "if(String.valueOf(employeeNum).length() == 9)" basically this will turn our input into a String so we can check the length (Remember if there is an error with the input the employeeNum will be "0" with the length of "1")
If the input is valid (9 numbers long) we then return it "return employeeNum;"
If it is not valid (Not long enough or too long) we tell the user that there was an error, and we restart the process.
I hope this helps some or at least gives you an idea on what to do next!
If you want to read and learn some more:
Try Catch : http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Edit: (A Hint)
When you check if the values are doubles for the pay rate and hours use something like this:
try {
hoursWorked = console.nextDouble();
}catch(Exception e){
hoursWorked = -1.0;
}
if(hoursWorked > 0.0)
return hoursWorked;
// the end should be the same as the other example :)
Related
I am trying to write a code that will exchange between AED,MYR,USD. I got to the following code and I cant fix the error.
It looked like the system.in isn't closing so I wrote the inclose(). But I still get the same results.
My problem might be something else and am not seeing it.
EDIT: this is the current code with changes.
import java.util.Scanner;
public class CurrencyConverter
{
protected static long amount;
static long Namount ;
static int commesion;
static String to;
public static void main( String[] args )
{
CurrencyConverterM MSg=new CurrencyConverterM();
CurrencyConverterM account1 = new CurrencyConverterM( );
String from ;
for(int i=0 ;i<3; i++)
{
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
//in.close();
if ("USD".equals(from)) {
amount=((long) (amount*0.27));
amount=account1.converter(to, amount);
}
else if ("MYR".equals(from)) {
amount=((long) (amount * 1.14));
amount =account1.converter(to, amount);
}
else {
if(mmount >= 900) {
Namount = (amount-50);
commesion =50;
}
else
{
Namount = (amount - 10);
commesion = 10;
}
}
System.out.println(MSg.getMsg());
}
}
}
the output should be as follows.
asking for current currency:
asking to what currency u want it:
asking about the amount.
am converting any amount to AED so I make it the main unit, then converting to the wished unit.
EDIT
public class CurrencyConverterM extends CurrencyConverter
{
long am;
#SuppressWarnings("static-access")
long converter (String to,long amount)
{
if ("MYR".equals(to)) {
am=(super.amount*=0.88);
}
else if ("MYR".equals(to)) {
am=(super.amount*=3.7);
}
return am ;
}
#SuppressWarnings("static-access")
public String getMsg()
{
return ("Thank you. The converted amount is "+(super.amount) + ". We will take" +super.commesion + " commission, and you will get "+ super.Namount);
}
}
before it didn't read the user's input, now its not converting the values.
I tried to print out my vales after each calculation but it looks like that the variable am is not being calculated correctly and its being multiplied by a 0 or divided by one ( the last result is always 0 ) but the amount that is in the main class is not 0 and its not converted to AED as well.
So I am getting this :Thank you. The converted amount is 0.0 1000.0. We will take50 commission, and you will get 0.0
String comparison is wrong.
from=="MYR" should be from.equals("MYR") rather I would recommend equalsIgnoreCase which is not case sensitive.
You should call scanner.nextLine() (in.nextLine()) and not in.toString()
Also you can use the same scanner and not to create 3 different scanners.
See the following part of your code updated with one Scanner (in):
System.out.println("Please enter your currency (USD, AED, or MYR only): ");
Scanner in = new Scanner( System.in );
from = in.nextLine();
System.out.println("What currency do you want?: ");
String to = in.nextLine();
System.out.println("How much you want to convert?: ");
amount= in.nextLong();
System.out.println(from + " " + to);
in.close();
by doing in.nextLine() you read the next line of user input.
From java 8 javadocs:
nextLine
public String nextLine()
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
The above will solve the issue that no input is read by your code.
Later you will have issues comparing the String user entered:
from=="USD" should be changed to "USD".equals(from)
Tip: Prefer to use "String".equals(variable) to avoid null pointer exceptions when variable is null.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 3 years ago.
I have to make a store that has items for purchase. After choosing an item, I prompt the user to enter the quantity of the item they would like to buy.
// 'input' is my Scanner object
int quantity;
quantity = input.nextInt();
If the user enters a non-integer (i.e. decimal, char...), it breaks the program.
Is there a way I can validate for this non-integer input?
Thank you
Sure, accept a String value instead of an int, check to see if you can parse that String value to an int, if you can, then do so. If not, sent a message stating that then entered value must be an number.
This could be done in a while loop.
import java.util.Scanner;
public class ScannerInputInt {
public static void main(String... args) {
Scanner in = new Scanner(System.in);
Integer input = null;
do {
System.out.println("Please enter number: ");
String s = in.nextLine();
try {
input = Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("ERROR: " + s + " is not a number.");
}
} while (input == null);
}
}
If you don't wanna use Exceptions method. You can try this.
This piece of code will continue to ask user input until user has entered correct input.
System.out.print("Enter quantity: ");
Scanner input = new Scanner(System.in);
boolean isInt = input.hasNextInt(); // Check if input is int
while (isInt == false) { // If it is not int
input.nextLine(); // Discarding the line with wrong input
System.out.print("Please Enter correct input: "); // Asking user again
isInt = input.hasNextInt(); // If this is true it exits the loop otherwise it loops again
}
int quantity = input.nextInt(); // If it is int. It reads the input
System.out.println("Quantity: " + quantity);
input.close();
Output:
Enter quantity: 12.2
Please Enter correct input: 12.6
Please Enter correct input: s
Please Enter correct input: s6
Please Enter correct input: as
Please Enter correct input: 2
Quantity: 2
I think it is slightly better approach because I think controlling flow of your program with Exceptions is bad practice and should be avoiding when there are other things that you can use.
Code a complete Java program to the following:
if it is a red light violation, then the fine is 1.75 % of the driver annual salary
if it is a speeding violation, then the fine is 1.2 %of the annual salary plus .5% of the salary for every 1 mile/hour over the speed limit.
What you need to do?
prompt user/officer to enter the full name of the driver
prompt officer to enter his/her full name.
prompt user/officer to enter annual salary of the driver.
prompt the officer to enter the type of violation (1 for red light or 2 for speeding)
if speeding then prompt user to enter how many miles/hour over speed limit.
evaluate with a set of if...else how much fine should be assessed, then print a full report including:
name of officer
name of driver
annual salary
violation type (you need to spell it out not just 1 or 2. (Red Light or Speeding)
amount of fine assessed (print a $ sign and round to two decimals)
Also, you must consider the following:
your program must not accept any code other than 1 or 2 for violation type.
your input must be handled by different methods and not in main()
evaluating the fine must be handled in a method of its own.
report must be handled by a different method.
the whole program must repeat for a new driver.
Extra credits: develop your own solution when a driver is subject to both violation…caught speeding and passing when red
Here is my code:
package FinFines_
import java.util.Scanner;
/*
* Description: This program assesses fines for traffic violations.
*/
public class FinFines_
{
static Scanner get = new Scanner(System.in);
//declarations:
static double mph = 0;
static double salary = 0;
static double fines = 0;
static int violation = 0;
static int answer = 1; //1 to continue or 0 to quit
static String officer = " ";
static String driver = " ";
public static void main(String[] args)
{
//input:
while (answer != 0) //while will allow the program to repeat for a new driver
{
input(officer, driver, salary, violation); //call input method
//calculations:
fines = calculateFines(violation, fines, salary, mph); //call calculateFines method
//Output:
disp(officer, driver, salary, violation,fines); //call disp method
//ask user if they would like to continue
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
System.out.println("Goodbye!");
}//end main
//=================================================================
public static void input(String officer, String driver, double salary, int violation) //Input Method
{
System.out.println("Officer, please enter your first and last name: ");
officer = get.nextLine();
System.out.println("Please the driver's first and last name: ");
driver = get.nextLine();
System.out.println("Please enter the driver's salary: ");
salary = get.nextDouble();
System.out.println("Press 1 if the driver ran a red light. Press 2 if the driver was speeding. Press 3 if the driver is subject to both violations. ");
violation = get.nextInt();
System.out.println("How many miles per hour was the driver going over the speed limit?: ");
mph = get.nextDouble();
}//end input
//=================================================================
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation
{
{
if (violation == 1)
return (salary * 1.75);
else if (violation == 2)
return (salary * 1.2) + (mph * .5 * salary);
else if (violation == 3)
return (salary * 1.75) + ((salary * 1.2) + (mph * .5 * salary));
return 0;
}
}//end calculateFines
//=================================================================
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method
{
System.out.println ("Your name is Officer " + officer + "\nThe name of the driver you pulled over is: " + driver);
System.out.println ( String.format( "The driver's annual salary is $%.2f", + salary) );
{
if (violation == 1)
System.out.println("\nThe type of traffic violation the driver received: Red Light");
else if (violation == 2)
System.out.println("\nThe type of traffic violation the driver received: Speeding");
else if (violation == 3)
System.out.println("\nThe type of traffic violation the driver received: Red Light & Speeding");
}
System.out.println ( String.format( "The amount of fines that will be assessed is $%.2f", + fines) );
}//end disp
}//end class FinFines_
Here is my issue:
When I input values for my program, the program acts as if I didn't input any names or numbers. All it says is
"Your name is Officer
The name of the driver you pulled over is:
The driver's annual salary is $0.00
The amount of fines that will be assessed is $0.00"
What can I do to make sure the program holds my inputted values?
When I press 1, to continue, it skips the first line when it asks for the officer's name. It doesn't allow me to input a name for the variable.
What can I do to make sure my program doesn't skip this line?
Is there an issue with my "return 0;" statement? If I don't include that statement then my program can't run, but I worry that me including it is making my program give 0 to all values.
I noticed that in the calculateFines() method, you have multiplied your values by 1.75. This will give 175% of the original. To find 1.75%, you need to multiply by 0.0175. This is also applicable for all other values.
Hope this helps
Though not a good practice to make everything static. Yet to just make your code work change all your methods as following -
public static void input(String officer, String driver, double salary, int violation) //Input Method {
to
public static void input() {
public static double calculateFines(int violation, double fines, double salary, double mph) //calculates the amount of fines for either violation {
to
public static double calculateFines() {
public static void disp(String officer, String driver, double salary, int violation, double fines) //Display Method {
to
public static void disp() {
This would ensure all your static fields are updated as you call these methods using the same parameters within thei definition and now your main() would include
while (answer != 0) {
input();
fines = calculateFines(); //call calculateFines method
disp();
System.out.println("Would you like to write a new ticket? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}
Note - I've cut short the text and removed comments, please do keep them in your code.
You need to read about the behavior of nextLine(), nextInt(), and nextDouble() regarding new line characters. If any of these leaves a newline character in the input buffer, then the following one will see that character and not consume any further input. This is what you are seeing.
To fix the issue, you need to read the newline character from the Scanner and ignore it. You should look at the Javadocs for Scanner to find an appropriate method to do this.
This is the same issue as #1.
Most likely there is no problem with this return as long as the if statements account for all possible values of violation. In fact, this is a very good solution because it will immediately let you see when violation has an invalid value. You should also learn about enums which allow you to define a finite number of choices for a variable.
So I have a class project for school and I have to make a bank account program, everything runs smoothly until I hit the while loop, and then it gets stuck in an infinite loop, not executing anything, please help, the code is the following
import java.util.Scanner;
public class Blueprint_ET
{
//initialize all variables in the object
private double balance;
private double interestRate;
private double years;
private String name;
private int age;
private int validAmount;
private double initialBalance;
//construct the objects with the following variables
public Blueprint_ET(double balance, String name, int age){
years=0;
interestRate=.02;
this.balance=balance;
this.name = name;
this.age= age;
initialBalance = balance;
}
//deposit method
public void deposit(double depositAmt){
balance+=depositAmt;
}
//withdraw method
public void withdraw(double withdrawAmt){
balance-=withdrawAmt;
}
//method used to set the account years and add the interest accordingly
public void setYearsAndAddInterest(double years){
this.years=years;
double interestEarned = (interestRate * years) * balance;
balance += interestEarned;
}
//method used to get the name so that it can be printed out later on
public String getName(){
return name;
}
//method used to get the initial balance so that it can be printed out
public double getStarting(){
return initialBalance;
}
//method used to get the years so that it can be printed out
public double getYears(){
return years;
}
//method used to get the final balance once the account it closed
public double getFinal(){
return balance;
}
//method used to get the age of the person
public int getAge(){
return age;
}
public static void main(String[] args){
//create "kboard" scanner
Scanner kboard = new Scanner(System.in);
//ask the user to enter the persons first name
System.out.print("Enter the account owners first name here: ");
String firstName = kboard.nextLine();
//ask the user to enter the persons last name
System.out.print("Enter the account owners last name here: ");
String lastName = kboard.nextLine();
//puts together the first and last name into one variable
String fullName = firstName + " " + lastName;
//asks the user for the starting balance of the account
System.out.print("Enter the starting balance of the account here: ");
double balance = kboard.nextDouble();
//asks the user for the age of the person
System.out.print("Enter the age of the person here: ");
int age = kboard.nextInt();
//initialize variables that will be used in the while loop
String option;
int exitNum=0;
double years=0;
double deposit=0;
double withdraw=0;
//Create account object
Blueprint_ET account1 = new Blueprint_ET(balance, fullName, age);
//start while loop
while (exitNum < 20 ){
//prompts the user to enter what option they want to do with according codes
System.out.print("To widthdraw, type wd, to deposit, type d, to change the number of years that the account has been open and add the according interest, type y, to close the account, type c.");
option = kboard.nextLine();
//if statement for entering the amount of money withdrawn if the option selected is the code for wd
if (option == "wd") {
System.out.print("Enter the amount you want to withdraw from the account: ");
withdraw = kboard.nextDouble();
account1.withdraw(withdraw);
}
//if statement for entering the years the account has been open and sets the years and adds the interest rate into the balance
else if (option == "y") {
System.out.print("Enter the years the person has had the account open: ");
years = kboard.nextDouble();
account1.setYearsAndAddInterest(years);
}
//if statement for entering the amount of money to deposit, adds it to balance
else if (option == "d") {
System.out.print("Enter the amount you want to deposit: ");
deposit = kboard.nextDouble();
account1.deposit(deposit);
}
//sets the exitNum to 21 so that it can exit the while loop
else if (option == "e") {
exitNum = 21;
}
}
//prints out all data once the account has been closed
System.out.println(account1.getName()+"'s is "+account1.getAge()+" had an account that had an intial balance of "+account1.getStarting()+". This account was open for "+account1.getYears()+" years. Also, when the account was closed, they had a balance of "+account1.getFinal());
}
}
Consider this code of yours:
//sets the exitNum to 21 so that it can exit the while loop
else if (option == "e") {
exitNum = 21;
}
Note that there are 2 ways to compare:
Using equals to == operator.
Using str.equals(str2) method.
Using equals to == operator.
== tests for reference equality. Let's suppose you have a String
str1 = "Hello World". Now this str1 String object takes up some
space in memory. Now let's suppose you create another exact same
String str2 = "Hello World". Now it's not always known whether these
two different Hello World String objects would return true or
false when compared with str1 == str2. They may return true if
both of these objects are referring to the same Object in memory.
However, this may also return false if they refer to different memory locations.
Bottomline is that == operator tests for the reference. It doesn't
matter to this operator as to what's there inside the objects.
Using str.equals(str2) method.
This str.equals(str2) would actually check what's there inside the
String Objects. It doesn't matter to this method whether both the
objects refer to the same or different memory locations. It only
considers the inside material of the String Objects.
Hence you should always use .equals() method when comparing String Objects. And so your method becomes:
//sets the exitNum to 21 so that it can exit the while loop
else if (option.equals("e")) {
exitNum = 21;
}
You must use a.equals("abc") to compare one string to another. And you have to know the difference between equals() and ==. I have run your code, this is the problem,I think.
You have used the == comparator, which perform a reference check on the two strings. Since the reference check will never be true, it will end up in an infinite loop, skipping all the if else statements
Since you are comparing the contents in the strings, use equals() instead.
You can look up this answer for a detailed explanation.
You should always compare two strings with equals() method. It actually compares the expression which is stored by a String object. For reference types operator == compares the addresses of two objects in memory
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
so far I have created two classes, which I will show below
I have tested both classes and they both seem to work.
I now need to create a menu which will use the two classes I have created and allow users to enter the information and to find information on their account for the following:
Add the customers details
Make a deposit to the business account
Record a meter reading to the business account
Display current balance of the business account
Display full account details
Change the discount value for the business account
Change the cost per unit for all business accounts
How to use the menu system
While I have tried my best to find out how to do it using resources online I am currently lost. Up to this point every time I have tried to create a menu system I just could not get it to work. I would greatly appreciate if someone could help me with the basics on how to go about doing it.
Thanks :)
public class GasAccount
{
private int intAccRefNo;
private String strName;
private String strAddress;
public double dblBalance;
private double dblUnits;
public static double dblUnitsCosts = 0.02;
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress)
{
}
public GasAccount (int intNewAccRefNo , String strNewName , String strNewAddress , double dblNewUnits)
{
intAccRefNo = intNewAccRefNo;
strName = strNewName;
strAddress = strNewAddress;
dblUnits = dblNewUnits;
dblBalance = dblUnits * dblUnitsCosts;
}
public int getAccRefNo()
{
return intAccRefNo;
}
public String getName()
{
return strName;
}
public String getAddress()
{
return strAddress;
}
public void deposit(double dblDepositAmount)
{
dblBalance = dblBalance - dblDepositAmount;
}
public double getBalance()
{
return dblBalance;
}
public double getUnitCost()
{
return dblUnitsCosts;
}
public void recordUnits (double dblUnitsUsed)
{
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblUnits = dblUnitsUsed + dblUnits;
}
public double getUnits()
{
return dblUnits;
}
public void updateUnitsCosts(double dblNewUnitsCosts)
{
this.dblUnitsCosts = dblNewUnitsCosts;
}
}
And another which extends it -
public class BusinessAccount extends GasAccount
{
private double dblDiscount;
public BusinessAccount (int intNewAccRefNo, String strNewName, String strNewAddress, double dblNewUnits, double dblNewDiscount)
{
super (intNewAccRefNo , strNewName , strNewAddress, dblNewUnits);
dblDiscount = dblNewDiscount;
}
public void setNewDiscount(double dblNewDiscount)
{
dblDiscount = dblNewDiscount;
}
public double getDiscount()
{
return dblDiscount;
}
#Override
public void recordUnits (double dblUnitsUsed)
{
double dblNewBalance;
dblBalance = dblBalance + dblUnitsUsed * dblUnitsCosts;
dblNewBalance = dblUnitsUsed * dblUnitsCosts * dblDiscount / 100;
dblBalance = dblBalance - dblNewBalance;
}
Here is what my attempted menu looks like up to the fifth option. I am doing something horribly wrong with calling in the methods from the other classes as BuisnessAccount.getMethod always shows up as an error. I am also pretty sure declaring the variables again is completely wrong as then they have no link to my other classes.
If someone could help me solve this it would be greatly appreciated
import java.util.Scanner;
public class Menu
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int Choice;
{
System.out.println("------------------------------");
System.out.println ( "1. Add the customers details" ) ;
System.out.println ( "2. Make a deposit to the business account" );
System.out.println ( "3. Record a meter reading to the business account" ) ;
System.out.println ( "4. Display current balance of the business account" ) ;
System.out.println ( "5. Display full account details" ) ;
System.out.println ( "6. Change the discount value for the business account" ) ;
System.out.println ( "7. Change the cost per unit for all business accounts ");
System.out.println ( "8. How to use the menu system ");
System.out.println ( "Any other number will exit the program");
System.out.println("------------------------------");
System.out.println ( "\n\nEnter a number from 1 to 8" );
Choice = input.nextInt();
switch (Choice)
{
case 1 :
int intNewAccRefNo;
String strNewName;
String strNewAddress;
Double dblNewUnits;
Double dblNewDiscount;
System.out.println("Please enter the account number?");
intNewAccRefNo = input.nextInt();
System.out.println("Please enter the account name?");
input.nextLine();
strNewName = input.nextLine();
System.out.println("Please enter the account address?");
strNewAddress = input.nextLine();
System.out.println("Please enter the number of initial number of units used?");
dblNewUnits = input.nextDouble();
System.out.println("Please enter the discount?");
dblNewDiscount = input.nextDouble();
case 2:
double dblDeposit;
System.out.println("Please enter the amount you want to deposit?");
dblDeposit = input.nextDouble();
System.out.println ( "The current balance: " + BusinessAccount.getBalance() ) ;
case 3:
double dblUnits;
System.out.println("Enter the number of Units Used");
dblUnits = input.nextDouble();
BusinessAccount.recordUnits(dblUnits);
case 4:
System.out.println("\n Current Balance: £"+ BusinessAccount.getBalance());
case 5:
System.out.println("Account Reference Number: " + BusinessAccount.getAccRefNo());
System.out.println("Address: " + BusinessAccount.getAddress());
System.out.println("Name: " + BusinessAccount.getName());
System.out.println("Balance: " + BusinessAccount.getBalance());
System.out.println("Discount: " + BusinessAccount.getDiscount());
System.out.println("Units: " + BusinessAccount.getUnits());
case 1 :
String strAddress;
System.out.println("Please enter the account address?");
strAddress = input.nextLine();
System.out.println("Address:" + firstAccount.getAddress());
There is no connection between what the user inputs and the method which i am calling, not sure how to fix.
By using BusinessAccount.someMethod(), you're attempting to call said method in a static context, but your methods are not static. To call upon your methods, you either need to make them static or need to create an object which can then call upon them, ie:
BusinessAccount ba= new BusinessAccount (4, "name", "address", 3.4, 43.4);
ba.someMethodFromClass();
In your case, you do NOT want them to be static. Read up more on static methods/variables (see below).
Some documentation that may be helpful:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
To answer your second question, you need to have a method (in your object's class, not main) which can assign values to your variables. ie:
public void setAddress (String address)
{
strAddress=address;
}
Then, you'd pass the address that you read in from main into your function. By doing that, you're initializing/assigning the value from the user to the value stored in your class, ie:
System.out.println("Please enter the account address?");
String temp = input.nextLine();
ba.setAddress(temp);
System.out.println("Address:" + ba.getAddress());
or better yet,
System.out.println("Please enter the account address?");
ba.setAddress(input.nextLine());
System.out.println("Address:" + ba.getAddress());
Going off of what SteveP said, it would be a good idea to store the instances of the other classes as instance variables in the Menu class.
Also, if you're using a GUI interface, this JMenu class API may come in handy:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html
Also look for JMenuBar, JMenuItem