Java ATM project logical error(s) - java

So here's my Source code :
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
public class ATM {
String names []= {"Nikhil", "Furrqaan", "Raj", "Saron", "Abishiek", "Aditya"};
static int pin_no;static int card_no;
static int card[]={1806978,1244668,5769124,7658301,6571354,5155499};
static int pin[]={4444, 3333, 2222, 1111, 6666, 7988};
int balance []={17867, 23345, 24670, 37532, 43637, 37356};
int account[]={219075286,156482798,456482748,465295772,665793758,565738957};
int f,ch,z;
static int r = 0;
static int opt=0;
Scanner s=new Scanner(System.in);
public static void main(String args []) {
int pincode=0;
int repeat=0;
ATM k=new ATM();
do{
k.info();
k.login();
for(int choice=0;choice<=5;choice++)
if(card_no==card[choice] && pin_no==pin[choice]){
k.menu(choice);
break;
}else{
System.out.println("Wrong card no. or pincode");
break;
}
k.End(repeat);
}while(k.End(repeat)==0);
}
void info(){
Calendar calender = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat(" dd EEEEEEEEE',' yyyy ");
SimpleDateFormat timeformatter = new SimpleDateFormat(" hh:mm:ss a");
System.out.println("");
System.out.println(" **************************************************************** ");
System.out.println(" *** HSBC's ATM **** ");
System.out.println(" **************************************************************** ");
System.out.println(" Date - "+ dateformatter.format(calender.getTime()));
System.out.println(" Time - "+timeformatter.format(calender.getTime()));
System.out.println(" **************************************************************** ");
System.out.println("");
}
void login (){
System.out.println(" >> Enter card number - ");
card_no=s.nextInt();
System.out.println(" >> Enter pin number - ");
pin_no= s.nextInt();
}
void menu (int choice){
System.out.println(" Welcome "+names[choice]);
System.out.println(" Your Account no: is " + account[choice]);
System.out.println(" ############################################### ");
System.out.println(" >>> [1]. Cash Withdrawal ");
System.out.println("");
System.out.println(" >>> [2]. Fast Cash ");
System.out.println("");
System.out.println(" >>> [3]. Cash Deposit ");
opt=s.nextInt();
switch (opt){
case 1:
Calendar calender = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat(" dd'/'MM ");
SimpleDateFormat timeformatter = new SimpleDateFormat(" HH:mm ");
ATM k=new ATM();
int ammount;
System.out.println(" ========================== ");
System.out.println(" CASH WITHDRAWAL ");
System.out.println(" ========================== ");
System.out.print(" Enter amount to withdraw - Rs.");
ammount=s.nextInt();
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
System.out.println(" Please wait while we process your request...");
if (ammount>balance[z]){
System.out.println(" You do not have sufficient balance in your account.");
k.menu(choice);
for(z=1;z<=1000000000;z++)
System.out.print("\f");
}else if (ammount>25000){
System.out.println(" The daily limit for cash withdrawal is Rs.25000 .");
k.menu(choice);
}else{
balance[z]=balance[z]-ammount;
System.out.println("");
System.out.println(" You have withdrawn Rs."+ammount+" from your account.");
System.out.println(" Please collect the cash.");
System.out.println(" Current Balance - Rs."+balance[z]);
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
}
break;
case 2:
int fast[]={100,500,1000,5000};
System.out.println(" ========================== ");
System.out.println(" FAST CASH WITHDRAWAL ");
System.out.println(" ========================== ");
System.out.println(" Please select a desired amount.");
System.out.println(" (1) Rs. 100 ");
System.out.println(" (2) Rs. 500 ");
System.out.println(" (3) Rs. 1000 ");
System.out.println(" (4) Rs. 5000 ");
System.out.print(" Your choice ? ");
ch=s.nextInt();
if (fast[ch-1]>balance[z])
{
System.out.println(" You do not have sufficient balance in your account.");
}else{
switch(ch)
{
case 1:
balance[z]=balance[z]-fast[ch-1];
break;
case 2:
balance[z]=balance[z]-fast[ch-1];
break;
case 3:
balance[z]=balance[z]-fast[ch-1];
break;
case 4:
balance[z]=balance[z]-fast[ch-1];
break;
}
}
System.out.println("");
System.out.println(" You have withdrawn Rs. "+fast[ch-1]+" from your account.");
System.out.println(" Please collect the cash.");
System.out.println(" Current Balance - Rs."+balance[z]);
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
break;
case 3:
System.out.println(" ========================== ");
System.out.println(" CASH DEPOSIT ");
System.out.println(" ========================== ");
System.out.print(" Enter amount to deposit - Rs.");
int deposite =s.nextInt();
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
System.out.println(" Please wait while we process your request...");
System.out.println("");
System.out.println(" You have deposited Rs."+deposite+" to your account.");
System.out.println(" The amount will be credited shortly.");
System.out.println(" Current Balance - Rs."+balance[z]+" + Rs."+deposite);
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
break;
case 4:
System.out.println(" ========================== ");
System.out.println(" BALANCE ENQUIRY ");
System.out.println(" ========================== ");
System.out.println(" Account Number - "+card[z]);
System.out.println(" Available Balance - Rs."+balance[z]);
System.out.println(" ::::::::::::::::::::::::::::::::::::::::::::::");
System.out.println(" Please collect the reciept...");
}
}
int End(int repeat){
ATM k=new ATM();
System.out.println();
System.out.println(" What would you like to do next? ");
System.out.println(" [1]. Enter main menu. ");
System.out.println(" [2]. Exit. ");
int option=s.nextInt();
switch (option){
case 1:
repeat=0;
break;
case 2:
repeat=1;
break;
default:
System.out.println("Please check input.");
}
return repeat;
}
}
When ever the only card number and pincode combination that works is the very first one. Everything else Prints the error message i.e "Wrong pincode or card number." And the last function of the program (void repeat) prints the "What would you like to do next?" part twice. Any help is appreciated.

