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.
Related
Hello guys I need help with my code. I am trying to understand how to use the method, loop,if-else statement, and exit code. So I'm writing a simple calculation base on the user choice but right now I can't figure out how to make the input read to loop back when user input else than the number (mean no alphabet are allowed) and it will continue back to the option till the user enter the right option that is either 1 or 2.
Do let me know if I make any mistake or is there a way to simplify this code more.
WANT OUTPUT TO BE LIKE THIS:-
[1] Calculation
[2] Exit
Your choice: a
Please choose only 1 or 2
[1] Calculation
[2] Exit
Your choice: 1
Enter 1st number: 1
Enter 2nd number: 1
Total: 2
CODE:-
import java.util.Scanner;
public class Testing {
int ans;
boolean Loop = true;
public void SimpleCalculation() {
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
System.exit (0);
}
public static void main(String[] args) {
Testing t = new Testing();
t.SimpleCalculation();
}
}
I have updated your code :
public class Testing {
public static void SimpleCalculation() {
boolean Loop = true;
Scanner input = new Scanner(System.in);
while (Loop) {
System.out.println("[1] Calculation ");
System.out.println("[2] Exit");
System.out.print("Your choice: ");
while(!input.hasNextInt()) {
System.out.println("Please choose only 1 or 2");
input.nextLine();
continue;
}
int ans = input.nextInt();
if (ans == 1) {
System.out.print("Enter 1st number: ");
int number1 = input.nextInt();
System.out.print("Enter 2nd number: ");
int number2 = input.nextInt();
int result = number1 + number2;
System.out.println("Total: " + result);
} else if (ans == 2) {
System.out.println("Thank you");
input.close();
break;
} else {
System.out.println("Please choose only 1 or 2");
}
}
}
public static void main(String[] args) {
SimpleCalculation();
}
}
Output :
[1] Calculation
[2] Exit
Your choice: a
Please choose only 1 or 2
[1] Calculation
[2] Exit
Your choice: 1
Enter 1st number: 1
Enter 2nd number: 2
Total: 3
My program is stuck in an infinite loop after a selection is made and completed. It needs to restart and go through the menu options again. Any help would be greatly appreciated.
public static void main(String[] args) {
// TODO Auto-generated method stub
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int choice = input.nextInt();
int count = 0;
while (choice < 1 || choice > 6){
count ++;
System.out.println("I'm sorry, " +choice+ " is not a valid option.\n");
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
choice = input.nextInt();
if (choice >= 1 && choice <= 6){
continue;
}
else if (count == 2){
System.out.println("Please try again later.");
System.exit(0);
return;
}
}
do
{
switch (choice)
{
case 1: choice = 1;
System.out.print("What is the first number? ");
int firstAdd = input.nextInt();
System.out.print("What is the second number? ");
int secondAdd = input.nextInt();
System.out.println("Answer: " +(firstAdd + secondAdd));
break;
case 2: choice = 2;
System.out.print("What is the first number? ");
int firstSub = input.nextInt();
System.out.print("What is the second nubmer? ");
int secondSub = input.nextInt();
System.out.println("Answer: " +(firstSub - secondSub));
break;
case 3: choice = 3;
System.out.print("What is the first number?" );
int firstMult = input.nextInt();
System.out.print("What is the second number? ");
int secondMult = input.nextInt();
System.out.println("Answer: " +(firstMult * secondMult));
break;
case 4: choice = 4;
System.out.print("What is the first number? ");
double firstDiv = input.nextInt();
System.out.print("What is the second number? ");
double secondDiv = input.nextInt();
while (secondDiv == 0){
System.out.println("I'm sorry, you can't divide by zero.");
break;}
{
System.out.println("Answer: " +(firstDiv / secondDiv));
break;
}
case 5: choice = 5;
System.out.println(Math.random() * 10 + 1);
break;
case 6: choice = 6;
System.out.println("Goodbye!");
System.exit(0);
return;
}
}while (choice >=1 && choice <= 6);
}
I've tried a few different options that I found in my book, but they seem to cause more errors in other areas. I don't know if there is a different statement than "break;" to use to restart the menu because this is my first time using cases.
Enclose everything after the scanner instantiation in a while loop.
Specifically,
while (true) {
// your code
if (choice == 6)
break;
}
FIXED: Also remove the do {} while() loop. Your loop is infinite because "choice" does not change in the loop.
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);
}
}
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.
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;
}