I have a small program I am working on. I Just put a try catch in my code and everything seems to be working except for 1 thing. I will post my code below... As you can see my try catch statement in my code it tells the program to go down to the checkNumber method for exception handling. I keep getting an error on this part...
if (input == 5){
}
The input keeps underlining red and saying "Incompatible operand types scanner and int.
Not sure what the problem is... or how to fix it.. here is my code
import java.util.ArrayList;
import java.util.Scanner;
public class BankMain
{
private double availableBal =80;
private double totalBal =100;
private double availableBal2 =480;
private double totalBal2 =500;
private double availableBal3 =80;
private double totalBal3 =100;
ArrayList<Integer> cardNum = new ArrayList<Integer>();
static Scanner input = new Scanner(System.in);
private String error; //String the error from the exception
{
error = "error";
}
public void cardNumbers(){
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
try{
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
checkNumber();
}
catch(invalidNumber err){
System.out.println("Caught Error: " + err.getError());
}
System.out.println("Thank you! You're card number is " +cardNum);
System.out.println("Type 'c' to go back to main menu.");
String value = keyboard.next();
if(value.equalsIgnoreCase("c")){
menu();
}
else if (!keyboard.equals('c')){
System.out.println("Invalid Entry!");
}
}
public void menu(){
System.out.println("ATM Menu:");
System.out.println();
System.out.println("1 = Create Account");
System.out.println("2 = Account Login");
System.out.println("3 = Exit ATM");
query();
}
public void startAtm()
{
menu();
}
public void drawMainMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection =input.nextInt();
switch(selection)
{
case 1:
viewAccountInfo();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
public void viewAccountInfo()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $"+totalBal);
System.out.println("\t--Available balance: $"+availableBal);
drawMainMenu();
}
public void viewAccountInfo2()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $"+totalBal2);
System.out.println("\t--Available balance: $"+availableBal2);
drawMainMenu();
}
public void deposit(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal =totalBal +depAmount;
availableBal =availableBal +depAmount;
}
public void checkNsf(int withdrawAmount)
{
if(totalBal -withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal =totalBal -withdrawAmount;
availableBal =availableBal -withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
public void addFunds()
{
int addSelection;
System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection =input.nextInt();
switch(addSelection)
{
case 1:
deposit(20);
drawMainMenu();
break;
case 2:
deposit(40);
drawMainMenu();
break;
case 3:
deposit(60);
drawMainMenu();
break;
case 4:
deposit(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void withdraw()
{
int withdrawSelection;
System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection =input.nextInt();
switch(withdrawSelection)
{
case 1:
checkNsf(20);
drawMainMenu();
break;
case 2:
checkNsf(40);
drawMainMenu();
break;
case 3:
checkNsf(60);
drawMainMenu();
break;
case 4:
checkNsf(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void query(){
Scanner keyboard = new Scanner(System.in);
double input = keyboard.nextInt();
if (input == 2){
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
BankMainPart2.loginCard(cardNum);
}
else if (input == 1){
cardNumbers();
}
else if (input == 3){
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
public void checkingMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection =input.nextInt();
switch(selection)
{
case 1:
viewAccountInfo2();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
private static void checkNumber() throws invalidNumber //run the check activation exception
{
if (input == 5)
{
System.out.println("");
}
else
throw new invalidNumber("invalid number");
}
public static void main(String args[])
{
BankMain myAtm = new BankMain();
myAtm.startAtm();
}
}
Class Bank Main 2
import java.util.ArrayList;
import java.util.Scanner;
public class BankMainPart2 {
public static void loginCard(ArrayList<Integer> cardNum){
BankMain main = new BankMain();
AccountMain main3 = new AccountMain();
Scanner logNum = new Scanner(System.in);
int loginInput = logNum.nextInt();
if (cardNum.contains(loginInput)) {
main3.selectAccount();
}
else {
System.out.println("Sorry, that pin number is incorrect!");
}
}
}
Your variable input is an object of Scanner which is declared globally and will be used for the method checknumber() and 5 is an int. Hence they are incompatible types.
The same statement works for method query() because for query you have locally defined a variable input which is of the type double.
What you should actually write is
if(input.nextInt() == 5){}
Related
I try to run this on the IDE and it just won't run.
Only inputting the number zero will run it.
Is it unable to leave the loop?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
do {
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
The initialization number should be done earlier. Here is the code:
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number != 0);
System.out.println("Exit");
}
}
Two changes: Move the scanner.nextInt() line inside do and change the while condition from number != 0 to number < 1 || number > 4:
Scanner scanner = new Scanner(System.in);
int number;
do {
number = scanner.nextInt();
switch(number) {
case 1:
System.out.println("Language selection");
break;
case 2:
System.out.println("Customer support");
break;
case 3:
System.out.println("Check account balance");
break;
case 4:
System.out.println("Check loan balance");
break;
}
}
while(number < 1 || number > 4);
System.out.println("Exit");
I need to make atm machine for school project.
I finished all and all is working fine, and i make the validation for the pin because it is string. So my problem is how to make validation for all other methods to check if anything else but numbers is entered to say the user that is wrong and to return him on the start of that method. All variables are stored into array as integers.
So here is my code please help i tried so many things and i cant make it work..
public class Banka {
static Scanner skener = new Scanner(System.in);
static String pin[] = {"1234","2345","3456","4567","5678"};
static String username[] = {"Mate","Nathan","John","Michelle","Angelina"};
static int balance[] = {200,100,250,150,300};
static boolean overdraft[] = {true,true,false,true,false};
static int index;
public static void main(String[] args) {
login();
}
public static void login() {
Date datum = new Date();
System.out.println("" +datum);
System.out.println("------------------------------");
System.out.println("Welcome to the Illuminati Bank \n Please log in with your PIN");
String login = skener.next();
checkpin(login);
for (int i = 0; i< pin.length; i++) {
if (login.matches(pin[i])) {
index = i;
System.out.println("\nWelcome " + username[index]);
Menu();
}
}
System.out.println("Wrong PIN entered, please login again \n");
login();
}
public static void Menu() {
System.out.println("Please select an option");
System.out.println("\n 1.View Bank Statement \n 2.Deposit \n 3.Withdraw \n 4.Change Pin \n 5.Exit \n");
int choice = skener.nextInt();
switch (choice) {
case 1: statement();
break;
case 2: deposit();
break;
case 3: withdraw();
break;
case 4: change();
break;
case 5: exit();
break;
default: System.out.println("Incorrect Choice ");
Menu();
}
}
public static void statement() {
switch(index) {
case 0: case 1: case 2: case 3: case 4:
System.out.println("" +username[index]+ ", your balance is: " +balance[index]+ "€");
if (overdraft[index] == true) {
System.out.println("You are entitled to overdraft");
}
else {
System.out.println("You are NOT entitled to overdraft");
}
Menu();
}
}
public static void deposit() {
System.out.println("" +username[index]+ ", how much you wish to deposit?");
int deposit = skener.nextInt();
balance[index] = balance[index] + deposit;
System.out.println("Thank you, you deposited " +deposit+ "€, now you have " +balance[index]+ "€ total");
depositm();
}
public static void depositm(){
System.out.println("\n 1.Deposit more \n 2.Exit to menu");
int more = skener.nextInt();
switch (more) {
case 1: deposit();
break;
case 2: Menu();
default: System.out.println("Wrong choice, please choose again");
depositm();
}
}
public static void withdraw() {
System.out.println("" +username[index]+ ", how much you wish to withdraw?");
int withdraw = skener.nextInt();
if (overdraft[index] == true) {
balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
if(overdraft[index] == false && balance[index] >= withdraw)
{balance[index] = balance[index] - withdraw;
System.out.println("Thank you, you withdrawed the money, now you have " +balance[index]+ "€");
Menu();
}
else {
System.out.println("You have insufficient funds \nPlease try again");
withdraw();
}
}
public static void change() {
System.out.println("" +username[index]+ ", do you want to change your pin?");
System.out.println("Press 1 to change or 2 to exit to menu");
int change = skener.nextInt();
switch (change) {
case 1: System.out.println("Please enter new PIN");
pin[index] = skener.next();
System.out.println("You successfully changed your PIN");
Menu();
case 2: System.out.println("Your PIN remains unchanged");
Menu();
default: System.out.println("Wrong choice, please choose again");
change();
}
}
public static void exit(){
System.out.println("Goodbye " +username[index]+ ", Illuminati Bank wish you all the best \n");
login();
}
public static int checkpin(String x){
while(!x.matches("\\d{4}")){
System.err.println("\n Error.\n Please enter 4 digit pin.");
login();
}
return 0;
}
}
so if any one can help me how to validate all other methods with user inputs where is INTs that would be great.
Try this
String input = "xxxx";
int pin;
try{
pin = Integer.parseInt(input);
}catch(NumberFormatException e){
// input contains letters or symbols.
}
Or here's another one using the Character class.
String input = "xxxx";
boolean allDigits = true;
for(char ch: input.toCharArray()){
if(!Character.isDigit(ch)) {
allDigits = false;
break;
}
}
if(allDigits){
// input contains only digits.
}
Edit: Answering this comment.
You can modify your method like this,
public static void checkpin(String x) {
if (x.length() == 4) {
try {
Integer.parseInt(x);
login();
} catch (NumberFormatException e) {
System.err.println("\n Error.\n Invalid pin.");
}
} else {
System.err.println("\n Error.\n Please enter 4 digit pin.");
}
}
this way the method login() is called only if the pin has 4 digits and all the digits are numbers.
import java.util.Scanner;
public class allPurpose {
public static void main(String[] args) {
theMain();
}
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void subtraction() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Subtraction\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a - b);
System.out.println("\n \t Subtraction: " + c);
System.out.println("\n!continue");
System.out.println("1. Subtraction");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
subtraction();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void multiplication() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Multiplication\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a * b);
System.out.println("\n \t Multiplication: " + c);
System.out.println("\n!continue");
System.out.println("1. Multiplication");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
multiplication();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void division() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Division\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a / b);
System.out.println("\n \t Division: " + c);
System.out.println("\n!continue");
System.out.println("1. Division");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
division();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void table() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Table\n");
System.out.print("Enter Number to get Table of it \t");
int a = sc.nextInt();
for (int i = 1; i<=10; i++){
int b = a*i;
System.out.println(a + " * " + (i) + " = " +b);
}
System.out.println("\n!continue");
System.out.println("1. Table");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
table();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void squareAndCube() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter one number to check its Square and Cube \t ");
int a = sc.nextInt();
int s = (a * a);
int c = (a * a * a);
System.out.println("\t Square: " + s + "\n \tCube: " + c);
System.out.println("\n!continue");
System.out.println("1. Square and Cube");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
squareAndCube();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
public static void exit() {
System.out.println("\n \tThank you have a nice day ahead! :)");
}
}
I am making calculator in java with many features
We can see that I have added following code on every method
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
just the difference is second line of every method is different, in above example code its
System.out.println("1. Addition");
in above example its addition according to the method name (in Addition method it used so )
in subtraction method it is subtraction
and so on
so can we make one method to keep all of the above code and in that code also we do something which auto catch second line according to method in which we are using
like in division second line of it will System.out.println("1. Division"); which auto catch according to the method
First of all, System.out.println is not the only place where your methods differ, but also (more important) in case 1 of switch construct where each method recursively calls itself. Second, there is a problem with your design, whose solution will also solve the original problem. Notice that from each method you are calling another method, even in the case when user requested going back to Main Menu. Stack gets larger and larger! So let's first rewrite theMain method:
public static void theMain() {
System.out.println("Welcome to All purpose java Programme \n Please select from the following:");
Scanner sc = new Scanner(System.in);
int n = 0;
while (n != 7) {
System.out.println("========MENU=========");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Table");
System.out.println("6. Square and Cube");
System.out.println("7. Exit");
n = sc.nextInt();
switch (n) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
break;
case 5:
table();
break;
case 6:
squareAndCube();
break;
case 7:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
}
As you can see, we are in the loop which breaks in case that user wants to leave the program.
Now let's rewrite one of methods:
public static void addition() {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
if (!proceed("Addition"))
break;
}
}
And finally, code of proceed method:
public static bool proceed(String method) {
System.out.println("\n!continue");
System.out.println("1. " + method);
System.out.println("2. Main Menu");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
return true;
case 2:
return false;
default:
System.out.println("Invalid input");
break;
}
}
Notice that exit is now only possible from Main Menu.
Answer to your question - method name can be retrieved through reflection, but I believe that is an overkill for this simple program.
Consider using interfaces to make more generic methods; for example, addition/subtraction/multiplication and division can be modeled as one method as follows:
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator("Addition", (a,b) -> a+b);
break;
case 2:
doCalculator("Subtraction", (a,b) -> a-b);
break;
case 3:
doCalculator("Multiplication", (a,b) -> a*b);
break;
case 4:
doCalculator("Division", (a,b) -> a/b);
break;
The generic calculator which takes two inputs, and outputs one value:
public static void doCalculator(String title, Calculator calc) {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected "+title+"\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = calc.calculate(a, b);
System.out.println("\n \t "+title+": " + c);
System.out.println("\n!continue");
System.out.println("1. "+title);
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
switch (n) {
case 1:
doCalculator(title, calc);
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
sc.close();
}
The key is to use an interface which models the calculation:
interface Calculator {
int calculate(int a, int b);
}
You can create other interfaces which closely model other types of calculations to expand the flexibility of this approach.
You can avoid using reflection if you add a simple interface:
public class allPurpose {
//All current methods here
interface Action{
void doOption();
}
}
Then, just index into the array of your methods.
In theMain() you can do:
public static void theMain() {
//Other code here
//instead of switch statement do:
Action[] initialOptions = new Action[] {
new Action() { public void doOption() { addition(); } },
new Action() { public void doOption() { subtraction(); } },
new Action() { public void doOption() { multiplication(); } },
new Action() { public void doOption() { division(); } },
new Action() { public void doOption() { table(); } },
new Action() { public void doOption() { squareAndCube(); } },
new Action() { public void doOption() { exit(); } },
};
int n = sc.nextInt();
if(n < 1 || > 7)
System.out.println("Invalid input");
else
actions[n-1].doOption();
}
Use a helper method in the other methods, where repeat is the current method:
public static void continueOptions(int i, Action repeat){
Action[] options = new Action[] {
repeat,
new Action() { public void doOption() { theMain(); } },
new Action() { public void doOption() { exit(); } },
};
if(i < 1 || > 3)
System.out.println("Invalid input");
else
options[i-1].doOption();
}
After this, for example addition would look like:
public static void addition() {
Scanner sc = new Scanner(System.in);
System.out.println("\nSelected Addition\n");
System.out.print("Enter one Number \t");
int a = sc.nextInt();
System.out.print("Enter another Number\t");
int b = sc.nextInt();
int c = (a + b);
System.out.println("\n \t Addition: " + c);
System.out.println("\n!continue");
System.out.println("1. Addition");
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
int n = sc.nextInt();
continueOptions(int i, new Action() { public void doOption() { addition(); } });
}
You can pass a parameter to a method and use switch case inside that method :
public static void callthismethod(int number){
System.out.println("\n!continue");
switch (number) {
case 1 : System.out.println("1. Addition");break;
case 2 : System.out.println("1. Subtraction");break;
case 3 : System.out.println("1. Multiplication");break;
..............
..............
..............
}
System.out.println("2. Main Menu");
System.out.println("3. Exit");
System.out.print("Select one option \t");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
switch (n) {
case 1:
if(number == 1){
addition();
}
else if(number == 2){
subtraction();
}
else if(number == 3){
multiplication();
}
...........
...........
...........
break;
case 2:
theMain();
break;
case 3:
exit();
break;
default:
System.out.println("Invalid input");
break;
}
}
In this class of Bank ,there are basic functions of Bank , however the real problem is in the switch case loop.
class Bank{
private int Balance;
private int Withdrawal;
private int Deposit;
private int AccountNumber;
void Transaction(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the account number to whose account you want
to transfer money");
AccountNumber = input.nextInt();
System.out.println("Enter your current Balance");
Balance= input.nextInt();
}
void Display(){
System.out.println("Account number "+AccountNumber);
System.out.println("Balance is "+ Balance);
}
void deposit(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to deposit");
int n =input.nextInt();
Balance+=n;
}
void withdraw(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount to withdraw");
int n =input.nextInt();
try {
if(n>Balance)
throw new Exception("The balance you have is insufficient");
}
catch(Exception e){
System.out.println(e);
}
}//void
I am trying to rerun the switch case loop, after inputing one value , i want it to ask user again all the options, i tried to use continue statement , but it shows error of continue outside the loop.Please help
public static void main(String args[])throws Exception{
Bank b1=new Bank();
Scanner input = new Scanner(System.in);
System.out.println("Enter the number corrosponding to your option ");
System.out.println("1 Set ");
System.out.println("2 Display ");
System.out.println("3 Deposit");
System.out.println("4 Withdraw");
System.out.println("5 Exit");
int num=input.nextInt();
switch(num){
case 1:
b1.Transaction();
//int c =input.nextInt();
//wants user to input value again so switch loop works
//again
break;
case 2:
b1.Display();
break;
case 3:
b1.deposit();
break;
case 4:
b1.withdraw();
break;
case 5:
return;
}
}//psvm
}
You could surround the switch in a
do{
int num=input.nextInt();
switch(num){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
return;
}
}while(num!=some_value_to_exit_switch);
}
}
I'd place the switch content in a while loop with a boolean flag, then it will re-run until you are satisfied with the input~
I made an ATM program. I have a try catch that will ask for the user to type in their pin number. The pin number must be 5 digits. So the exception will check if it is 5 digits or not but the exception handling is not working. No matter what number I type in, it always says invalid number.
Here is my code the try catch is at the top of the program and the exception handling checkNumber is at the bottom of the program..
import java.util.ArrayList;
import java.util.Scanner;
public class BankMain
{
private double availableBal = 80;
private double totalBal = 100;
private double availableBal2 = 480;
private double totalBal2 = 500;
private double availableBal3 = 80;
private double totalBal3 = 100;
ArrayList<Integer> cardNum = new ArrayList<Integer>();
static Scanner input = new Scanner(System.in);
private String error; // String the error from the exception
{
error = "error";
}
public void cardNumbers()
{
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
try
{
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
checkNumber();
}
catch (invalidNumber err)
{
System.out.println("Caught Error: " + err.getError());
}
System.out.println("Thank you! You're card number is " + cardNum);
System.out.println("Type 'c' to go back to main menu.");
String value = keyboard.next();
if (value.equalsIgnoreCase("c"))
{
menu();
}
else if (!keyboard.equals('c'))
{
System.out.println("Invalid Entry!");
}
}
public void menu()
{
System.out.println("ATM Menu:");
System.out.println();
System.out.println("1 = Create Account");
System.out.println("2 = Account Login");
System.out.println("3 = Exit ATM");
query();
}
public void startAtm()
{
menu();
}
public void drawMainMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch (selection)
{
case 1:
viewAccountInfo();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
public void viewAccountInfo()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $" + totalBal);
System.out.println("\t--Available balance: $" + availableBal);
drawMainMenu();
}
public void viewAccountInfo2()
{
System.out.println("Account Information:");
System.out.println("\t--Total balance: $" + totalBal2);
System.out.println("\t--Available balance: $" + availableBal2);
drawMainMenu();
}
public void deposit(int depAmount)
{
System.out.println("\n***Please insert your money now...***");
totalBal = totalBal + depAmount;
availableBal = availableBal + depAmount;
}
public void checkNsf(int withdrawAmount)
{
if (totalBal - withdrawAmount < 0)
System.out.println("\n***ERROR!!! Insufficient funds in you accout***");
else
{
totalBal = totalBal - withdrawAmount;
availableBal = availableBal - withdrawAmount;
System.out.println("\n***Please take your money now...***");
}
}
public void addFunds()
{
int addSelection;
System.out.println("Deposit funds:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
addSelection = input.nextInt();
switch (addSelection)
{
case 1:
deposit(20);
drawMainMenu();
break;
case 2:
deposit(40);
drawMainMenu();
break;
case 3:
deposit(60);
drawMainMenu();
break;
case 4:
deposit(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void withdraw()
{
int withdrawSelection;
System.out.println("Withdraw money:");
System.out.println("1 - $20");
System.out.println("2 - $40");
System.out.println("3 - $60");
System.out.println("4 - $100");
System.out.println("5 - Back to main menu");
System.out.print("Choice: ");
withdrawSelection = input.nextInt();
switch (withdrawSelection)
{
case 1:
checkNsf(20);
drawMainMenu();
break;
case 2:
checkNsf(40);
drawMainMenu();
break;
case 3:
checkNsf(60);
drawMainMenu();
break;
case 4:
checkNsf(100);
drawMainMenu();
break;
case 5:
drawMainMenu();
break;
}
}
public void query()
{
Scanner keyboard = new Scanner(System.in);
double input = keyboard.nextInt();
if (input == 2)
{
BankMainPart2 main2 = new BankMainPart2();
System.out.println("Please enter your 5 digit card number.");
BankMainPart2.loginCard(cardNum);
}
else if (input == 1)
{
cardNumbers();
}
else if (input == 3)
{
System.out.println("Thank you, have a nice day!");
System.exit(0);
}
}
public void checkingMenu()
{
AccountMain main3 = new AccountMain();
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
switch (selection)
{
case 1:
viewAccountInfo2();
break;
case 2:
withdraw();
break;
case 3:
addFunds();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
private static void checkNumber() throws invalidNumber // run the check activation exception
{
if (String.valueOf(input).length() != 5)
{
throw new invalidNumber("invalid number");
}
else
{
System.out.println("Works!");
}
}
public static void main(String args[])
{
BankMain myAtm = new BankMain();
myAtm.startAtm();
}
}
This code snippet looks fine:
if (String.valueOf(input).length() != 5)
{
throw new invalidNumber("invalid number");
}
else
{
System.out.println("Works!");
}
As long as you don't realize that input is not the double variable declared locally somewhere:
double input = keyboard.nextInt()
instead it's an instance of java.util.Scanner (!)
static Scanner input = new Scanner(System.in)
And Scanner.toString() is certainly not the PIN you want.
Why you are having three different instances of Scanner class.. That is what making the program confusing..
In the compareNumber() method, you are actually checking the value of input, which is an instance of Scanner.. It's better to use it like this: -
checkNumber(input.nextInt())
And add the number to the list in your checkNumber(int num) method..
Of course I am not saying that it is a good way of coding.. But it will solve your problem for the time being..
Else, there are so many issues with your code..
This is your try-catch block: -
try {
System.out.println("Please select a 5 digit card number");
cardNum.add(input.nextInt());
checkNumber();
} catch (invalidNumber err) {
System.out.println("Caught Error: " + err.getError());
}
And this is your checkNumber() method : -
private static void checkNumber() throws invalidNumber
{
if (String.valueOf(input).length() != 5) {
throw new invalidNumber("invalid number");
}
else {
System.out.println("Works!");
}
}
Now you must see that you are using input as a parameter to String.valueOf(input).
But you have declared 'input` as an instance of Scanner before your try-catch block..
Scanner cards = new Scanner(System.in);
Scanner input = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
This code is in your codeNumbers() method..
So, clearly your input can never actually contain a user input, rather a hashcode representing the object new Scanner(System.in).
So, its better that you pass the integer input from user to checkNumber() method..
************ MODIFICATION Needed in Code..
So, your checkNumber()` will be modified as: -
private static void checkNumber(int number) throws invalidNumber
{
if (String.valueOf(number).length() != 5) {
throw new invalidNumber("invalid number");
}
else {
System.out.println("Works!");
}
}
And your call to this method in try-catch block will change to this: -
try {
System.out.println("Please select a 5 digit card number");
int number = input.nextInt();
cardNum.add(number);
checkNumber(number);
} catch (invalidNumber err) {
System.out.println("Caught Error: " + err.getError());
}
Your code checks that String.valueOf(input) has a length of 5 characters. But input is not the number entered by the user. It's the object of type Scanner that is used to parse what the user enters. So the result of String.valueOf(input) is probably something like java.util.Scanner#B09876.