Lets start with the second problem. You are calling the End method twice. So no wonder it prints twice.
k.End(repeat);
}while(k.End(repeat)==0);
Now it works only for the first combination because you are breaking the loop in else part as well. So, it never checks for second value onwards
for(int choice=0;choice<=5;choice++)
if(card_no==card[choice] && pin_no==pin[choice]){
k.menu(choice);
break;
}else{
System.out.println("Wrong card no. or pincode");
break;
}

Comment one line code k.End(repeat); above while condition and have a try. It will only display once then.
//k.End(repeat);
} while (k.End(repeat) == 0);

I don't immediately see what's wrong here, but two more general observations:
1). Don't write all this and then start testing. Work in smaller pieces. Test the login() function, does it reliably return the two numbers entered by the user? Once you have confidence int that test the verifification of those two numbers against your array, and so on.
2). Use a debugger. Just stepping through your code and examining a few variables would quickly show you what's happening.

Related

Q: Doing multiple loops and multiple if-statements and if-else-statements | RENTAL CAR CALCULATOR PROJECT

my instructions on the project were as followed:
Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator
Ask each user for:
Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.) Days rented Calculate the (For each customer):
Rental cost, Taxes, Total Due. There are three different rental options with separate rates: Economy # 31.76, sedan # 40.32, SUV # 47.56. [Note: only whole day units to be considered (no hourly rates)].
Sales tax is = to 6% on the TOTAL.
Create summary data with:
The number of customers Total money collected. Also, Include IPO, algorithm, and desk check values (design documents).
{WHAT I HAVE GOING AND MY QUESTION(S)}
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);
while ( !checkRunOrQuit ) {
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
switch ( cus ) {
case 0: System.out.println("End of application");
System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
break;
case 1: checkRunOrQuit = true;
break;
default:
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry: ");
in.next();
}
}
while( !chooseTypeVehicle ) { // --> simplified comparison
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
carType = in.nextInt();
chooseTypeVehicle = true;
switch ( carType ) {
case 1: dailyFee = 31.76;
break;
case 2: dailyFee = 40.32;
break;
case 3: dailyFee = 47.56;
break;
default:
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
chooseTypeVehicle = false;
break;
}
} catch (InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next(); // -> you forgot this one.
}
}
while ( !numberOfDAysChosen ) {
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
} else {
nonTaxTotal = (dailyFee * days);
total = (nonTaxTotal * 1.06);
fullTotal+=total;
numberOfDAysChosen = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next();
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
}
}
How would I make this program loop back to prompting the user: "Press 1 to enter Rental Calculator or else press 0 to quit\". After the "days rented input is entered?
[Note: Once the days rented is input, I was wanting a total calculation but not a summary. However, I want the summary info when the program is exited.]

How to set limit on input from 0-100 Java

