Trying to loop switch statement through JOptionPane input using do while loop - java

The switch statement manages to compute the default case if the user places an incorrect input that doesn't match any of the following cases, but after the "incorrect statement" the code crashes and doesn't continues to the next line of code where my loop supposedly happen.
import javax.swing.JOptionPane;
public class Testing {
public static void main(String[] args) {
String input;
double transportEmission;
do {
input = JOptionPane.showInputDialog("""
Which of the following do you use to commute to school everyday?
car
bus
train""");
switch(input) {
case "car": transportEmission = 12.6; //in kg
break;
case "bus": transportEmission = 11.7; //in kg
break;
case "train": transportEmission = 0.5; //in kg
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Option, please try again");
return;
}
input = JOptionPane.showInputDialog("Did you enter either car, train or bus only (Yes/No)?");
} while ("no".equals(input)); {
}
JOptionPane.showMessageDialog(null, "Transport Emission is : " + transportEmission);
}
}

Related

Is there a way to get my program to start at the very beginning of a do while loop if an exception occurs?

I want it to start again at the most outer for loop, so that if a user messes up the input, they can sign in again and everything work just like if the program started all over again. I tried using continue statements and break statements and using the nicknames for the loops. Like
outer: do {
//loop code
}
then break outer;
The problem is when I do that, it messes up my controlling of the loop. The end statement that asks the user if they want to go back to the main menu. Right now I just have the app exit, if an exception is encountered, using return statement, but If I'm just gonna exit, I might as well just let the app crash. I want to actually resolve the situation and ask the user for valid input.
package main;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;
import model.BankAccount;
public class app {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
HashMap<String, BankAccount> accounts = new HashMap<>();
BankAccount sallyAccount = new BankAccount(1000);
BankAccount bobAccount = new BankAccount(2000);
BankAccount naomiAccount = new BankAccount();
accounts.put("Sally", sallyAccount);
accounts.put("Bob", bobAccount);
accounts.put("Naomi", naomiAccount);
String name;
BankAccount account;
int userInput;
double amount;
boolean again;
do
{
again = true;
System.out.println("Login: Enter your name.");
name = console.next();
account = accounts.get(name);
if(account == null)
{
System.out.println("Please enter a valid name.");
return;
}
do
{
System.out.println("1 - Deposit");
System.out.println("2 - Withdraw");
System.out.println("3 - View Balance");
System.out.println("4 - Logout");
userInput = console.nextInt();
switch(userInput)
{
case 1:
System.out.println("Enter amount to deposit: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.deposit(amount);
break;
case 2:
System.out.println("Enter amount to withdraw: ");
try
{
amount = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a numeric amount.");
return;
}
if(amount < 0)
{
System.out.println("You can't withdraw a negative amount");
return;
}
account.withdraw(amount);
break;
case 3:
System.out.println(account.getBalance());
break;
case 4:
again = false;
break;
default:
System.out.println("Enter a valid option.");
}
}
while(again);
System.out.println("Back to main menu? 1 - Yes, 2 - No");
try
{
userInput = console.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Please enter a number");
return;
}
}
while(userInput == 1);
}
}
package model;
public class BankAccount {
private double balance = 0;
public BankAccount() {}
public BankAccount(double balance)
{
this.balance = balance;
}
public void deposit(double amount)
{
balance = balance + amount;
}
public void withdraw(double amount)
{
if((balance - amount) < 0)
{
System.out.println("Transaction Failed: You can't withdraw more than you have.");
}
else
{
balance = balance - amount;
}
}
public double getBalance()
{
return balance;
}
}
You'll be best served by breaking up your main function in multiple functions that handle different parts of the control logic. A good rule of thumb (for beginning programmers) is a function over ~10-15 lines should probably be multiple functions, though it's not an ironclad rule.
I rewrote your program to be multiple functions, but since this seems like a homework problem I won't post the whole thing. Rather, a general strategy with some snippets.
For example, when the user enters an amount to deposit or withdraw. What your programs wants in that moment is a single double, so you could request a single double, and let another method figure out how to get it:
switch (getMenuChoice()) {
case 1:
account.deposit(getDepositOrWithdrawAmount("deposit"));
break;
case 2:
account.withdraw(getDepositOrWithdrawAmount("withdraw"));
break;
// etc.
}
Then, that function is responsible for looping infinitely until the user provides a valid value:
static double getDepositOrWithdrawAmount(String depositOrWithdraw) {
// loop infinitely until we get a valid value
while (true) {
System.out.println("Enter amount to " + depositOrWithdraw);
try {
double amount = console.nextDouble();
if (amount < 0) {
System.out.println("You can't " + depositOrWithdraw + " a negative amount.");
} else {
// valid value! return for deposit / withdraw to use
// , ending the infinite loop
return amount;
}
} catch (InputMismatchException e) {
System.out.println("Please enter a numeric amount.");
// clear the bad token from the stream
// if you don't do this, each time you
// call `nextDouble`, the same value will
// be returned, causing an infinite loop
console.next();
}
}
}
The nice thing about this function is it works in isolation:
public static void main(String[] args) {
System.out.println("Test: " + getDepositOrWithdrawal("test!"));
}
Gives this result:
Enter amount to test!
abc
Please enter a numeric amount.
Enter amount to test!
not-a-number
Please enter a numeric amount.
Enter amount to test!
-5
You can't test! a negative amount.
Enter amount to test!
1000
Test: 1000.0
This lets you test that pieces of your program are working on their own, instead of trying to debug one big program.
You can write other parts of your program as functions as well, but I'll leave that to you.

