How to handle invalid input in java - java

I am making a simple Bank Deposit and Withdraw code. Code works for Deposit section but at the time of withdraw it asks withdraw values 2 times. And it takes last value for withdraw amount.
I think there I need to enter scannerObject.nextLine(); somewhere, but where and how to use scannerObject.nextLine();?
Following is my sample code. There is one other class file BankAccount.java with only getter and setter methods.
package com.amit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
boolean option = true;
Scanner scanner = new Scanner(System.in);
while (option){
System.out.println("Press 1 For Deposite. Press 2 For Withdrawal. Press 3 For Exit");
boolean hasvalue = scanner.hasNextInt();
if(hasvalue){
//means user has entered integer value now check if its in 1, 2 if its other
// than this we'll take him out of program to print balance
int userValEntered = scanner.nextInt();
if (userValEntered == 1){
//code for deposite
System.out.println("Enter Amount To Deposite");
Scanner amountToDeposite = new Scanner(System.in);
account.setBalance(amountToDeposite.nextDouble());
}else if (userValEntered == 2) {
//Code for withdrawal
System.out.println("Enter Amount To Withdraw");
Scanner amountToWithdraw = new Scanner(System.in);
if (amountToWithdraw.nextDouble() >= account.getBalance()){
System.out.println("Unable to Withdraw Given Amount, Try Other Amount");
continue;
}else {
double currentBalance = account.getBalance() - amountToWithdraw.nextDouble();
account.setBalance(currentBalance);
System.out.println("Thanks for Doing Business With us");
}
}else{
//if user enters anything other than 1 or 2
break;
}
}else {
//if user enters anything other than integer
break;
}
}
//code to print balance here.
System.out.println("Your Balance is: "+account.getBalance());
}
}

thanks #Tiij7, I found my bug that I was using .nextDouble twice. Now from now on, I'll make sure to save it in variable first, before using it.
This is how I updated my code.
package com.amit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
boolean option = true;
Scanner scanner = new Scanner(System.in);
while (option){
System.out.println("Press 1 For Deposite. Press 2 For Withdrawal. Press 3 For Exit");
boolean hasvalue = scanner.hasNextInt();
if(hasvalue){
//means user has entered integer value now check if its in 1, 2 if its other
// than this we'll take him out of program to print balance
int userValEntered = scanner.nextInt();
if (userValEntered == 1){
//code for deposite
System.out.println("Enter Amount To Deposite");
Scanner amountToDeposite = new Scanner(System.in);
account.setBalance(amountToDeposite.nextDouble());
}else if (userValEntered == 2) {
//Code for withdrawal
System.out.println("Enter Amount To Withdraw");
Scanner amountToWithdraw = new Scanner(System.in);
double withdrawAmt = amountToWithdraw.nextDouble();
if (withdrawAmt >= account.getBalance()){
System.out.println("Unable to Withdraw Given Amount, Try Other Amount");
continue;
}else {
double currentBalance = account.getBalance() - withdrawAmt;
account.setBalance(currentBalance);
System.out.println("Thanks for Doing Business With us");
}
}else{
//if user enters anything other than 1 or 2
break;
}
}else {
//if user enters anything other than integer
break;
}
}
//code to print balance here.
System.out.println("Your Balance is: "+account.getBalance());
}
}

Related

Ending while loop with string not working

I have a problem with trying to end this while loop. When it runs, typing "exit" for the name part doesn't seem to register and the code continues as if "exit" was a name typed in. What I intended to happen is for "exit" to be typed in so that the loop can end. Any help? Here is the code for the class:
import java.util.*;
import java.io.*;
public class BankTest {
public static void main(String args[]) {
List<BankAccount> bank = new ArrayList<BankAccount>();
Scanner scan = new Scanner(System.in);
//enter into list the accounts and end with exit typed in
String name = "";
while (name.contains("exit")==false) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
//find highest account amount
double largestMon = bank.get(0).getBalance();
String largestPer = bank.get(0).getName();
for (int i=0;i<bank.size();i++) {
double compare = bank.get(i).getBalance();
if (compare>largestMon) {
largestMon = compare;
largestPer = bank.get(i).getName();
}
}
System.out.println(largestPer+" has the largest account with $");
}
}
I've already tried switching between != and equals() compare the strings.
Change while (name.contains("exit")==false) to while(true)
and add line if (name.equals('exit')) break; after name = scan.nextLine();
First of all you could change
name.contains("exit")==falseinto !name.contains("exit")
A better solution would be to use a while true loop and break if the name variable is equal to "exit"
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
Notice that in cases like this you shouldn't use .contains() or .equals but rather .equalsIgnoreCase()
This should work
while(true){
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}
Modify your while loop as follows:
while (true) {
System.out.println("Please enter the name(exit to stop): ");
name = scan.nextLine();
if(name.equals("exit"))
break;
System.out.println("Please enter the deposit: ");
double balance = scan.nextDouble();
scan.nextLine();
BankAccount newAccount = new BankAccount(name, balance);
bank.add(newAccount);
}

Loops in Java after user inputs values

public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");

How to store the data on every instance of do-while loop in Java?

