How to exit the program with a letter - java

I am attempting to create a program thtat does some processing and exits when a given letter is typed.
//1.00usd = .727751euro
int reset = 0;
while(reset == 0)
{
double euro;
double ems;
String input = JOptionPane.showInputDialog(null,"Enter Amount of US Dollar: ");
ems = Double.parseDouble(input);
if (ems < 0)
{
JOptionPane.showMessageDialog(null, "Please enter a real amount of money");
reset = 0;
}
if (ems >= 0)
{
euro = .727751;
ems = ems*euro;
ems = ems*100;
ems = Math.round(ems);
ems = ems/100;
JOptionPane.showMessageDialog(null,"Amount in euros: € " + ems);
}
}
This program is to convert usd to euro and I wanted to know how I can make the program exit when entering the letter "Q".
This is for a an object class so I'm still learning.

Something like
String input = JOptionPane.showInputDialog(null,"Enter Amount of US Dollar: ");
if( input.equals("Q") ) // but the case is important here
{
System.out.println("Bye bye");
System.exit(0);
}
ems = Double.parseDouble(input);

If your question is "how to exit the program", you can call
System.exit(0);
when the user presses a key.
If you just want to "quit" the loop you're in, manage to get the condition true, or use "break" (but you should not need it in your case).

Add this if statement in the while loop.
if(inputString.equalsIgnoreCase("q")) {
System.exit(0);
}

Related

How to return to the previous statement after catching an error instead of restarting the whole program in Java?

I recently started learning Java as I have a keen interest in programming. I am currently creating an application that calculates a person's BMI.
Question: Is there a way to return to the previous statement when the user has made a mistake on instead of restarting the whole program (EG: when the line Please enter your weight in pounds executed, the user input a non-integer value and an error prompts out saying Invalid Input, it will then return to the previous line that the user made an error -> Please enter your weight in pounds executed).
If yes, how so?
import java.util.Scanner;
import java.text.DecimalFormat;
public class Body_Mass_Calculation {
private static int gender, inputAnswer;
private static boolean wenttocatch;
private static double myBMI, heightInch, weightPound, weightKilo, heightMeter;
private static Scanner input_1 = new Scanner(System.in);
private static DecimalFormat df2 = new DecimalFormat("#.##");
//Questions + Calculation
static void myMethod() {
try {
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
while (gender > 2 || gender < 1) {
System.out.println("Invalid input!");
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
}
if (gender == 1 || gender == 2) {
System.out.println("Please enter your height in inches. ");
heightInch = input_1.nextInt();
System.out.println("Please enter your weight in pounds. ");
weightPound = input_1.nextInt();
heightMeter = heightInch * 0.0254;
weightKilo = weightPound * 0.45359237;
myBMI = weightKilo / (heightMeter * heightMeter);
}
if (gender == 1) {
if (myBMI >= 27.8)
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
else
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high ! \n \n");
}
if (gender == 2) {
if (myBMI >= 27.3)
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
else
System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high! \n \n");
}
System.out.println("Do you wish to continue? Enter: 1 -> Yes, 2 -> No.");
inputAnswer = input_1.nextInt();
System.out.println("Invalid Input !");
if (inputAnswer == 2) { //If input = 2, Program executes line below
System.out.println("Thank You for using this shitty app !");
System.exit(2);
} else if (inputAnswer == 1) {
myMethod();
}
} catch
(Exception e) {
input_1.next();
wenttocatch = true;
System.out.println("Invalid input !");
input_1.nextLine();
myMethod();
}
}
public static void main(String[] args) {
//Executes Function/Method
System.out.println("Welcome ! \n ");
myMethod();
}
}
No, you can't. The solution is to write a method that takes care of it. Instead of writing a ton of code and repeating yourself, you use a method to encapsulate some functionality, so that you can invoke it a lot without copying code. For example, instead of:
System.out.println("Please enter gender. 1-- Male 2--Female");
gender = input_1.nextInt();
while (gender > 2 || gender < 1) {
System.out.println("Invalid input!");
gender = input_1.nextInt();
}
you really just want to write something like:
gender = askInt("Please enter gender. 1-- Male 2-- Female", 1, 2);
where the askInt is a method you write which takes the text you want to show as prompt, along with the smallest and largest valid value.
Now that you have this function, you can expand its functionalities and all the code that uses this function gets the functionality automatically. So, if you add 'catch invalid input exceptions and re-ask' functionality to this one method, ALL the questions get it.
int askInt(String prompt, int min, int max) {
int result;
while (true) {
System.out.println(prompt);
result = input.nextInt();
if (result >= min && result <= max) return result;
System.out.println("Invalid input!");
}
}
This basic loop will keep looping until the if clause is triggered, causing the method to return, which is the only way out. You can now add handling for NumberFormatException within this one method, within the while loop. You can't go back to the line that caused the problem, but you can go forward, and in a while loop, going forward automatically jumps back to the start (i.e., that's how to go 'backwards'). So, we mix a while loop (which can go backwards) and a catch block, and that's how to solve the problem. And then we put all this in a method, so that we can write this code only once, instead of having to repeat it every time.
You can do it by using a do { _code1 } while (_condition) which execute the _code until _condition is false.
And _code1 is a try {}catch which will catch any exception (error) thrown from inside the try {} block.Here the exception (error) is thrown if the user enters a character instead of a digit.
System.out.println("Please enter gender. 1-- Male 2--Female");
int gender = 0 ;
do {
try {
if (gender == -1) {
System.out.println("Invalid input!");
System.out.println("Please enter gender. 1-- Male 2--Female");
}
gender = input_1.nextInt () ;
}catch (Exception e){
gender = -1 ;
}
}while (gender > 2 || gender < 1);