making a custom method with an array print a value

I am trying to make this method print one of the four string messages contained within String[] strArr. I have tried doing this by calling the method in the main method, by typing many different forms of simpleArray(); and I have tried filling the parenthesis, writing it several different ways but nothing has worked. I have actually been working on it for days, and usually I give up and move on to a different part of the code.
Though it may seem impractical, I do need the method to be written similarly to the way it is because my project criteria states it must contain one argument and return void.
public static void simpleArray(String[] greetings) {
String[] strArr = {"Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card", "We value your business!"};
int i = (int)(Math.random() * strArr.length);
System.out.println(strArr[i]);
}
here is my main method, where I try to call the custom method in line 6.
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray();
printStartupMessage();
Scanner keyboard = new Scanner(System.in);
Scanner keyboardDouble = new Scanner(System.in);
saveRandomBalance = getRandomBalance();
System.out.println("CHECKING BALANCE**** $" + saveRandomBalance);
System.out.println("Would you like to withdrawl from CHECKING****? Y/N");
String proceedWithWithdrawl = keyboard.nextLine();
while (!proceedWithWithdrawl.equalsIgnoreCase("y") && !proceedWithWithdrawl.equalsIgnoreCase("n")
&& !proceedWithWithdrawl.equalsIgnoreCase("yes") && !proceedWithWithdrawl.equalsIgnoreCase("no"))
{
System.out.println("Invalid response. Enter [Y] or [N].");
proceedWithWithdrawl = keyboard.next();
}
switch(proceedWithWithdrawl)
{
case "N":
case "n":
case "nO":
case "NO":
case "No":
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
break;
case "yeS":
case "YEs":
case "yEs":
case "yES":
case "YeS":
case "YES":
case "Yes":
case "yes":
case "y":
case "Y":
System.out.println("Enter amount to withdrawl: ");
amountToWithdrawl = keyboardDouble.nextDouble();
remainingBalance = saveRandomBalance - amountToWithdrawl;
remainingBalance = Math.round(remainingBalance * 100);
remainingBalance = remainingBalance/100;
if (amountToWithdrawl % 20 == 0 && amountToWithdrawl <= saveRandomBalance)
{
System.out.println("Dispensing...");
System.out.println("ACCOUNT BALANCE: $" + remainingBalance);
System.out.println("$" + amountToWithdrawl + " has been withdrawn from CHECKING****");
System.out.println("Returning card... please wait...");
System.out.println("Card returned. Thank you for using CWU Bank!");
//CallDollarBill.dollarBill();
}
else if (amountToWithdrawl > saveRandomBalance)
{
System.out.println("Insufficient Balance.");
}
else if (amountToWithdrawl % 20 != 0)
{
System.out.println("Please enter multiples of 20.");
}
//else
//{
// System.out.println("invalid input");
//}
}
}
now, the error it provides is as follows.
firstDraftFinal.java:69: error: method simpleArray in class firstDraftFinal cannot be applied to given types;
simpleArray();
^
required: String[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand that part of the problem is probably int i (and strrArr) are integers, but I do not know what to do about this. I hired a tutor, but I ran out of time. I am also aware that the switch statement is not efficient, I will be changing that.
Thank you.
Your current code specifies a parameter that is not used; while it's unclear why you would want to do this, you can simply pass null. However, maybe what you intended was to pass the list of greetings; i.e. see second version below.
class Test {
public static void main(String[] args) {
// Per your current code.
for (int i=0; i&lt10; i++) simpleArray(null);
System.out.println("");
// What you may be looking for.
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
for (int i=0; i&lt10; i++) simpleArray2(strArr);
}
public static void simpleArray(String[] greetings) {
String[] strArr = { "Welcome To CWU BANK!", "Thank you for using CWU ATM!", "Please insert DEBIT card",
"We value your business!" };
int i = (int) (Math.random() * strArr.length);
System.out.println(strArr[i]);
}
public static void simpleArray2(String[] greetings) {
int i = (int) (Math.random() * greetings.length);
System.out.println(greetings[i]);
}
}
You have compile error because you didn't pass any arguments to method that require them, just pass to your method any string array, because you don't use passed argument in this method:
public static void main(String[] args) throws IOException {
double amountToWithdrawl;
double saveRandomBalance;
double remainingBalance;
simpleArray(new String[0]);
printStartupMessage();
To continue refactor your code you may want to get rid of this argument (pay attention if other parts of code may use it) and rewrite it like this:
public static void printGreetings() {
String[] greetings = {"Welcome To CWU BANK!",
"Thank you for using CWU ATM!",
"Please insert DEBIT card",
"We value your business!"
};
int random = new Random().nextInt(greetings.length);
System.out.println(greetings[random]);
}

Trying to access a sets of variable from string (JAVA)

Given this :
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
play(1);
break;
case "2":
play(2);
break;
case "3":
play(3);
break;
default:
System.out.println("invalid");
/?? means I don't know
public static void play(1??){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
// if yes ?? ++win1
// if no ?? ++loose1
// I know how to do those loops, I don't know how to make the variable choice fit the current case (++win2 and ++loose2 ans the case 2: for example)
}
My problem, for every cases, there are a set of specific variables that has to be increment (example casevar1, win1, loose1, etc.), if the case 2 is selected, I want that the variables in the play() method now automatically refer to the proper variables (example casevar2, win2, loose2, etc.). So how do I pass that information to the play() method?
You could do somthing like this
public static void play(String s){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
if("1".equals(s)) {
if("y".equals(choice)) {
win1 ++;
} else if ("n".equals(choice)) {
loose1 ++;
}
}
if("2".equals(s)) {
if("y".equals(choice)) {
win2 ++;
} else if ("n".equals(choice)) {
loose2 ++;
}
}
}
Ok, with inspiration from you guys, I've answered my question. I did it this way :
in the main, something like that
case "1":
play(1, nbEasy, easyPos, easyNeg);
break;
case "2":
play(2, nbInter, interPos, interNeg);
break;
case "3":
//same thing with hard
and in the play() method, something like that :
public static void play(int niv, int nbGames, int nbPos, int nbNeg){
++nbGames;
System.out.print("Completed? ( (y)yes or (n)o ) ");
choice = validation.nextLine();
if (choice.equals("y")){
++nbPos;
}
else if (choice.equals("n"))
++nbNeg;
switch (niv){
case 1:
nbEasy=nbGames; easyPos=nbPos; easyNeg=nbNeg;
case 2:
nbInter=nbGames; interPos=nbPos; interNeg=nbNeg;
case 3:
//same thing with hard
}
}
It’s perfect for me, because I can add a lot of lines in the first section of the play () method, working with what has been passed with the switch in the main and at the end, I’m affecting the new values to the proper variables.
I would like to thank you all, I’m new to programming and new to this community, but for having tried a bunch of places, that place looks by far the best. You’re responsive, polite, cordial, and I will read all the rules to suit better this place, prepare more my questions and when I will be able, I will help others. This place is amazing, I love you guys.
I am not sure I fully understand your question. I think part of it is how to pass parameters to a method. Please follow the code and comments :
//I used 3 integers just for demonstration purpose
int casevar1, win1, loose1,casevar2, win2, loose2;
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//assign values
casevar1 =7; win1 =9; loose1 =0;
play(casevar1, win1, loose1); //pass appropriate variables to play method
break;
case "2":
//assign values
casevar2 =17; win2 =8; loose2 = 4;
play(casevar2, win2, loose2); //pass appropriate variables to play method
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(int casevar, int win, int loose){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
EDITED: Added an example to answer your question.
Create an object warping the data, as #David Wallace suggested:
public class Test {
public static void main(String[]arghs){
public static void main(String[]arghs){
System.out.println("Make a choice : (1), (2), (3)");
//validation is a scanner already declare elsewhere
n = validation.nextLine();
switch (n) {
case "1":
//set an object initialized to casevar =7, win =9, loose = 0
play(new DataObject(7,9, 0));
break;
case "2":
play(new DataObject(17,8, 4));
break;
case "3":
//do like case "1" / case "2"
break;
default:
System.out.println("invalid");
}//end of switch
}
//an example of a play method recieving 3 integers.
public static void play(){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//follow Aku Nour's answer
}
}
//play method receiving data object
public static void play(DataObject data){
System.out.print("Did you win? ( (y)es or (n)o ) ");
choice = validation.nextLine();
//
casevar++;
}
//as David Wallace proposed
//an object containing the 3 parameters you mentioned
class DataObject {
private int casevar; private int win; private int loose;
DataObject(int casevar, int win, int loose){
this.casevar = casevar;
this.win = win;
this.loose = loose;
}
public int getCasevar() {
return casevar;
}
public void setCasevar(int casevar) {
this.casevar = casevar;
}
public int getWin() {
return win;
}
public void setWin(int win) {
this.win = win;
}
public int getLoose() {
return loose;
}
public void setLoose(int loose) {
this.loose = loose;
}
}
}
If it doesn't answer or not clear enough don't hesitate to ask.

Control Flow in Multiple Method Program

I'm writing a simple Java program, to familiarise myself with methods, that logs the people a person has met. For instance, if I meet Alison in London, I would log the following (Format: name,gender,when,where):
Alison,F,apr2013,London
The program is built up as follows:
The user is presented with different opportunities:
Log person
Search for all people named [name]
Search for all people met [place]
Get a list of available commands
Quit
Here is the skeleton of my code:
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
while (myCommand !=5) {
if (myCommand == 1) {
writeToFile(); //Log new person
}
// Search for person type
else if (myCommand == 2) {
searchFor(); // Search for person by name
}
// Search for place
else if (myCommand == 3) {
searchFor(); // Search for person by place
}
// help
else if (myCommand == 4) {
showCommands(); // get a list of available commands
}
else if (myCommand == 5) {
exit();
}
// default
else {
System.out.println("Command not found");
}
}
}
This works just fine. However, after I choose one of the five options (log new person, search for name, search for place, help, quit), I would like to go back to the chooseCommand() method, so as to get the same options presented again, instead of having the initially chosen method loop infinitely. That is to say, after I log a new person, I want to be able to get new options, as opposed to having to log new people for all eternity, without killing the program.
// REGISTER
public void writeToFile() {
// Write to file
try {
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
System.out.println("Enter sighting: ");
for (int i = 0; i < personBlank.length; i++) {
System.out.println(personInfo[i] + ": ");
personEntry = input.next();
personBlank[i] = personEntry;
}
// change to toString() method
observed = personBlank[0] + "," + personBlank[1] + "," + personBlank[2] + "," + personBlank[3];
if (observed.equals(escape)) {
exit();
}
else {
output.write(observed); // log new person
output.newLine();
output.close();
}
back();
}
catch (IOException e){
e.printStackTrace();
}
}
Any help on this is highly appreciated!
public void someMethod() {
while(isRunning) {
chooseCommand();
}
}
Then in chooseCommand() lose the loop, make option 5 set isRunning = false instead of exit(), and use a switch statement for prettyness.
e.g.
public void chooseCommand() throws FileNotFoundException {
System.out.println("Enter command: ");
text = input.next();
myCommand = Integer.parseInt(text);
switch (myCommand) {
case 1:
writeToFile(); //Log new person
break;
case 2:
// Search for place
break;
case 3:
searchFor(); // Search for person by place
break;
// help
case 4:
showCommands(); // get a list of available commands
break;
case 5:
this.isRunning = false;
break;
default:
System.out.println("Command not found");
}
}
in the place of your code where chooseCommand() was called you could use a boolean and check that boolean is true to call chooseCommand()
java pseudocode
------------------
boolean continue=true;
while(continue)
{
System.out.println("Do you want to continue?");
Scanner scan=new Scanner(System.in);
if(scan.nextLine().equals("true"))
chooseCommand();
else
continue = false;
}

pasword masking in console window and recursive function call in java

the following java code is executed in the console window in DR.java IDE.
i have the following two problems please help me friends.
Is it possible to make password masking ?? i tried a lot by googling but none worked for me (should use only console window for excecution).
When i call the "GetLoginDetails();" inside the "ShowAdminMainMenuFun(String EmpName)" method it is showing error ([line: 148] Error: Unhandled exception type java.io.IOException).
i thought of making recursive function but it dint worked can u correct the coding and post it back.
thanking u friends
{
import java.io.*;
import java.awt.*;
import java.io.Console;
import java.util.Scanner;
/*
UserLoginAuthentiction UserLoginAuthentictionObj = new UserLoginAuthentiction();
UserLoginAuthentictionObj.GetLoginDetails();
*/
class UserLoginAuthentiction
{
static String EmployeeID,Password;
public static byte resultRole = 0;
public static void main(String[] args) throws Exception
{
GetLoginDetails(); // it works well here but not works when called againin the following code
}
static void GetLoginDetails() throws IOException
{
Scanner sc = new Scanner(System.in);
byte resultRole = 0;
byte CountForLogin = 0;
System.out.println("Totally 3 attempts ");
do
{
if(CountForLogin<3){
System.out.print("\nEnter User Name:");
EmployeeID = sc.nextLine();
System.out.print("Enter Password :");
Password = sc.nextLine();
resultRole = ValidateUserIDAndPassword(EmployeeID,Password);
// if result is zero then the login is invalid,
// for admin it is one ,
// for quality analyser it is 2
// for project developer it is 3
// for developer it is 4
if(resultRole==0)
{
System.out.println("Username & Password does not match ");
System.out.print("Retry ::");
CountForLogin++;
if(CountForLogin>2)
{System.out.println("ur attempts are over is locked");}
}
else
{
System.out.println("here t should call the appropriate employe function");
GetRoleAndAssignFun(EmployeeID,resultRole);
break;
}
}
}while(resultRole==0);
}
static byte ValidateUserIDAndPassword(String EmployeeID,String Password)
{
byte resultRole = 0;
if((EmployeeID.equals("tcs"))&&(Password.equals("tcs")))
{
resultRole = 1;
}
/*
Code for checking the arraylist and returning the validations
this method should return the roles of the users password
*/
return resultRole;
}
static void GetRoleAndAssignFun(String EmpName ,int EmpRole)
{
// System.out.println(" ");
switch(EmpRole)
{
case 1:
System.out.println(" hi " +EmpName+ " u are logged in as admin ");
ShowAdminMainMenuFun(EmpName);
break;
case 2:
System.out.println(" hi " +EmpName+ " u are logged in as QA ");
// QualityAnalyserMainMenu(EmpName);
break;
case 3:
System.out.println(" hi " +EmpName+ " u are logged in as PM ");
// ProjectMAnagerMainMenu(EmpName);
break;
case 4:
System.out.println(" hi " +EmpName+ " u are logged in as DEVeloper ");
// DeveloperMainMenu(EmpName);
break;
default:
// System.out.println(EmpName +" You dont have any roles asigned ");
break;
}
}
public static void ShowAdminMainMenuFun(String EmpName)
{
Scanner sc = new Scanner(System.in);
int loop_option=0;
do
{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(" Hi "+ EmpName + " you can perform task ussing the menu given below");
System.out.println("press the appropriate option only");
System.out.println("1.Create New Employe Profile ");
System.out.println("2.See Employee's Profile ");
System.out.println("3. LogOut ");
System.out.println("Enter the Option u need:");
int option = sc.nextInt();
switch(option)
{
case 1:
System.out.println("1.Creating New Employe Profile");
//CreateNewEmployeeProfile();
break;
case 2:
System.out.println("2.See Employee's Profile ");
// ViewEmployeeProfile();
break;
case 3:
System.out.println("3. LogOut");
System.out.println("Do u want to continue logging out ?? If yes Press 1 ..");
boolean ConformLogout = false;
ConformLogout = sc.nextBoolean();
if(ConformLogout)
{
**GetLoginDetails();** //**** error is here */ how can i call this function please help me
}
else
{
}
// LogOut();
break;
default :
System.out.println(" You .. ");
}
System.out.println("Do u want to continue to main menu ?? Press 1 to continue..");
loop_option = sc.nextInt();
}while(loop_option==1);
}
}
}
Regarding your first question,
Is it possible to make password
masking?
You can use java.io.Console class to hide the password on console window.

Categories

Resources