So this is my code: I need to set a limit on the input of the grades in the switch statement so that it will not go over 100 and under 0. If anyone could help, that would be incredible. Thanks.
import java.util.Scanner;
public class assigment1{
static Scanner key = new Scanner(System.in);
public static void main(String[] args){
int number;
System.out.println("Student Grade System");
System.out.println("====================");
System.out.println("");
System.out.println(" 1) Enter student details");
System.out.println(" 2) Dsiplay student grades");
System.out.println(" 3) Display student statistics");
System.out.println(" 4) Display full transcript");
System.out.println(" 0)Exit system");
System.out.println(" ");
System.out.print("Select an option [0-4]>>");
Scanner input= new Scanner(System.in);
number=input.nextInt();
switch(number){
case 1:
System.out.print("Entering Student Detials");
System.out.print("========================");
System.out.print(" Student number: ");String a =key.nextLine();
System.out.print(" Programing Grade: ");number=input.nextInt();
System.out.print(" web Development Grade: ");number=input.nextInt();
System.out.print(" Mathematics Grade: ");number=input.nextInt();
System.out.print(" Critical Thinking Grade: ");number=input.nextInt();
System.out.print(" Operating System Grade: ");number=input.nextInt();
System.out.print(" Computer Archetecture Grade: ");number=input.nextInt();
break;
case 2:
System.out.println("Display stuent grades");
break;
case 3:
System.out.println("Display student statistics");
break;
case 4:
System.out.println("Display full transcript");
break;
default:
System.out.println("Thanks for using the system");
break;
You could write a function like this:
(didn't tried this code)
private int getNumberFrom0To100() {
Scanner in = new Scanner(System.in);
int result;
do {
result = in.nextInt();
} while(result < 0 || result > 100);
return result;
}
and use it at your needed position:
number = getNumberFrom0To100();
Else have a look at the delimiter function where you can pass regex:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)
Scanner s = new Scanner(input).useDelimiter("^[1]?[0-9]?[0-9]$");
you can use this code , You must write This code Before Switch Case :
Scanner in = new Scanner(System.in);
System.out.println("Enter The number");
int score = in.nextInt();
while(score<0||score>100){
System.out.println("You Entered the wrong number , Enter The number Again :");
score = in.nextInt();
}
Here is a one-liner to fit in your code's logic and display
Solution
while((number = Math.abs(input.nextInt())) > 100)
System.out.println("Invalid input. Try Again");
Console
537
Invalid input. Try Again
-537
Invalid input. Try Again
-2
Attention
If user enters -2 for example, it will take it as a valid input since 2 which is abs(-2) is contained between 0 and 100.

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

Use Loop to print out each monthly rent, Threshold [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Use a Loop to print out each monthly rental from the array that falls below the user entered threshold
This was a question I received from my lecturer, I require help because I simply have no idea where to even start. Here is my complete code for the Program, it is the last case.
import java.util.Scanner ;
public class jakeGrim {
public static void main(String[] args) {
// Local variable
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
{
switch (option) {
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
{
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +(totalSum));
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
case 5:
Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
System.out.println("
break;
default:
System.out.println("Invalid selection");
break;
}
}
}while (option!=0);
}
}
Well,your program has several flaws which should be improved for better performance.
There is no need of braces before switch.So,delete the braces{ before the switch statement!
Again,there is no need of braces { in case 2 and } before break statement of case-2. You better leave it as it is.
Add these lines of code in your case 5: after deleting previous data into that.
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
Lastly,you simply need to edit do-while condition,set it as do{...}while(option>=1 && option<=5);
Also, as a matter of fact,try to indent your code properly to give it a better feel! It will make others go through your code and sincerely help you!
Correct working code :-
import java.util.Scanner;
public class jakeGrim {
public static void main(String[] args) {
int option;
String squareFootage="";
int noBed = 0;
double totalSum =0;
String propertyCode="";
String propertyType="";
String threshold="";
Scanner input = new Scanner( System.in );
Scanner user_input = new Scanner( System.in );
double[] array = new double[12];
do{
// Display menu graphics
System.out.println(" ");
System.out.println("| *****Rental Menu******* |");
System.out.println("| 1. Enter rental property Details ");
System.out.println("| 2. Enter monthly rent ( 12 Months ) ");
System.out.println("| 3. Display Annual Rent");
System.out.println("| 4. Display rental report ");
System.out.println("| 5. Display Monthly rents falling below a certain threshold ");
System.out.println(" ");
System.out.println(" Please Select an option: ");
option = input.nextInt();
switch (option){
case 1:
System.out.println("Enter Rental Details: ");
System.out.println("Property Code: ");
propertyCode = user_input.next();
System.out.println("Property Type: ");
propertyType = user_input.next();
System.out.println("Square Footage: ");
squareFootage = user_input.next();
System.out.println("Number Of bedrooms ");
noBed = input.nextInt();
break;
case 2:
Scanner keyboardScanner = new Scanner(System.in);
for (int i = 0; i < 12; i++) {
System.out.println("Enter Rental for month[" +( i +1)+ "]");
array[i] = keyboardScanner.nextDouble();
}
//So now, we need to do something with that array and sum up all the values in that array.
for (int i = 0; i < array.length; i++){
System.out.println(array[i]);
totalSum += array[i];
}
break;
case 3:
System.out.println("The annual rent for propery code "+propertyCode+" is: " +totalSum);
break;
case 4:
System.out.println(" Property Code: "+propertyCode);
System.out.println(" Property Type: "+propertyType);
System.out.println(" Square Footage: "+squareFootage);
System.out.println(" Number of Bedrooms: "+noBed);
System.out.println("");
System.out.println("");
for(int i = 0; i<12; i++)
System.out.println("Rental for month " + (i+1) + " : " + array[i]);
break;
case 5:
// Scanner user_input = new Scanner( System.in );
System.out.println("Enter the Rental Threshold: ");
threshold = user_input.next();
for(int i=0;i<array.length;i++){
if(Integer.valueOf(threshold)>array[i])
System.out.println("Month "+(i+1)+" has the rent falling below the threshold range as the rent is "+array[i]);
}
System.out.println("");
break;
default:
System.out.println("Invalid selection");
break;
}
} while (option>=1 && option<=5);
}
}

Return Switch case to main program in Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know this is an easy question, but I am new to Java and am so lost. All that is left to do in my program is output a message saying something like "Invalid input, try again" at the end of each case in my program if the user does not enter either a yes or a no and return to the point where it asks for another calculation. I know it's elementary and I looked for an answer the best I could but I simply don't know enough of the java terminology. If you could help me I would appreciate it so much!
P.S.It was pointed out to me that my variables should not begin with capital letters, I am aware and will not do it in the future.
System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediumd and the program will output the speed in feet per second and miles per hour\n");
//declare variables
Scanner keyboard = new Scanner(System.in);
final double Air = 1126.1;
final double Water = 4603.2;
final double Steel = 20013.3;
final double Earth = 22967.4;
double OneFootPerSecond = .68181818182;
double Distance;
double AirSpeed;
double WaterSpeed;
double SteelSpeed;
double EarthSpeed;
boolean shouldContinue = true;
while (shouldContinue == true){
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
while (!keyboard.hasNextDouble()){
System.out.println("Please enter a valid numeric value, try again: ");
keyboard.next();
}
Distance =keyboard.nextDouble();
{
System.out.print("Input the media: Air, Water, Steel, or Earth: ");
String Input = keyboard.next();
switch(Input.toLowerCase())
{
case "air":
AirSpeed = Distance/Air;
System.out.print("\n \nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through AIR" +"\n");
System.out.printf("%.6f", AirSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Air);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
String Another = keyboard.next();
Another.toLowerCase();
if (Another.equals("no")){
shouldContinue = false;
}
if (!Another.equals("no"))
if (!Another.equals("yes"))
{System.out.print("Invalid.");
}
break;
case "water":
WaterSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through WATER" +"\n");
System.out.printf("%.6f",WaterSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Water);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
Another = keyboard.next();
Another.toLowerCase();
if (Another.equals("yes")){
shouldContinue = false;
}
break;
case "steel":
SteelSpeed = Distance/Steel;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through STEEL" +"\n");
System.out.printf("%.6f",SteelSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Steel);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
Another = keyboard.next();
Another.toLowerCase();
if (Another.equals("yes")){
shouldContinue = false;
}
break;
case "earth":
EarthSpeed = Distance/Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through EARTH" +"\n");
System.out.printf("%.6f",EarthSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond*Earth);
System.out.print(" miles per hour.");
System.out.print("\n \nEnter Yes for another calculation, else No: ");
Another = keyboard.next();
Another.toLowerCase();
if (Another.equals("yes")){
shouldContinue = false;
}
break;
default :
System.out.print("Invalid. Re-run the program. ");
break;
}
}
Considering you want to ask for another calculation for every case, to prevent duplicated code move the prompt for additional processing out of the cases and put it after the switch statement. Then provide a method to continue prompting the user until they enter acceptable input.
public boolean promptForContinue(final Scanner keyboard) {
boolean isValid = false;
String userInput = "";
do {
userInput = keyboard.next();
isValid = userInput.matches("Yes|No");
if (!isValid) {
System.out.println("Invalid entry.");
}
} while (!isValid);
return userInput.equals("Yes") ? true : false;
}
EDIT: Alternative implementation removing the need for extra local variables and removing the usage of regex. Also, the addition of .toLowerCase() expands the acceptable input without the need of additional case statements. For this simple use case, we can take advantage of the fall through effect of case statements to expand acceptable values to 8.
private static boolean promptForContinue(final Scanner keyboard)
{
do
{
System.out.print("Continue (Yes/No) ?");
final String userInput = keyboard.next().toLowerCase();
switch(userInput)
{
case "y":
case "yes": return true;
case "n":
case "no": return false;
default :
System.out.println("Invalid Entry.");
}
}
while (true);
}
Then shouldContinue would be set to the return value of that method in the end of your while loop.
shouldContinue = promptForContinue(keyboard);
Incorporating what you had with my suggestion the file should look something like the following. Also, I would suggest storing both calculations in a variable so that you could move the duplicated print statements out of the cases.
public static void main(String[] args)
{
System.out.println(" The purpose of this program is to calculate the speed of sound through several mediums.\n The program user will input a distance in feet followed by a mediumd and the program will output the speed in feet per second and miles per hour\n");
//declare variables
Scanner keyboard = new Scanner(System.in);
final double Air = 1126.1;
final double Water = 4603.2;
final double Steel = 20013.3;
final double Earth = 22967.4;
double OneFootPerSecond = .68181818182;
double Distance;
double AirSpeed;
double WaterSpeed;
double SteelSpeed;
double EarthSpeed;
boolean shouldContinue = true;
while (shouldContinue == true)
{
System.out.print(" What is the distance in feet:");
//ask the user to input variables
while (!keyboard.hasNextDouble())
{
System.out.println("Please enter a valid numeric value, try again: ");
keyboard.next();
}
Distance = keyboard.nextDouble();
System.out.print("Input the media: Air, Water, Steel, or Earth: ");
String Input = keyboard.next();
switch (Input.toLowerCase())
{
case "air":
AirSpeed = Distance / Air;
System.out.print("\n \nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through AIR" + "\n");
System.out.printf("%.6f", AirSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond * Air);
System.out.println(" miles per hour.");
break;
case "water":
WaterSpeed = Distance / Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through WATER" + "\n");
System.out.printf("%.6f", WaterSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond * Water);
System.out.println(" miles per hour.");
break;
case "steel":
SteelSpeed = Distance / Steel;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through STEEL" + "\n");
System.out.printf("%.6f", SteelSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond * Steel);
System.out.println(" miles per hour.");
break;
case "earth":
EarthSpeed = Distance / Water;
System.out.print("\nThe time to for sound to travel ");
System.out.print(Distance);
System.out.print(" feet through EARTH" + "\n");
System.out.printf("%.6f", EarthSpeed);
System.out.print(" seconds or ");
System.out.printf("%.1f", OneFootPerSecond * Earth);
System.out.println(" miles per hour.");
break;
default:
System.out.println("Invalid. Re-run the program. ");
break;
}
shouldContinue = promptForContinue(keyboard);
}
}
private static boolean promptForContinue(final Scanner keyboard)
{
boolean isValid = false;
String userInput = "";
do
{
System.out.print("Continue (Yes/No) ?");
userInput = keyboard.next();
isValid = userInput.matches("Yes|No");
if (!isValid)
{
System.out.println("\nInvalid entry.");
}
}
while (!isValid);
return userInput.equals("Yes") ? true : false;
}
You have a logic problem
System.out.print("\n \nEnter Yes for another calculation, else No: ");
Another = keyboard.next();
Another.toLowerCase();
if (Another.equals("yes")){
shouldContinue = false;
}
this code is going to exit the loop if the user type yes, your if should be something like:
if (Another.equals("yes")){
shouldContinue = true;
}
else
if (Another.equals("no")){
shouldContinue = false;
}
else
{
System.out.print("Invalid input");
shouldContinue = true;
}

Categories

Resources