I am trying to make a project out of what I had learn online.
public static void main(String[]args){
int balance, payment;
balance = 11310;
String new1 = "new";
String old = "old";
String partial = "partial";
String full = "full";
String no = "no";
String yes = "yes";
String First = "first year second sem";
String Second = "second year first sem";
String Third = "second year second sem";
System.out.print("\nEnter Name: ");
Scanner st = new Scanner(System.in);
String name = st.nextLine();
System.out.print("\nOld Student or New Student: ");
String student = st.nextLine();
if(student.equalsIgnoreCase(new1)){
System.out.print("\nGreetings, "+name);
System.out.print("\nPlease fill out our Registration Form.");
System.out.print("\nThank you!");
try {
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File("C:\\Users\\toshiba-1\\Desktop\\Regform1styr.2ndsem - Copy.docx"));
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return;
}
System.out.print("\nGreetings, "+name);
System.out.print("\nWould you want to enroll for a new semester? ");
String enroll = st.nextLine();
if(enroll.equalsIgnoreCase(no))
{
System.out.print("\nThank you!");
return;
}
if(enroll.equalsIgnoreCase(yes))
{
}
System.out.print("\nWhich Semester? ");
String semester = st.nextLine();
if(semester.equalsIgnoreCase(First)) // My error started here.
{
}
else if(semester.equalsIgnoreCase(Second))
{
}
else if(semester.equalsIgnoreCase(Third))
{
}
else
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
}
}
}
I am having trouble when the user chooses on the three string. I alternatively tried this set of codes.
if(semester.equalsIgnoreCase(First))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else if(semester.equalsIgnoreCase(Second))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else if(semester.equalsIgnoreCase(Third))
{
System.out.print("\nPlease choose a semester.");
}
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
System.out.print("\nChoose your Payment term(Partial/Full): ");
String term = st.nextLine();
if(term.equalsIgnoreCase(partial))
{
System.out.print("\nHow much would you like to pay for this semester: ");
Scanner in = new Scanner(System.in);
payment = in.nextInt();
balance = balance - payment;
System.out.print("\nYour Balance is: SR"+ balance);
if(balance > payment){
System.out.print("\nYou have remaining balance of: SR" + balance);
}else if(balance == payment){
System.out.print("\nYou are already paid");
}
else
{
System.out.print("Please choose a semester.");
return;
}
But the results keeps on getting mix up. Please help me.
If you want your code to work, you need to add loop for question:
System.out.print("\nWhich Semester? ");
// changed code!!
while(true){
String semester = st.nextLine();
if(semester.equalsIgnoreCase(First)){
break;
}else if(semester.equalsIgnoreCase(Second)){
break;
}else if(semester.equalsIgnoreCase(Third)){
break;
}else{
System.out.print("\nPlease choose a semester.");
}
}
//end of chaged code!!
System.out.print("\nThe Enrollment fee for this Semester is: "+ balance);
However this is really bad idea to base program flow control on Strings like yours.
Related
this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here
From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.
You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}
I am wondering what is the shortest way to accept different inputs from a user and make it trigger the exact same section of code. For instance, if I have if(userInputStr.equalsIgnoreCase("quarterly")) and i want it to accept different inputs (q, qrtly, etc.) to trigger the same section of code, what would I do? Any help appreciated! :)
Here is my code:
import java.util.Scanner;
public class Interest
{
static double userInputDou;
static String userInputStr;
static double rate;
static double time;
static double principal;
static double interest;
static double subinterest;
static double cNum;
static double total;
static Scanner myScanner = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Would you like to calculate simple interest or compound interest?");
userInputStr = myScanner.nextLine();
if(userInputStr.equalsIgnoreCase("simple interest"))
{
System.out.println("Please enter the rate: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
rate = (userInputDou / 100);
}
else
{
System.out.println("Please enter a integer for the rate.");
System.exit(0);
}
System.out.println("Please enter the time: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
time = userInputDou;
}
else
{
System.out.println("Please enter an integer for the time.");
System.exit(0);
}
System.out.println("Please enter the principal: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
principal = userInputDou;
}
else
{
System.out.println("Please enter an integer for the principal.");
System.exit(0);
}
interest = (principal * rate * time);
System.out.println("Your interest is $" + interest);
System.out.println("Your total payment is $" + (interest + principal));
}
else if(userInputStr.equalsIgnoreCase("compound interest"))
{
System.out.println("Please enter the rate: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
rate = (userInputDou / 100);
}
else
{
System.out.println("Please enter a integer for the rate.");
System.exit(0);
}
System.out.println("Please enter the time: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
time = userInputDou;
}
else
{
System.out.println("Please enter an integer for the time.");
System.exit(0);
}
System.out.println("Please enter the principal: ");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
principal = userInputDou;
}
else
{
System.out.println("Please enter an integer for the principal.");
System.exit(0);
}
System.out.println("Would you like to compound the interest quarterly or annually?");
userInputStr = myScanner.next();
if(userInputStr.equalsIgnoreCase("quarterly"))
{
System.out.println("For how many quarters would you like to compound the interest for?");
if(myScanner.hasNextDouble())
{
userInputDou = myScanner.nextDouble();
cNum = (userInputDou * 4);
subinterest = (principal * (1 + (rate / cNum)));
interest = Math.pow(subinterest, (cNum * time));
total = (principal + interest);
System.out.println("Your quarterly compounded interest is $" + interest);
System.out.println("Your total payment is $" + total);
}
else
{
System.out.println("Please enter an integer for the number of quarters.");
System.exit(0);
}
}
else if(userInputStr.equalsIgnoreCase("annually"))
{
cNum = time;
subinterest = (principal * (1 + (rate / cNum)));
interest = Math.pow(subinterest, time);
total = (principal + interest);
System.out.println("Your annually compounded interest is $" + interest);
System.out.println("Your total payment is $" + total);
}
else
{
System.out.println("Please enter either 'quarterly' or 'annually'.");
System.exit(0);
}
}
else
{
System.out.println("Please enter either 'simple interest' or 'compound interest'.");
System.exit(0);
}
}
}
I'm trying to write a bank account that asks the user if they want to see records, remove records, and other stuff. This is what I'm trying to produce
My program is nearly done the only problem I'm having is getting the output. I'm getting some weird error when i tried producing the output. When the output works. I'll put it inside a linked list.
public class Bank
{
public static void main(String args[]){
ArrayList<Customer> accounts = new ArrayList<Customer>();
Customer customer1 = new Customer(1, "Savings", "Dollars", 800);
Customer customer2 = new Customer(2, "Checking", "Euro", 1900);
Customer customer3 = new Customer(3, "Checking", "Pound", 8000);
accounts.add(customer1);
accounts.add(customer2);
accounts.add(customer3);
int customerID=4;
String choice;
int deposit;
int withdraw;
Scanner in = new Scanner(System.in);
Customer operation = new Customer();
boolean flag = true;
String accountType;
String currencyType;
int balance;
while(flag){
System.out.println("Select a choice:");
System.out.println("1. Existing customer");
System.out.println("2. New customer");
System.out.println("3. Quit");
String input = in.next();
//existing user
if(input.equals("1")){
System.out.println("Enter CustomerID: ");
customerID = in.nextInt();
System.out.println("Would you like to: ");
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Display account info ");
System.out.println("4. Check balance ");
choice = in.next();
if(choice.equals("1")){
System.out.println("How much would you like to deposit?");
deposit = in.nextInt();
operation.deposit(deposit);
}
else if (choice.equals("2")){
System.out.println("How much would you like to withdraw?");
withdraw = in.nextInt();
operation.withdraw(withdraw);
}
else if (choice.equals("3")){
operation.display(accounts.get(customerID));
}
else if (choice.equals("4"))
operation.balance(accounts.get(customerID));
else
System.out.println("Invalid");
}
//new user
else if(input.equals("2")){
//add new user to arraylist
int newID = customerID + 1;
System.out.println("Enter account type: ");
accountType = in.next();
System.out.println("Enter currency type: ");
currencyType = in.next();
System.out.println("Enter initial balance: ");
balance = in.nextInt();
System.out.println("Your customer ID will be: " + newID);
accounts.add(new Customer(newID, accountType, currencyType, balance));
}
else if(input.equals("3")){
System.out.println("Thanks for using this bank!");
flag = false;
}
else{
System.out.println("Invalid");
}
}
}
}
My second class:
public class Customer
{
String accountType, currencyType, info;
public int customerID, balance, amount;
Scanner input = new Scanner(System.in);
public Customer(int customerID, String accountType, String currencyType, int balance)
{
this.accountType = accountType;
this.currencyType = currencyType;
this.customerID = customerID;
this.balance = balance;
this.amount = amount;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public int deposit(int amount){
amount = input.nextInt();
if (amount >= 500) {
System.out.println("Invalid");
}
else{
balance = balance + amount;
}
return balance;
}
public int withdraw(int amount){
if (balance < amount) {
System.out.println("Invalid amount.");
}
else if (amount >= 500) {
System.out.println("Invalid");
}
else {
balance = balance - amount;
}
return balance;
}
public void display(ArrayList<Customer> accounts)
{
System.out.println("CustomerID:" + accounts.customerID);
System.out.println("Account Type:" + accounts.accountType);
System.out.println("Currency Type: " + accounts.currencyType);
System.out.println("Balance:" + accounts.balance);
}
public void balance(ArrayList<Customer> accounts) {
System.out.println("Balance:" + accounts.balance);
}
}
java.util.ArrayList won't have properties or methods such as customerID, accountType, currencyType and balance.
I guess your methods display() and balance() shoudn't take any arguments and should use the properties of the instance to print.
public void display()
{
System.out.println("CustomerID:" + customerID);
System.out.println("Account Type:" + accountType);
System.out.println("Currency Type: " + currencyType);
System.out.println("Balance:" + balance);
}
public void balance() {
System.out.println("Balance:" + balance);
}
Then, these lines
operation.display(accounts.get(customerID));
operation.balance(accounts.get(customerID));
should be
accounts.get(customerID).display();
accounts.get(customerID).balance();
There seems many more things to be corrected -- for example, usage of withdraw().
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
This is the code, I am trying to get to test whether or not a user input entered in another class file has a character other than an integer or double. I need for this piece of code to work here and with a withdraw class that I have already created underneath this one, I figured if it I can get it to work in one it will work in the other.
Thanks in advance!
Here is the code Requested:
import java.util.Scanner;
public class Bank {
double balance = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false; {
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice){
case 1:
//Deposit Money
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
}while
(!quit);
}
}
And here is the entirety of the first portion of code:
public class BankAccount {
public double balance;
public int sufficientFunds = 1;
public int insufficientFunds = -1;
public BankAccount(){
balance = 0;
}
public BankAccount (double initialBalance){
balance = initialBalance;
}
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
while (!double || !int) {
System.out.println("Invalid Input. Try again");
}
}
public double withdraw (double amount){
balance = balance - amount;
if (balance == amount){
return sufficientFunds;
}else if (balance > amount){
return sufficientFunds;
}else if (balance < amount){
System.out.println("INSUFFICENT FUNDS");
return insufficientFunds;
}
return amount;
}
public double getBalance(){
return balance;
}
}
Java is a strongly typed language, so there is no chance that the amount variable could contain anything other than a double, which is a number.
Use this for bank
import java.util.Scanner;
public class Bank {
double balance = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
public void thisShouldBeAMethod(){
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
//userChoice = in.nextInt();
String regex = "[0-9]+";
String input = in.next();
if(input.matches(regex)){
userChoice = Integer.parseInt(input);
switch (userChoice) {
case 1:
// Deposit Money
System.out.println("How Much would you like to deposit?");
double amount;
amount = in.nextDouble();
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
System.out.println("How much would you like to withdraw?");
amount = in.nextDouble();
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out
.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out
.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
}
else{
System.out.println("Invalid Input. Try again");
}
} while (!quit);
}
}
update this in BankAccount
public void deposit (double amount){
if (amount >= 0) {
balance = balance + amount;
} else {
System.out.println("Your deposit is a negative number, If you would like to withdraw please enter '0' and select Withdraw.");
}
// while (!double || !int) {
// System.out.println("Invalid Input. Try again");
// }
}
And test
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
Bank bank = new Bank();
bank.thisShouldBeAMethod();
}
}
Ok, so when accepting the input for amount, surround it with a try-catch block so that instead of simply
amount = in.nextDouble();
you'll get
try{
amount = in.nextDouble();
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
}
Additionally you'll want to wrap that in a do-while loop so that the program asks again until a valid input is accepted:
boolean inputInvalid;
double amount;
do{
System.out.println("How Much would you like to deposit?");
try{
amount = in.nextDouble();
inputInvalid = false;
}catch(InputMismatchException ime){
//What to do if this is not a numerical value
inputInvalid = true;
}
}while(inputInvalid);
Edit: due to the in.nextDouble(), the program may be continuously trying to read the \n in the buffer (which is when the user presses Enter). To avoid this, right after initializing the Scanner object (or first thing in a method if it's a class variable), add
in.useDelimiter("\n");
To the Java to end the input at that and ignore the newline character.
The else if section of deposit is not working and same is the case with else if section of no for updating the balance.
public class BankAccount
{
static double Balance;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the account holder's name...");
String Name = sc.next();
System.out.println("enter his account number...");
long AccNo = sc.nextLong();
System.out.println("enter his type of account...");
String AccTyp = sc.next();
System.out.println("enter his current balance...");
Balance = sc.nextDouble();
System.out.println("Do you want to update your balance, press y for yes and n for no...");
if(sc.next().equalsIgnoreCase("y") == true)
{
System.out.println("To withdraw money press w, To deposite the same, press d");
if(sc.next().equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(sc.next().equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else
System.out.println("Thank you for your transaction");
}
else if(sc.next().equalsIgnoreCase("n") == true)
{
System.out.println("Thank you for your transaction");
}
System.out.println("Thank you for your transaction");
}
public static double Withdraw(double a)
{
Balance = Balance - a;
return Balance;
}
public static double Deposit(double b)
{
Balance = Balance + b;
return Balance;
}
}
Don't keep invoking the next() method:
if(sc.next().equalsIgnoreCase("w") == true)
...
else if(sc.next().equalsIgnoreCase("d") == true)
Instead the code should be something like:
String response = sc.next();
if(response.equalsIgnoreCase("w"))
...
else if(response.equalsIgnoreCase("d"))
...
If 'if' block execute sc.next() then 'else' block can't execute sc.next(). Assign the input to a variable action like this.
String action=sc.next();
if(action.equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(action.equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}