Correct user input not matching array values

I've written a portion of code to take a user input, match it to a string value and then use a related double value to make calculations:
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < currencytext.length; i++) {
boolean valid = false;
while(!valid){
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
String payment = keyboard.next();
if(payment.equals(currencytext[i])){
sum = sum - currency[i];
if(sum == 0) {
System.out.print("You gave " + payment);
System.out.print("Perfect! No change given.");
System.out.print("");
System.out.print("Thank you" + name + ".");
System.out.print("See you next time.");
}
}
if(!(payment.equals(currencytext[i]))) {
System.out.print("Invalid coin or note. Try again. \n");
}
if(payment.equals(currencytext[i]) && currency[i] > sum){
System.out.print("You gave " + payment);
System.out.print("Your change:");
}
}
}
The problem is that when it gets to user input, it doesn't match any string values except for $0.05. It seems to me like its not iterating through the array properly but I can't figure out why. Is anyone able to see a problem here?
This is a possible solution for your problem
Scanner keyboard = new Scanner(System.in);
double [] currency = new double[] {0.05,0.10,0.20,0.50,1.00,2.00,5.00,10.00,20.00,50.00,100.00};
String [] currencytext = {"$0.05","$0.10","$0.20","$0.50","$1.00","$2.00","$5.00","$10.00","$20.00","$50.00","$100.00"};
String payment = keyboard.next();
double sum = 100; // <- Working example - Read sum from keyboard entry
while (sum > 0) {
boolean paymentFound = false;
for (int i = 0; i < currencytext.length; i++) {
if (payment.equals(currencytext[i])) {
sum = sum - currency[i];
paymentFound = true;
if (sum == 0) {
System.out.println("You gave " + payment);
System.out.println("Perfect! No change given.");
// System.out.print("Thank you" + name + ".");
System.out.println("See you next time.");
break;
} else if (sum < 0) {
System.out.println("You gave " + payment);
System.out.println("Your change:" + (-1 * sum));
break;
}
}
}
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
}
while-loop will continue until the payment is fullfilled.
for-loop traverse the arrays until a suitable payment is found
If suitable payment is found we substract it from sum. We use break to exit the for-loop in both cases. There is no need to keep searching.
If no suitable payment is found [!paymentFound], we keep on asking.
if (!paymentFound) {
System.out.println("Invalid coin or note. Try again. \n");
}
if (sum > 0) {
System.out.format("$%.2f remains to be paid. Enter coin or note: ", sum);
payment = keyboard.next();
}
The program will end when (sum < 0), in which case the while-loop exits.
I have use println instead of print to improve message legibility.
Too many flaws to point out.
However,
When the currencytext[i] does not match payment, it executes this code:
System.out.print("Invalid coin or note. Try again. \n");
System.out.format("$%.2f remains to be paid. Enter coin or note: ",sum);
payment = keyboard.next();
So, it executes this for all the times that your input does not match currencytext[i].
And, in this block, you have
payment = keyboard.next();
So, it asks for new input, in this block itself. Hence, you get the said output for all inputs except $0.05.
As far as $0.05 is concerned, your first if block executes successfully, and prints no output. So, it moves to the next iteration of the while loop, where again, payment remains the same ($0.05), but currencytext[i] becomes $0.10. SO they do not match, and you get the said output.
How to correct this:
With this code, you need to do a lot of corrections.
I suggest you again start from scratch.
If it doesn't fit, it sets valid to true, so the code just has the chance to check against the first item at currencytext[0], which is $0.05. Then !payment.equals(currencytext[i]) is also true, and your code prints the lines there. Your else ifs are also not properly nested.
I don't know how you are reading input. One improvement you can do is write reading input code in for loop.
Scanner scanner = new Scanner(System.in);
for (... ) {
....
String payment = scanner.nextLine();
....
}

