Allow Java to recognize input not equal to a wanted value - java

I am new to both Java and this site so please have mercy on any mistake I may make, I am at my wits end!
I am trying to make a program that calculates the speed of sound through different mediums. As of now the program will ask the user for input on the distance and allow input, same for the medium. I created several cases that will calculate the the answer of the given medium which work properly.
The issue is when I try to create a loop that recognizes if the medium input is not one of the 4 options available. I was able to successfully create a loop that recognizes if the distance input is not a numeric value and tried using similar principles for the medium input but either keep getting stuck in infinite loops or getting the message I created for a wrong entry when I entered the right option.
I have tried the basic loops that I have been taught: for, do-while, etc., but am stuck. Any and all suggestions are appreciated, thank you so much!
public static void main(String[] args) {
//prompt the user about the purpose of this program
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 mediums 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;
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();
Input.toLowerCase();
switch (Input)
{
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();
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.");
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.");
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.");
break;

First of all, as suggested in the comment, change Input.toLowerCase(); to something like:
Input = Input.toLowerCase();
or change switch(Input) to:
switch(Input.toLowerCase())
Now to the fun part...
Instead of a case of a new word, add a default: block. This will be run, if nothing else is matched.
switch (Input)
{
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();
break;
// Some more cases...
default:
// Something something that will happen as a "last resort".
break;
} // End switch

No problem.
I see the following Problem:
Input.toLowerCase();
is not working use
Input=Input.toLowerCase();
because the function just return a new String

Related

Java - Do you want to continue?(Y/N)

I want to write a simple loop for the program to go back and restart it again.
Just a simple 1 question program. Then the system ask if the user want to do it again. If the user inputs Y ... the program will loop it back to the beginning and run the entire program again. If the user inputs N, it exits.
import java.util.Scanner; // show them as code
public class HowToDoLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
while(true){
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
String c = input.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}//else continue to loop on any string ;-)
}
String c = "";
do{
System.out.println("How much money do you want to have? ");
double money = input.nextDouble();
System.out.println("Ok, here is yours $" + money);
System.out.println("Do you want to continue y or n");
c = input.nextLine();
}while(c.equalsIgnoreCase("Y"));

Do-While Qualifiers and Totalling in Java

I am trying my hand a few basic do-while codes, and am running into a couple of problems.
I want the code to ask the user to input 1 of 3 options (choosing which group they would like to add a number to, or to exit and total), give an error if they input an irrelevant option, and then total all ints at the end for each group.
public static void main(String[] args) {
String answer = "default";
int grp1 = 0;
int grp2 = 0;
int input1 = 0;
int input2 = 0;
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (answer.equals("A") || answer.equals("B"));
grp1 += input1;
grp2 += input2;
keyboard.close();
System.out.println("Group 1's total is: + grp1);
System.out.println("Group 2's total is: + grp2);
}
I need the to add a qualifier for if the user does not input a valid option, I tried using else:
else {
System.out.println("Invalid option - Try again.")
}
but this just skips to printing the totals, and does not ask the user for another input. How would I best achieve this?
Also,
grp1 += input1;
grp2 += input2;
Only counts the lasted entered int, is there a way to have it add all the entered ints?
Any help would be greatly appreciated, even outside of the questions I asked.
I think you have two confusions.
1) The "while" line in your code applies to the "do" block above it. That means that based on where the grp1 += and grp2 += lines are, they will only ever be run once. I suggest moving those calls to the end of the loop. You could move each line inside the relevant if block so that the code is run every time the user successfully enters a number after A or B.
2) The while condition is asking if the user entered "A" or "B". It's saying if they did, continue looping by going back to "do". If they entered literally anything else (any invalid answer), it will stop and run the code after the "while" line. I think what you really want is while (!answer.equals("X")), which will continue the loop until the user correctly enters an "X" character.
You'll also want to move those grp += lines up a bit.
Just change the condition inside while And also shift the totalling logic
do{
System.out.println("Make a selection:\n");
System.out.println("A: Enter a number for Group 1.");
System.out.println("B: Enter a number for Group 2.");
System.out.println("X: Exit and total the numbers for each group.\n");
System.out.println("Select your option: ");
answer = keyboard.next();
if (answer.equalsIgnoreCase("A")){
System.out.println("Enter int: ");
input1 = keyboard.nextInt(); // add an int to grp1
grp1 += input1;
}
else if (answer.equalsIgnoreCase("B")){
System.out.println("Enter int: ");
input2 = keyboard.nextInt(); // add an int to grp2
grp2 += input2;
}
else if (answer.equalsIgnoreCase("X")){
} // exit and total
else {
System.out.println("Invalid option - Try again.");
} // Invalid input - restart
}
while (!answer.equals("X"));
keyboard.close();
This will make your do while loop running i.e showing options to user until they wishes to exit. And also group total would be updated properly. I have updated answer based on answer by #Devin Howard

Java - Error message to display

I have to add validation so that once the user enters a number that's not 0-100 inclusive, it shows an error message. My question is, do I just have to enter one simple line or do I need to enter something after each prompt to validate the entry? (I might just be overthinking this, as my brain is gone with the birds today) What follows is the block that I need to adjust.
switch(choice)
{
case 1:
System.out.println("Entering Student Details");
System.out.println("------------------------");
System.out.print(" Student name: ");
name = sc.nextLine();
sc.nextLine();
System.out.print(" Student number: ");
stuNum = sc.nextLine();
System.out.print(" class 0 grade: ");
grade = sc.nextInt();
System.out.print(" class 1 grade: ");
grade2 = sc.nextInt();
System.out.print(" class 2 grade: ");
grade3 = sc.nextInt();
System.out.print(" class 3 grade: ");
grade4 = sc.nextInt();
System.out.print(" class 3 grade: ");
grade5 = sc.nextInt();
System.out.print(" class 4 grade: ");
grade6 = sc.nextInt();
}
}while(choice != 0);
System.out.println("Thank you for using the system.");
You would need to validate each input after the user inputs it. If there is an error you should send an error message to the user and ask for a different input for that grade and continue looping until a valid input is received. This may be better to put in another method in order to split up functionality. You could create a new method called getUserInput() that has a loop in it and asks user for input until a valid input is received.

