Working on a coding assignment and we have to incorporate methods and returning it. However, that is the beside the point. I am struggling on the price calculation portion. Okay, here's the gist of what I am stuck with. When the program asks, is your car and import. If the answer is yes, you will be charge with a 7% import tax, if no, the charge is negated. Now, the program asks for four services, depending on yes or no, the charge will be added based on their answer.
So, if the user wants an Oil Change and Tune Up and if their car is an import the services price will be added along with the import tax or if the car is not an import but want all services then the charges will be displayed without the import tax added, etc... The final outcome would display "Before taxes, it would be $# and after taxes, your total is..." An if statement is required but I do not know where to start because I am mainly struggling with the yes or no... Any help? My professor advised me to use an accumulator so I added one.. No avail, I am lost, any help would be greatly appreciated.
import java.util.Scanner;
public class CarMaintenance
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String car;
//capture car
System.out.println("What is the make of your car");
car = keyboard.nextLine();
String answer;
boolean yn;
System.out.println("Is your car an import?");
while (true)
{
answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("yes"))
{
yn = true;
break;
}
else if (answer.equalsIgnoreCase("no"))
{
yn = false;
break;
}
else
{
System.out.println("Sorry, I didn't catch that. Please answer yes or no");
}
}
String[] services = {"Oil Change", "Coolant Flush", "Brake Job", "Tune Up"};
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
}
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
// double total = 0;
double c = 0;
c = car(amount);
// c = car(total);
System.out.println("The price for your services for your" + " " + car + " " + "is" + " "+ c + ".");
}
public static double car(double amount)
{
return (double) ((amount-32)* 5/9);
}
}
Before I talk about your code, I recommend you read this article.
Rubber Duck Debugging.
It is a bit flippant, but there is a deep truth to it. And it maps neatly with a debugging technique that I was taught .... umm ... 40 years ago.
First I draw your attention to this:
System.out.println("Is your car an import?");
while (true)
{
answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("yes"))
{
yn = true;
break;
}
else if (answer.equalsIgnoreCase("no"))
{
yn = false;
break;
}
else
{
System.out.println("Sorry, I didn't catch that. Please answer yes or no");
}
}
That code does a pretty good job of asking a "yes or no" question and getting the answer. It includes code to retry if the user responds with something that isn't recognizable as "yes" or "no".
So I'm guessing that someone wrote that code for you ... or you found it somewhere. You need to read that code carefully, and make sure you understand exactly how it works.
Next, I draw your attention to this:
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
}
This code does not make sense. (Explain it to your rubber duck!)
Your earlier code is a good example of how to ask a yes / no question. But this is nothing like that:
You are not testing for "yes" or "no".
You are not repeating if the user gives an unrecognizable answer
You are not even storing the answer .... for each distinct service.
Then this:
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
It looks like this is trying to add the price of service items to the overall amount. But:
You are doing it for every service item, not just the items that the customer asked for.
You are actually doing the calculation incorrectly anyway. (Talk to your Rubber Duck about it!)
How to fix this?
Some things should be obvious from what I said above.
The problem of remembering the answers from the first for loop and using them in the second for loop ... is actually a problem you can / should avoid. Instead, combine the two loops into one. Here's some pseudo code:
for each service:
ask the user if he wants this service
if the user wants this service:
add the service cost to the total.
Understand the logic of that, and translate it into Java code. (Yes I could write it for you, but that defeats the purpose!)
If you would want the charges to be added to the value of answer you should do it in only one for loop and because the index of services and prices line up just use and if statement to check if the response is yes
String[] services = {"Oil Change", "Coolant Flush", "Brake Job", "Tune Up"};
for(int i=0; i<services.length; i++)
{
System.out.println("Do you want a " +services[i]);
answer = keyboard.next();
if(answer.equalsIgnoresCase()){
answer += prices[i]
}
}
double amount = 0;
double[] price = {39.99, 59.99, 119.99, 109.99};
for(int i =0; i<price.length; i++)
{
amount = (price[i] + price [i]);
}
Related
Basically this program roles a dice between a computer and then shows who got the higher score. So in my last if/else statement, the main difference is you won, vs you lost. Is there anyway that I can combine this so it's cleaner? I tried combining it but couldn't figure it out. Any ideas? Appreciate it!!
//import scanner and random
import java.util.Random;
import java.util.Scanner;
//declare variables and methods
class Main {
int userOne, userTwo, compOne, compTwo, userTotal, compTotal;
char playAgain;
Scanner scan = new Scanner(System.in);
Random gen = new Random();
//method to run entire program
public void runProgram()
{
int r=1;
//this will run the roll of the dice for the user and the computer
for(r=1; r<2;)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
if (userTotal > compTotal)
{
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
r=1;
}
else
{
r=2;
}
}
else
{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
r=1;
}
else
{
r=2;
}
}
}
}
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
Yes, by moving the code responsible for determining whether or not to run the program again outside the if/else statement since it doesn't matter if the user won or lost, in the end, the question remains the same: do you want to play again or not? regardless of the result, therefore such logic should not be encapsulated by the logic responsible for determining who one (because again, irrelevant).
The second thing and this is totally optional but it will make your code cleaner, it seems you're using if/else statements just to determine which values should be assigned to variables, in such cases, it is cleaner to use the ternary operator
And one more thing, when using methods that return a boolean true/false it is unnecessary to type == false/true since the function itself already does that, such as the equalsIgnoreCase() function.
So after all of these edits, your code looks something like this:
//import scanner and random
import java.util.Random;
import java.util.Scanner;
//declare variables and methods
class Main {
int userOne, userTwo, compOne, compTwo, userTotal, compTotal;
char playAgain;
Scanner scan = new Scanner(System.in);
Random gen = new Random();
String result;
//method to run entire program
public void runProgram() {
int r=1;
//this will run the roll of the dice for the user and the computer
for(r=1; r<2;)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
result = userTotal > compTotal ? "won! " : "lost. ";
// Ternary operator
System.out.println("you " + result + "Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
// another ternary operator
r = String.valueOf(playAgain).equalsIgnoreCase("y") ? 1 : 2;
}
}
public static void main(String[] args) {
Main prog = new Main();
prog.runProgram();
}
}
Like khelwood suggested, you can combine the play again messages outside of the win/loss if statement.
if (userTotal > compTotal) {
System.out.println("You won!");
} else {
System.out.println("Sorry, you lost.");
}
System.out.println("Would you like to play again? Yes or No?");
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y")) {
r = 1;
} else {
r = 2;
}
One thing that I would say could be improved with this code is avoiding copying and pasting code. Don't ever repeat yourself.
Second thing to improve is you could make your loop while((String.valueOf(playAgain)).equalsIgnoreCase("y")) instead of your weird for loop. That way you don't have a confusing r variable that is based on whether or not playAgain is 'y'.
public void runProgram()
{
playAgain = 'y';
//this will run the roll of the dice for the user and the computer
while ((String.valueOf(playAgain)).equalsIgnoreCase("y") == true)
{
System.out.println("Your turn:");
userOne = gen.nextInt(6)+1;
System.out.println("Your first roll was: " + userOne);
userTwo = gen.nextInt(6)+1;
System.out.println("Your second roll was: " + userTwo);
userTotal = userOne + userTwo;
System.out.println("Your total of the two rolls was: " + userTotal);
System.out.println("Computers turn:");
compOne = gen.nextInt(6)+1;
System.out.println("The computers first roll was: " + compOne);
compTwo = gen.nextInt(6)+1;
System.out.println("The computers second roll was: " + compTwo);
compTotal = compOne + compTwo;
System.out.println("The computers total of the two rolls was: " + compTotal);
//This determines win or loss and lets the user choose if they want to play again
if (userTotal > compTotal)
{
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
}
else
{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
}
playAgain = scan.next().charAt(0);
}
}
Making these changes make your code a little more clear about what you're intending the program to do.
Just moves duplicated stuff out of the if-else statement.
Also, == true can be removed from if() since it already returns a boolean value.
if (userTotal > compTotal){
//winning- statement to ask if the user wants to play again
System.out.println("You won! Would you like to play again? Respond with Yes or No: ");
}else{
//losing- statement to ask if the user wants to play again
System.out.println("Sorry, you lost. Would you like to play again? Yes or No?");
}
playAgain = scan.next().charAt(0);
if ((String.valueOf(playAgain)).equalsIgnoreCase("y")){
r=1;
}else{
r=2;
}
I am doing this assignment for my CSCI 1301 class and i'm kinda stuck.
The assignment is to write a program that will provide a list of services to users and allow them to choose any or all services they would like and display the final price.
Here's my code so far,
public static void carMaintenance()
{
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.next();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
System.out.println("What services whould you like for your "+makeOfCar+"?");
System.out.println(services[0]+", "+services[1]+", "+services[2]+", "+services[3]+".");
}
Where i'm stuck at is how would I go about allowing the user to request as many services they want?(Logically speaking, they can only request up to 4 services)
I figured I could use another array and put it in a "do-while" loop to achieve this but then, once I check it against the "services" array how would I assign a price to each service the user requested so that I can calculate the total price for all requested services?
any insight and help is greatly appreciated!
You could keep track of the sum in an extra variable. So your idea with the extra array to check for duplicates would still work. Check if the service is already chosen and if not, add the chosen index to the sum.
public static void carMaintenance() {
Scanner sc = new Scanner(System.in);
String makeOfCar;
System.out.println("What's the make of your car?");
makeOfCar = sc.nextLine();
String[] services = {"Oil Change", "Tire Rotation", "Air Filter", "Fluid Check"};
double[] prices = {39.99, 49.99, 19.99, 10.99};
double sum = 0;
System.out.println("What services whould you like for your " + makeOfCar + "?");
System.out.println(services[0] + ", " + services[1] + ", " + services[2] + ", " + services[3] + ".");
String choice;
//This array simply tracks true or false for chosen/not chosen. boolean arrays are initialized with all values false.
boolean[] chosenServices = new boolean[services.length]; //Can only be as many elements as there are services. This way you don't have to change it when you add another service
do {
choice = sc.nextLine();
int choiceIndex = getIndex(services, choice);
if (choiceIndex < 0) break; //Choice doesn't exist. You will have to refine that and add messages
if (!chosenServices[choiceIndex]) { //service not yet chosen
chosenServices[choiceIndex] = true;
sum += prices[choiceIndex];
} else {
System.out.println("Was already chosen!");
}
} while (!choice.toLowerCase().equals("exit")); //Or something similar
System.out.printf("%.2f", sum); //Price with 2 digits
}
public static int getIndex(String[] arr, String search) {
for (int i=0; i<arr.length; i++) {
if (search.equals(arr[i]))
return i;
}
return -1;
}
As mentioned in one of the comments, this is only a rough implementation. You might want to do this with index input from the user, you might want to check for false inputs more precise than I did here etc. but that should do what I think you mean.
So basically I have this survey program and I want to know how to calculate the percentage of questions answered that match the response given by the "if" statements. but this percentage can vary based on what the user types. another thing is that I need to put the code for calculating percentage into a non-main method which I have already setup and commented on (labeled non-main method) in the code below. What i want to know is how to make a formula that will account for all possible user inputs (basically 1/5, 2/5, 3/5, 4/5 and 5/5 since the survey is 5 questions) .
import java.util.Scanner;
public class VideogameSurveyFINAL {
//non-main method
private static void gamerpercentagelikeme (String[] args) {
int correct
}
//main method below
public static void main(String[] args) {
boolean run = true;
while(run){
System.out.println ("WELCOME TO THE GRAND SURVEY OF VIDEOGAMES!");
System.out.println ("");
Scanner keyboard = new Scanner(System.in);
//Q1
System.out.println("Question 1: Do you like Videogames? (Please answer Yes or No)");
String input = keyboard.nextLine();
if (input.equalsIgnoreCase("Yes")||input.equalsIgnoreCase("Yeah")||input.equalsIgnoreCase("Y")||input.equalsIgnoreCase("YES!")) {
System.out.println("Awesome!");
}
else {
System.out.println("Wow. You have no sense of fun.");
}
//Q2
System.out.println ("");
System.out.println("Question 2: What types of videogames do you play?(Please use abbreviated froms of games such as FPS, MMO, RPG etc).");
String input2 = keyboard.nextLine();
if (input2.equalsIgnoreCase("Fps")) {
System.out.println("Fantastic! Me too!");
}
else {
System.out.println("OK, thats cool!My favorite is FPS.");
}
//Q3
System.out.println ("");
System.out.println("Question 3:Do you like Singleplayer or Multiplayer games? ");
String input3 = keyboard.nextLine();
if (input3.equalsIgnoreCase("Singleplayer")||input.equalsIgnoreCase("S")||input.equalsIgnoreCase("SP")) {
System.out.println("Me Too!!");
}
else {
System.out.println("Rad! My favorite is Singleplayer. ");
}
//Q4
System.out.println ("");
System.out.println("Question 4: What do you like in a videogame");
String input4 = keyboard.nextLine();
if (input4.equalsIgnoreCase("I dont play games")||input.equalsIgnoreCase("None")||input.equalsIgnoreCase("N")) {
System.out.println("You are sooooo boring.");
}
else {
System.out.println("Awesome! What I like in a videogame is solid gameplay, great graphics and immersive audio...but most of all, IT HAS TO BE FUN!!");
}
//Q5
System.out.println ("");
System.out.println("Question 5: What is your ALL-TIME favorite videogame?");
String input5 = keyboard.nextLine();
if (input5.equalsIgnoreCase("Skyrim")) {
System.out.println("Really?! ME TOO!");
}
else {
System.out.println("Great! My personal favorite is SKYRIM!");
}
System.out.println ("");
System.out.println("THANK YOU FOR TAKING THE GRAND SURVEY OF VIDEOGAMES!");
System.out.println ("");
System.out.println ("Would you like to take the survey again? (Please answer with Yes or No: Case sensitive)");
String input6 = keyboard.nextLine();
if (input6.equalsIgnoreCase("No")) {
break;
}
else
{
System.out.println("Okay! The Survey will restart shortly.");
System.out.println ("");
System.out.println ("");
}
}
}
}
Right inside of public static void main(String[] args) { declare a public variable like:
int questionsCorrect = 0; //this is where we will keep track of the questions 'correct'
Now every time we get a question right, we will increment this count.
Inside of the if(condition...) statements, we will do this increment.
For example:
if (input.equalsIgnoreCase("Yes")||input.equalsIgnoreCase("Yeah")||input.equalsIgnoreCase("Y")||input.equalsIgnoreCase("YES!")) {
System.out.println("Awesome!");
questionsCorrect++; //increment number of questions correct by 1
}
do this for every question in the survey.
Now for the percentage... I believe that it would be wise to change the private static void gamerpercentagelikeme (String[] args) method's parameters to take the questions correct and the total questions, then returning the percentage in decimal form.
private static double gamerpercentagelikeme (int correct, int total){
return correct/total;
}
Now at the end when we want to display the answer, we can call:
double results = gamerpercentagelikeme(questionsCorrect, TOTAL_QUESTIONS); //note: declare TOTAL_QUESTIONS before using it.
double percentageLikeMe = results * 100;
System.out.println(percentageLikeME + "% like me.);
Hope this helps.
If i'm understanding correctly, you need to calculate the percentage of questions that the user got right?
You need to have a new field that is an int that stores the number of questions they got right, initialized to zero. Then every time they get a question right you increment this total by one.
Then at the end of the program you do that field divided by the total number of questions
My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));
Ok, I need my program to validate user entered data. If that data is invalid, the program needs to skip almost all of my code and get to the end of my while loop to ask if the user would like to proceed with calculating another loan. My professor has not provided us with a method of doing this and all the information ive found on the internet is not specific enough to help me. Once again, I need the code after the validation to be skipped without exiting the program and go to the end of the loop where I ask the user if they want to calculate another loan. Here is my code thus far.
/* This program is an extension of the previous Interest Calculator. The only different is this one can
compute not only simple interest but daily and monthly compound interest using a switch statement to
differentiate each type of interest. */
import javax.swing.*;
// Import the GUI methods
public class InterestCalculatorLoop {
public static void main(String[] args) {
// Entry point of program
String again = "yes";
while (again.equalsIgnoreCase("yes" ))
{
String option = JOptionPane.showInputDialog("Which type of loan would you like to find interest for? \n1 = Simple Interest \n2 = Monthly Compounded Interest \n3 = Daily Compounded Interest");
int optionInt = Integer.parseInt(option);
int interestType = Integer.parseInt(option);
String paString = JOptionPane.showInputDialog("Enter the principal amount");
double pa = Double.parseDouble(paString);
double interest = 0;
double months = 0;
double totalInterest = 0;
double years = 0;
final double daysInYear = 365.0;
final double daysInMonth = 30.41666666667;
final double monthsInYear = 12.0;
// Logic statements to validate user input or otherwise run through the rest of the program without calculation
if (pa <= 0)
{
JOptionPane.showMessageDialog(null, "Data Error: The principal amount must be greater than zero. You entered " + pa);
return;
}
else
{
String interestString = JOptionPane.showInputDialog("Enter The Annual Interest Rate [1 - 100 percent]) ");
interest = Double.parseDouble(interestString);
}
if (interest < 0 || interest > 100)
{
JOptionPane.showMessageDialog(null, "Data Error: The interest amount must be between 1 and 100. You entered " + interest);
return;
}
else
{
String monthsString = JOptionPane.showInputDialog("Enter the number of months");
months = Double.parseDouble(monthsString);
}
if (months <= 0)
{
JOptionPane.showMessageDialog(null, "Data Error: The number of months must be above 0. You entered " + months);
return;
}
else
{
switch (optionInt)
{
// Case for simple intrest
case 1: optionInt = 1;
months = months/monthsInYear;
totalInterest = pa * (interest/100.0) * months;
JOptionPane.showMessageDialog(null, "The total amount of interest of your loan is $" + totalInterest + ".");
break;
// Case for monthly compounded interest
case 2: optionInt = 2;
interest = interest/100.0;
years = months/monthsInYear;
double exponent = months*years;
double interestOverMonths = 1+interest/months;
double thirdTotal = Math.pow(interestOverMonths, exponent);
double secondTotal = pa*thirdTotal;
totalInterest = secondTotal - pa;
JOptionPane.showMessageDialog(null, "The total amount of interest of your loan is $" + totalInterest + ".");
break;
// Case for daily compounded interest
case 3: optionInt = 3;
interest = interest/100.0;
double days = months*daysInMonth;
years = days/daysInYear;
exponent = days*years;
double interestOverDays = 1+interest/days;
thirdTotal = Math.pow(interestOverDays, exponent);
secondTotal = pa*thirdTotal;
totalInterest = secondTotal - pa;
JOptionPane.showMessageDialog(null, "The total amount of interest of your loan is $" + totalInterest + ".");
break;
}
}
again = JOptionPane.showInputDialog("Would you like to compute another loan? (yes or no)");
}
}
}
Break is very useful for stopping loops as you said you wanted. Essentially it has the effect of setting the boolean parameter of a for loop to true.
You can of course, use what in CMD is referred to a GOTO. you can create something like:
top:
for(int i = 0; i < 10; i++){
if(i == 9){
break top;
}
}
I've skimmed through your code and to be honest, I don't know much about loans and the calculations associated with it.
As you're clearly still learning the basics, a simple solution by the looks of it would be to take out:
while (again.equalsIgnoreCase("yes" ))
{
/*
* FROM HERE
*/
String option = JOptionPane.showInputDialog("Which type of loan would you like to find interest for? \n1 = Simple Interest \n2 = Monthly Compounded Interest \n3 = Daily Compounded Interest");
int optionInt = Integer.parseInt(option);
//...
/*
* TO HERE
*/
again = JOptionPane.showInputDialog("Would you like to compute another loan? (yes or no)");
}
And put it in its own method called for example:
public static void askAndProcessDetails()
So when you return you will go to the repeat dialogue.
while (again.equalsIgnoreCase("yes" ))
{
askAndProcessDetails();
again = JOptionPane.showInputDialog("Would you like to compute another loan? (yes or no)");
}
continue is maybe one of the worse feature of java, with the break keyword (except in switch statements). It leads to jigsaw code where you have to find out where the code jumps. One continue may be practical but it gets very hard to change the code it produces (think about adding an inner loop..), and 2 continues will make you crazy.
You can always avoid using continue, there is always another solution. Same for break.
Here, why don't you just use some kind of
if( answerIsValid ) {
//process it
...
}//if
That's easy, simple, clear and even better when you have a separate method that contains processing.
Also, in your case, that is tied to robustness, you could provide a process() method that throws an exception if the data entered is not valid. This makes it even more clear that there is a "normal" program behavior and a bunch of strange cases you handle as errors.
public void processAnswer( String stringAnswer ) throws ArithmeticException {
int answer = Integer.parseInt( stringAnswer );
//rest of processing
...
}//met
then your main loop becomes
String again = "yes";
while (again.equalsIgnoreCase("yes" ))
{
String stringAnswer = JOptionPane...
try {
process( stringAnswer );
} catch( ArithmeticException ex ) {
JOptionPane.showMessageDialog( "This is not an integer !" );
}//catch
}//while