I have something not working with my looping. it can run but its not looping

while (input != '1'){
String customer;
customer = JOptionPane.showInputDialog("Enter customer's name: ");
String type;
type = JOptionPane.showInputDialog("Choose type of photocopy: G/C");
if (type.equals("G")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.10;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.05;
}
} else if (type.equals("C")) {
noOfPhotocopy = Integer.parseInt(JOptionPane
.showInputDialog("Enter no of photocopy: "));
if (noOfPhotocopy < 10) {
totalprice = noOfPhotocopy * 0.20;
} else if (noOfPhotocopy >= 10) {
totalprice = noOfPhotocopy * 0.10;
}
}
JOptionPane.showMessageDialog(null, "Customer name : "+customer+"\nType of Photocopy : "+type+"\nNumber of Photocopy : "+noOfPhotocopy+"\nTotal Price : RM"+ (float)totalprice);
String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");
Please help me with this code. I cannot determine what is wrong with this code. When I run this program, it seems that the looping is not working. This is my assignment project and need to be submit earlier.
Why is my loop not looping?
You break unconditionally. break will always exit the enclosing loop.
Also you have a type confusion in your loop condition between char and int. It is legal due to type coercion (int will be converted to char for comparison or vice versa), but it won't do what you intend.
'1'
is a char. It's a UTF-16 character whose int value is 49.
1
is an int
You really want this:
while (input != 1) {
Here's another way to approach this that you can apply generally when programs go pear-shaped (don't work as expected).
Make a backup of this code and start a new Java class. In that class create a smaller example. Maybe something like this:
while (input != '1') {
String input1;
input1 = JOptionPane.showInputDialog( "Press 1 to stop or press anything to continue ");
input = Integer.parseInt(input1);
break;
}
JOptionPane.showMessageDialog(null, "Program finished ^^");
This program has the same bugs, but is much smaller. Can you see the problem in that smaller program?
This approach done either by removing code or commenting it out allows you to isolate a bug by trial and error. Over time you'll develop an intuition for the bugs and see them immediately, but this approach goves you an avenue for getting to that point.
while (input !='1'){
is wrong. Because input is int. Inside your code you write:
input = Integer.parseInt(input1); // so input is int type
Rewrite it as:
while (input != 1){
int input=1;
Scanner scn=new Scanner(System.in);
System.out.println("Start!!!");
while (input!=0) {
System.out.println("Enter 0 to exit!!");
input=scn.nextInt();
}
System.out.println("Finish!!!");
Refer this code for your code.
No need to use break inside loop. You can use it with conditional break.

Why isn't this do while loop working properly? [duplicate]

This question already has answers here:
Java do-while loop isn't working
(3 answers)
Closed 7 years ago.
I working on a project for my course. The program runs fine until it hits my end program I've been messing with it for about 2 hours when I thought I was already finished.
This is the code it's messing up on.
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
I tried messing with the else if then switched to if. Full code is
public static String endProgram = null;
public static void main(String[] args) {
String MUR = "--------------Monthly Use Report--------------";
int minutesAllowed;
int minutesUsed = 0;
int minutesOver;
double totalOwed;
double monthlyRate = 74.99;
double minOver = 0.20;
double realOwed;
boolean valid = false;
boolean over = false;
boolean aui = false;
Scanner Input = new Scanner(System.in);
System.out.println("Welcome to the Cell Phone Minutes Calculator.");
do {
do {
System.out.println("Please input the amount of minutes you were allowed to use per month.");
System.out.println("Please Enter a value between (200 - 800)");
minutesAllowed = Input.nextInt();
} while (minutesAllowed <= 199 || minutesAllowed >= 801);{
}
do{
try{
System.out.println("How many minutes were used during the previous month?");
minutesUsed = Input.nextInt();
if(minutesUsed <= 1){
System.out.println("--Invalid Input! Please use a positive number.--");
} else {
valid = true;
}
} catch(Exception e){
System.out.println("Invalid Input! Please try again.");
Input.next();
}
}while(!valid);
minutesOver = minutesAllowed - minutesUsed;
if(minutesAllowed >= minutesUsed){
System.out.println("You were not over your minutes for the month!");
} else {
System.out.println("You were over your minutes by "+ Math.abs(minutesOver));
over = true;
}
totalOwed = (Math.abs(minutesOver))*(minOver);
realOwed = totalOwed+monthlyRate;
System.out.println(MUR);
System.out.println("Minutes allowed were "+ minutesAllowed);
System.out.println("Minutes used were "+ minutesUsed);
if(over){
System.out.println("Minutes over were "+ Math.abs(minutesOver));
System.out.println("Total due is $"+ realOwed);
} else {
System.out.println("Total due is $"+ monthlyRate);
}
do {
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
}
if (endProgram.equalsIgnoreCase("n")){
endProgram = "n";
aui = true;
}
if (endProgram.equalsIgnoreCase("y")){
endProgram = "y";
aui = true;
}
} while(aui = false);
}while((endProgram.equalsIgnoreCase("n")) && (aui = false));
}
}
Sorry if the code is sloppy. When I run the Program it runs properly unless I put two improper user inputs. such as,
Program running//
--------------Monthly Use Report--------------
Minutes allowed were 450
Minutes used were 500
Minutes over were 50
Total due is $84.99
Do you want to end program? (Enter n or y):
g
Do you want to end program? (Enter n or y):
If I add Input.Next(); to nest if statement to
if(!endProgram.equals("y") || (!endProgram.equals("n"))){
System.out.println("Do you want to end program? (Enter n or y):");
endProgram = Input.next();
it displays it correctly. I tried messing with the massive do while loop that goes across the whole project. If anybody can help me it will be much appreciated. Sorry if this is confused I'll respond if you guys have any questions. Thanks in advance for any response and sorry for the inconveniences.
Replace
while (aui = false); //here you are assigning aui to false value
to
while (aui == false); //here you are comparing aui to false value
= is as assignment operator, == is comparison operator.
The best practise is to use boolean directly, not by comparing:
while (!aui);

validating if statement not working properly

I'm trying to make an if statement to catch if the user of the program enters a value besides y or n for the question asked at the end of the program "Continue? (y/n): ". But no matter what the value I input "y", "n", or something invalid I get the message "Invalid input try again" from the console. This is only supposed to happen when the choice is not y or n anyone know why it keeps happening regardless of what I input?
import java.util.Scanner;
public class ProductApp
{
public static void main(String[] args)
{
//display a welcome message
System.out.println("Welcome to the Product Selector ");
System.out.println();
// perform 1 or more selections
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("Enter Product Code: ");
String productCode = sc.next(); //read the product code
sc.nextLine() ; //discard any other data entered on the line
//make sure the case the user enters for a product code doesn't matter
productCode = productCode.toLowerCase();
// get the Product object
Product p = ProductDB.getProduct(productCode) ;
// display the output
System.out.println();
if (p != null)
System.out.println(p);
else
System.out.println("No product matches this product code. \n");
System.out.println("Product count: " + Product.getCount() + "\n" );
// see if the user wants to continue
System.out.println("Continue? (y/n): ");
choice = sc.nextLine() ;
System.out.println();
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
{
System.out.println("Invalid input try again");
continue;
}
}
}
}
also wherever I get the message "Invalid input try again" the program asks for a new input once but then moves on whether it's valid or not. it runs again if its "y" and closing if its anything else instead of asking a second time for a valid input.
Your condition is not working because you have ; after your if statement.
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
^^
Change
if( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") );
{
System.out.println("Invalid input try again");
continue;
}
TO
if(!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")))
{
System.out.println("Invalid input try again");
continue;
}
your condition is not correct it should be
if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")){
// choice is not y or n
}
choice.equalsIgnoreCase("y") && choice.equalsIgnoreCase("n") it will never be true
because choice may be either y or n but not both
Make it a while statement if you want it to ask until you input y or n. Otherwise it will jump to the big while loop and exit since the big one is asking for
while (choice.equalsIgnoreCase("y"))
so, the inner loop would look like this:
while( !choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n") )
{
System.out.println("Invalid input try again");
//continue; //not needed
}
EDIT: Another approach would be to treat only 'y' as yes and everything else as 'n'
// pseudocode
while (!choice.equalsIgnoreCase("n")) {
// do your thing
if (!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n"))) {
choice = "n"; // so exit
}
}
check your condition. it should be:
if(!(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n") ))
{
System.out.println("Invalid input try again");
continue;
}
if( !(choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) )
{
System.out.println("Invalid input try again");
continue;
}
Try this .
I think you should change if(!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")); to if(!choice.equalsIgnoreCase("y") || !choice.equalsIgnoreCase("n")){. Cause using && checks for both condition to be true and this can never happen since choice can contain only one value.

Categories

Resources