Validate the switch statement with an if statement - java

Use a switch statement to implement a menu. Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc ). If the user enters an invalid selection your program should tell them and then exit.
The answers for air, water and steel must use printf. Display air to 3 decimal places, water to 4 decimal places and steel to 5 decimal places.
After the user enters the distance the sound wave must travel but before using the number in a calculation, validate it. If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit. Nest the switch statement (menu – see above) within this if statement.
import java.util.Scanner;
public class SpeedSound
{
public static void main(String[] args)
{
String input;
double distance;
double time;
final double AIR = 1/1100;
final double WATER = 1/4900;
final double STEEL = 1/16400;
Scanner kyb = new Scanner(System.in);
System.out.print("Enter the corresponding medium:\n ");
System.out.println("Air\n ");
System.out.println("Water\n ");
System.out.println("Steel\n ");
input = kyb.nextLine();
System.out.print("Enter the distance: ");
distance = kyb.nextDouble();
if (distance < 0 || distance > 10000)
System.out.print("Error: ");
switch (input)
{
case "Air":
case "AIR":
time = (distance / 1100);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Water":
case "WATER":
time = (distance / 4900);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Steel":
case "STEEL":
time = (distance / 16400);
System.out.println("The total time traveled is " + time + "seconds.");
break;
}
}
}

Indentation doesn't matter for java, use a block by using {} braces, otherwise it will only execute the next statement.
if (condition) {
// .. lots of
// .. lines of
// .. code
}

Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc )
As you need to handle all the lower/upper case version of the input. Just convert the string into lower casebefore passing to switch case, then define there only lowercase case statements instead of multiple statements.
intput = input.toLowerCase(); // this is not require if you have converted it earlier
switch (input) {
case "air":
If the user enters an invalid selection your program should tell them and then exit.
You can use the if condition and exit the user:
input = kyb.nextLine().toLowerCase();
if (! (input.equals("air") || input.equals("water") || input.equals("steel")) ) {
System.out.println("Invalid input. Exit");
return;
}
If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit.
if (distance < 0 || distance > 10000) {
System.out.print("Error: ");
return;
}

Related

Calculator int choice = Integer.parseInt(char_a); java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}
I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);
There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

How to create Menu to Select using Characters A B C or a b c in Java