I am currently studying Java and I need to add the values of every instance in my do-while loop. Is there some way to store the values so it won't be overwritten every loop?
import java.util.Scanner;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
int itemQty = input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
You can define a variable for the totalSum outside of the loop and then everytime the user enters a number, add itemQty to it.
int totalSum = 0;
do {
...
int itemQty = input.nextInt();
totalSum += itemQty;
...
} while (...);
// Here totalSum is the sum of all user inputs
you can update your program like this below -
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char userChar;
int itemQty = 0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty += input.nextInt();
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
char userChar;
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
totalQty+=itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next()charAt(0);
} while (userChar == 'y');
// all values entered by the user needs to be added
System.out.println("The total is: $" + (itemQty*10));
}
}
As suggested by Lino, Keep itemQty outside the loop and initialize it to zero.
Do you also want to store the value of itemQty for every loop iteration?
If yes then use ArrayList.
ArrayList<int> valuesList = new ArrayList<int>();
and change your loop code to
int itemQty=0;
int totalQty=0;
do {
System.out.println("Apples are $10");
System.out.println("How many do you want?");
itemQty = input.nextInt();
valuesList.add(itemQty*10);//New line to be added
totalQty += itemQty;
System.out.println("Do you wish to buy more? (y/n)");
userChar = input.next().charAt(0);
} while (userChar == 'y');
And then after the loop ends, display the values in each stage.
for (int i = 0; i < valuesList.size(); i++) {
System.out.println("The value of Qty in stage "+(i+1)+" is $"+valuesList.get(i));
}
And this will be your final output
Apples are $10
How many do you want?
10
Do you wish to buy more? (y/n)
y
Apples are $10
How many do you want?
5
Do you wish to buy more? (y/n)
n
The total is: $150
The value of Qty in stage 1 is $100
The value of Qty in stage 2 is $50

While-loop equals to not working properly (java bank account)

So my task is to write a bank-account program that asks wether you want to deposit or withdraw money, it asks for how much and at last if I want to continue or not, and if not it will show my current account balance. Example:
Deposit or withdraw (0-deposit, 1-withdraw):
How much?
Do you want to continue?
Balance: XX.XX
The program should be looped and break when the answer is "Y" on "Do you want to quit?".
package Account;
import java.util.Scanner;
public class bankVisit {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
bankAccount account = new bankAccount();
String respond = "N";
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
int choice = scan.nextInt();
while (respond.equals("N")) {
if (choice == 0) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.credit(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
} else if (choice == 1) {
System.out.print("Amount: ");
double total = scan.nextDouble();
account.withdraw(total);
System.out.print("Do you want to quit? ");
respond = scan.next();
}
System.out.print("Deposit or withdraw (0-deposit, 1-withdraw): ");
choice = scan.nextInt();
}
System.out.println("Balance: " + account.getBalance());
scan.close();
}
}
I get it to loop, but I dont get how I should make the loop to quit, and post my balance, it keeps looping even though "respond" not equals "N".. Any ideas? Im very new to Java so anything will do.

I'm almost finished, but how to loop the entire program?

My cash register program is nearly complete, it can process sales and returns and adds or subtracts this to the money in the register.
My only problem is that once I'm done adding values for example, the program closes and i cant figure out how to loop it back to the choice menu. I tried using a do loop and a do while loop but it yelled at me saying it had invalid input (probably because you have to press F to stop when you're checking out).
How can I loop this whole thing?
import java.util.Scanner;
import java.util.ArrayList;
public class Assignment3_000848913
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<Integer> Prices = new ArrayList<Integer>();
ArrayList<Integer> ReturnPrices = new ArrayList<Integer>();
int totalRegisterMoney = 0;
int Choice = 0;
System.out.print("What would you like to do?");
System.out.println();
System.out.print("Press 1. Process a sale");
System.out.println();
System.out.print("Press 2. Process a return");
System.out.println();
System.out.print("Press 3. Display Money in register");
System.out.println();
System.out.print("Press 4. Exit");
System.out.println();
Choice = in.nextInt();
if(Choice == 1)
{
//THIS LOOP READS IN ALL THE PRICES//
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the integer price of the item: $");
int i = in.nextInt();
Prices.add(i);
System.out.println();
}
while(in.hasNextInt());
int totalPrice = processSale(Prices);
totalRegisterMoney = totalRegisterMoney + totalPrice;
System.out.print("Your total comes to $");
System.out.println(totalPrice);
}
if(Choice == 2)
{
System.out.print("Press F when finished.");
System.out.println();
do
{
System.out.print("Enter the price of the returned item: $");
int j = in.nextInt();
ReturnPrices.add(j);
System.out.println();
}
while(in.hasNextInt());
int returnTotal = processReturn(ReturnPrices);
if(returnTotal > totalRegisterMoney)
{
System.out.print("Sorry, there's not that much money in the register.");
System.out.println();
}
else
{
totalRegisterMoney = totalRegisterMoney - returnTotal;
}
System.out.print("You've completed the return.");
System.out.println();
}
if(Choice == 3)
{
viewBalance(totalRegisterMoney);
}
}
//END OF MAIN
If you were getting that error when you did the do..while, you were doing it OK.
The problem is that after writing the 'F' to exit option 1 , the loop returns and tries to convert that 'F' into
Choice = in.nextInt();
This causes an error bucause a 'F' is not a number.
You would need to put an
in.next();
after your
while(in.hasNextInt());
This also would happen on option 2 in your code

Categories

Resources