Why is my Java for/if/else statement outputting duplicates

I am practicing using loops in Java and I have created this if/else loop to continually ask if there is another customer, if the user input is
"Yes" then it asks for that customers bill.
"No" then I am going to total the bill (I haven't written code for that yet so ignore that part).
The problem I am having is after I enter the initial bill amount the code asks if there is another customer like it should, but then prematurely asks for their bill amount and then asks if there is another customer a second time?
My main question is, did I structure this wrong? How am I able to get the loop to not output something twice and/or prematurely?
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
for(int c = 0; c > -1; c++) {
System.out.println("Is there another customer?");
String customer = input.nextLine();
if (customer.equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
} else {
System.out.println("Okay, let's total your bill amount.");
}
}
for(int c = 0; c > -1; c++)
This loop will (basically) run forever as c will always be greater than -1.
(Actually this loop will run until overflow occurs because the value of c will be too big to fit in the available storage space allocated for this integer. You can refer here for more information: http://en.wikipedia.org/wiki/Integer_overflow)
A cleaner way to structure this would be to do something like:
String answer = "Yes";
while (answer.equals("Yes"))
{
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
System.out.println("Is there another customer? (Yes or No)");
answer = input.nextLine();
}
Of course, you need to add error handling if the user enters inputs that you are not expecting. Also, this is more pseudocode than a true implementation.
After this while loop is when you would want to total the amount. Also, in the while loop you might want to have a variable keeping the total amount. Something like:
total += bill0;
after the line:
double bill0 = input.nextDouble();
might do the trick.
Matt Jones is correct - your loop (basically) runs forever - (overflow means it doesn't truly run forever, but it's close enough).
It seems you're trying to break the loop once the user enters "No". That means you don't know how many iterations you're going to need, so a while loop is more suited to this task than a for loop. So let's use a while loop to do that.
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
//loop until the user enters the phrase "No".
while(true) {
System.out.println("Is there another customer?");
String customer = input.nextLine();
if (customer.equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
} else if(customer.equalsIgnoreCase("No") {
System.out.println("Okay, let's total your bill amount.");
break; //End the loop
} else{
System.out.println("Sorry, unrecognized input. Please enter yes or no.");
}
}
//Do post-loop totaling and stuff.
I would use a while loop
while (scannerInput.equals("yes"))
//do your thing
}
Once the scanner input doesn't equal "yes" anymore, it will exit the while and do something else
for loops are more to iterate through a set of data, rather than a while, which is waiting for state change.
Scanner input = new Scanner(System.in);
double total;
System.out.println("Please enter your bill amount.");
double bill0 = input.nextDouble();
System.out.println("Is there another customer?");
while((String customer = input.nextLine()).equalsIgnoreCase("Yes")) {
System.out.println("Please enter their bill.");
double bill = input.nextDouble();
}
System.out.println("Okay, let's total your bill amount.");

Having Problems With do...while Loop

I have a little problem with this do while loop; when I run the program it is working, at least partially, what I mean is first you need to make a choice for convertion from C to F or from F to C and after you enter the values the program stops what I want to do is to keep asking for values until you enter 3. I tried to do it with a do while loop but it is not working so if someone has any ideas I would be grateful. Here is the code:
import java.util.Scanner;
public class DegreesInConversion2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Conversion table: ");
int choice = input.nextInt();
do {
System.out.println();
System.out.println("1 for convertion from Celsious to Fahrenhait: ");
System.out.println("2 for convertion froom Fahrenheit to Celsious: ");
System.out.println("3 for Exit: ");
System.out.println();
System.out.println("Make a choice between 1 - 3 ");
choice = input.nextInt();
System.out.println();
switch (choice) {
case 1:
System.out.println("Enter temperature in Celsious: ");
double cel = input.nextDouble();
if (cel < -273.15) {
System.out.println("Invalid values, please enter temperature greater than -273.15 in C:");
} else {
System.out.println("You enetered " + cel + "C " + "which is " + (((cel * 9) / 5) + 32) + "F");
}
break;
case 2:
System.out.println("Enter temperature in Farhneit: ");
double far = input.nextDouble();
if (far < -459.67) {
System.out.println("Invalid values, please enter temperature greater than -459.67 in F:");
} else {
System.out.println("You enetered " + far + "F " + "which is " + (((far - 32) * 5) / 9) + "C");
}
break;
case 3:
System.out.println("Goodbyu have a nice day: ");
break;
default:
System.out.println("Invalid entry: Please enter a number between 1-3:");
}
} while (choice != 3);
}
}
Like in your other question, here you're scanning for input before prompting the user for input.
You need to remove the second line below:
System.out.println("Conversion table: ");
int choice = input.nextInt();
do
With your code as is, it outputs
Conversion table:
and then blocks waiting for input. Whereas you want it instead to continue into the while loop and output
1 for convertion from Celsious to Fahrenhait:
2 for convertion froom Fahrenheit to Celsious:
3 for Exit:
Make a choice between 1 - 3
before blocking to scan for input.
As is, if you enter any number at the first block, your program enters the loop and behaves as you wanted. So you're nearly there!
The code does work. the problem is most likely the
int choice = input.nextInt();
before the do
Remove this, and change
choice = input.nextInt();
to
int choice = input.nextInt();
Besides the fact that you have: int choice = input.nextInt(); outside of the loop which is unnecessarily getting input before showing the menu, it seems to all work relatively fine. You can just declare int choice inside the loop where you have choice = input.nextInt(); (ie. just change that to intchoice = input.nextInt();).
I tested your code, and it works fine if you change the line int choice = input.nextInt(); (just before your do{} while() block) into int choice;.
As others have already mentioned, you should not read input before your do{} while() block, since the question has not been asked yet.
you forgot the break; after your default case

Categories

Resources