We need to create a menu that can be selected using Characters
such as A. B. C. also a. b. c. and use Q. to quit.
package mainmenu;
import java.util.Scanner;
public class MainMenu{
public static void main(String[] args){
System.out.println(" Welcome to our project");
System.out.println("Please Choose an option from the menu");
System.out.println("Type the letter to select the option");
System.out.println();
// We need to create a menu that can be selected using Characters
//such as A. B. C. also a. b. c. and use Q. to quit.
Here we will set a menu with 7 options:
Was looking for a way to create a menu using letters and a way to convert them to a upper case.
/* A. The Radius of a circle.
B. The Cost of gym membership over a year.
C. Compound Interest of CD over 6 years.
D. The Square Root of a 5 digit number.
E. Guess the number Game.
F. Day of your birth day.
G. Little Shop of Horrors.
Q. Quit / Exit.
*/
// A. Radius of a Circle
// Scan for the Diameter then display the Results
// B. Cost of a Gym Membership
// Scan for the Gym info, Name, joining fee, monthly cost, yearly dues, cancellation fee.
// double joinFee, monthCost, yearDues, cancelFee.
// double initialCost = joinFee + monthCost;
// double yearlyCost = initialCost + (monthCost * 11) + yearDues;
// double earlycancel = (monthCost * 2 ) + cancelFee;
// Display the options
// C. Compound Interest of CD over 6 year period
/*
A=P(1+R)^N
double amount;
double principal = 10000 ;
double rate = .01;
for(double months=1; months<=60; months++){
amount=principal * Math.pow(1 + rate, months);
System.out.println (months + " " + amount); }
*/
// D. Calculate the Square Root of a 5 digit number
// E. Guess the Number Game
// Too low
// Too high
// F. Day of the week of your Birthday.
// Calculate the Day and display
// G. When should Seymour feed the plant
// Feed me Seymour!!
// Feed him in the morning, in the afternoon, in the evening and at midnight.
// Q. Quit / Exit
This code should help:
Scanner sc = new Scanner(System.in);
String options = "A. The Radius of a circle.\n" +
"B. The Cost of gym membership over a year.\n"
+"C. Compound Interest of CD over 6 years.\n"
+"D. The Square Root of a 5 digit number.\n"
+"E. Guess the number Game.\n"
+"F. Day of your birth day.\n"
+"G. Little Shop of Horrors.\n"
+"Q. Quit / Exit.\n";
String input = null;
System.out.println("Enter the option you would like to select. Your choices are: ");
System.out.println(options);
boolean validInput = false;
while (!validInput) {
input = sc.next(); //asks for the user input
input = input.toUpperCase(); // makes the entire String uppercase
if (!input.equals("A") || !input.equals("B") || !input.equals("C") || !input.equals("D") || !input.equals("E") || !input.equals("F") || !input.equals("G") || !input.equals("Q")) {
System.out.println(input+" is not an option");
System.out.println("Your choices are: ");
System.out.println(options);
} else
validInput = true; //exits the loop when they give something useful.
}
if (input.equals("A")) {
//do A stuff
} else if (input.equals("B")) {
//do B stuff
} else if (input.equals("C")) {
//do C stuff
} else if (input.equals("D")) {
//do D stuff
} else if (input.equals("E")) {
//do E stuff
} else if (input.equals("F")) {
//do F stuff
} else if (input.equals("G")) {
//do G stuff
} else if (input.equals("Q")) {
//do Q stuff
}
sc.close(); //do this when you are done with the scanner
What it does is it asks for the user's input, then it checks to see if it equals one of the choices. I use
input = input.toUpperCase();
to make the input upper case so that "a" and "A" are recognized as the same thing. Make sure you don't try just
input.toUpperCase();
because that won't do anything. Strings are immutable. Here is more information about that: String is immutable. What exactly is the meaning?
Also, make sure that you use
input.equals("whatever")
Instead of
input == "whatever"
Because the second example is unreliable. More info on this here:How do I compare strings in Java?

java Scanner.hasNext() usage

public static void main(String args[]){
Scanner in = new Scanner(System.in);
String a = in.next();
if (in.hasNext()) {
System.out.println("OK")
} else {
System.out.println("error");
}
}
What I want is:
if the user type in a String with more than one word, print "OK".
if the user type in a String with only one word, print "error".
However, it doesn't work well. When I type a single word as an input, it doesn't print "error" and I don't know why.
Read a line and then check whether there are more than one word.
String a = in.nextLine();
if( a.trim().split("\\s").length> 1 ){
System.out.println("OK");
} else {
System.out.println("error");
}
Your condition resolves true, if you have any kind of new input. Try something like contains(" ") for testing your input to contain spaces. If you want to make sure the input doesn't just contain spaces but also some other characters, use trim() before.
hasNext() is a blocking call. Your program is going to sit around until someone types a letter, and then go to the System.out.println("OK"); line. I would recommend using an InputStreamReader passing in System.in to the constructor, and then reading the input and determining its length from there. Hope it helps.
From Scanner#hasNext() documentation
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
So in case of only one word scanner will wait for next input blocking your program.
Consider reading entire line with nextLine() and checking if it contains few words.
You can do it same way you are doing now, but this time create Scanner based on data from line you got from user.
You can also use line.trim().indexOf(" ") == -1 condition to determine if String doesn't contain whitespace in the middle of words.
Scanner#hasNext() is going to return a boolean value indicating whether or not there is more input
and as long as the user has not entered end-of-file indicator, hasNext() is going to return true
The end-of-file indicator is a system-dependent keystroke combination
which the user enters to indicate that there’s no more data to input.
on UNIX/Linux/Mac OS X it's ctrl + d,,, On Windows it's ctrl + z
look at this simple example to see how to use it
// Fig. 5.9: LetterGrades.java
// LetterGrades class uses the switch statement to count letter grades.
import java.util.Scanner;
public class LetterGrades
{
public static void main(String[] args)
{
int total = 0; // sum of grades
int gradeCounter = 0; // number of grades entered
int aCount = 0; // count of A grades
int bCount = 0; // count of B grades
int cCount = 0; // count of C grades
int dCount = 0; // count of D grades
int fCount = 0; // count of F grades
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n",
"Enter the integer grades in the range 0–100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
// loop until user enters the end-of-file indicator
while (input.hasNext())
{
int grade = input.nextInt(); // read grade
total += grade; // add grade to total
++gradeCounter; // increment number of grades
// increment appropriate letter-grade counter
switch (grade / 10)
{
case 9: // grade was between 90
case 10: // and 100, inclusive
++aCount;
break; // exits switch
case 8: // grade was between 80 and 89
++bCount;
break; // exits switch
case 7: // grade was between 70 and 79
++cCount;
break; // exits switch
case 6: // grade was between 60 and 69
++dCount;
break; // exits switch
default: // grade was less than 60
++fCount;
break; // optional; exits switch anyway
} // end switch
} // end while
// display grade report
System.out.printf("%nGrade Report:%n");
// if user entered at least one grade...
if (gradeCounter != 0)
{
// calculate average of all grades entered
double average = (double) total / gradeCounter;
// output summary of results
System.out.printf("Total of the %d grades entered is %d%n",
gradeCounter, total);
System.out.printf("Class average is %.2f%n", average);
System.out.printf("%n%s%n%s%d%n%s%d%n%s%d%n%s%d%n%s%d%n",
"Number of students who received each grade:",
"A: ", aCount, // display number of A grades
"B: ", bCount, // display number of B grades
"C: ", cCount, // display number of C grades
"D: ", dCount, // display number of D grades
"F: ", fCount); // display number of F grades
} // end if
else // no grades were entered, so output appropriate message
System.out.println("No grades were entered");
} // end main
} // end class LetterGrades
and the output will be something like this
Enter the integer grades in the range 0–100.
Type the end-of-file indicator to terminate input:
On UNIX/Linux/Mac OS X type <Ctrl> d then press Enter
On Windows type <Ctrl> z then press Enter
99
92
45
57
63
71
76
85
90
100
^Z
Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2
Resources Learning Path: Professional Java Developer
and Java™ How To Program (Early Objects), Tenth Edition

Do / While Loop Verification

I'm using javax.swing.JOptionPane.
I need the user to enter in the product number, revenue, and expenses.
I need to validate the information to make sure that the revenue is between 0 and 20000 and verify that the expenses are between 1500 and 10000. I need to make sure that if they enter in an invalid revenue or expense it prompts them, and not allow the program to continue.
The program needs to be able to determine if there was a net profit, loss, or break even.
The user has to have the option of entering multiple records. Also, I need to count how many times the user entered in the information.
I feel like I was able to knock out a big chunk of the code.
When the user inputs an invalid revenue or expense, it keeps looping the messages and doesn't return to the ability to enter in the values again.
I also am not sure how I am going to get the user to input "Y" to loop the entire program again.
Can anyone lend me some assistance please?
/**
* The program will output the Product Number, Revenue, Expenses, as well as the Net Income
*/
import javax.swing.JOptionPane;
import java.io.*; // Access System.out
import java.util.Scanner;
public class RevenueJopt
{
public static void main(String[] args)
{
// Declarations
double finalValue;
char repeat;
int counter = 1;
String input;
Scanner keyboard = new Scanner(System.in);
// Do Loop to run
do{
// Advise the user the conditions that have to be met for inputs
JOptionPane.showMessageDialog(null,"Please ensure that your revenue is between 0 to 20,000.00 dollars." +
"\nPlease ensure that your expenses are between 1,500.000 to 10,000.00 dollars.");
// Ask user the values of the variables
String response = JOptionPane.showInputDialog(null, "Enter in a Product Number(or -1 to END)");
String response1 = JOptionPane.showInputDialog(null, "Enter the Revenue?");
String response2 = JOptionPane.showInputDialog(null, "Enter the Expenses?");
// Read in values
int productNumber = Integer.parseInt(response);
float revenue = Float.parseFloat(response1);
float expenses = Float.parseFloat(response2);
//While loop to Validate Information
while(revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000) {
JOptionPane.showMessageDialog(null,"You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
JOptionPane.showMessageDialog(null,"Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
JOptionPane.showMessageDialog(null,"Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
//When this part runs, it goes into an infinite cycle. I am not sure how to break free of this.
counter++;
//calculates final value
}
}
finalValue = revenue - expenses;
// Calculates final value and displays as net profit, loss or break even.
if (finalValue > 0) {
JOptionPane.showMessageDialog(null, "You made a profit. Your net income is: "+finalValue);
} else if (finalValue == 0) {
JOptionPane.showMessageDialog(null, "You broke even. Your revenue was "+ revenue +" your expenses were " +expenses);
} else if (finalValue < 0) {
JOptionPane.showMessageDialog(null,"You have not made any profit. Your net loss is: "+finalValue);
}
JOptionPane.showMessageDialog(null,"Number of records: " +counter);
//validate user input
JOptionPane.showMessageDialog(null,"Would you like to input more records?");
String response3 = JOptionPane.showInputDialog(null, "Enter 'Y' for yes or 'N' for no.");
// I am not sure how to hold the value "Y" to make the loop keep repeating
input = keyboard.nextLine();
repeat = input.charAt(0);
counter++;
}
while(repeat == 'Y' || repeat == 'y');
}
}
Replace
input = keyboard.nextLine();
repeat = input.charAt(0);
with
repeat = response3.charAt(0);
to get the first character of the String entered into the input dialog box.
However, this will throw an StringIndexOutOfBoundsException if the user enters nothing into the dialog box, so you have to decide on a default value for that case:
repeat = response3.isEmpty() ? 'n' : response3.charAt(0);
Reading from System.in is basically for CLI applications.
Also check the "validate information" while loop. If the user enters invalid values, he will be informed about this indefinitely, with no chance of entering correct values.

In Java, is it possible to use some sort of while loop (or anything) to determine the amount of prompts for input?

public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
First off, I'm a beginner programmer. My terminology and jargon are quite lacking, so bear with me.
I'm writing a program to capture 3 test scores then validate them using a while loop (must be within the 1-100 range). The test scores are then averaged and the output displays the average. Pretty simple stuff.
I'm wanting to find a way, if possible, to capture the number of test scores, then from there, capture each actual score. For example, the program asks "How many tests are being computed for average?", then take that number and have it be the same amount of times the program prompts, "Please enter test score (1):" or something along those lines. So for further clarity, if the user typed 4 for number of tests, then the prompt for inputting the score would show up 4 times.
I feel the above code is redundant by using a while loop for each score and at that, limited because the program is only meant for 3 scores. Any help is much appreciated and feel free to critique anything else in the code.
Yes you can.
What you need is a nested loop. In pseudo code:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
Short answer:Yes, it is possible.
Option 1: Initially ask the user how many scores they are planning on entering, and store that in an int variable.
For example:
Ask user how many scores to enter.
Check the response, and store it in an int variable.
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable
Once loop is exhausted, just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Option 2: Use a sentinel-loop (the user has to enter a letter -usually 'Q' or 'N'- or something to exit the loop)
Create an int variable to store total loops (initialize to 0).
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Check if the value is the quit character
If it is not
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable and increment
the total loops variable by 1.
If it is
just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Hope it helps.
In http://korada-sanath.blogspot.in/p/discussion-on-tech-topics.html, there is a pseudo code which illustrates similar problem with basic Java programming skills. In that in looping section you can simply add a check whether user entered score is in range 1-100 or not. If not, you can decrease loop variable by '1' so that user can enter his score one more time...
For further illustration please add below code in looping section of code present in above mentioned link.
instead of directly assigning user entered value to your testScores array, you can use one temp var and then can assign if user entered score in range.
Double temp = Double.parseDouble(br.readLine());
if(temp > 1 && temp < 100) {
testScores[loopVar] = temp;
} else {
loopVar--;
}

Categories