Java pseudocode to code [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm about to build a program written in Java. I've already done its pseudocode, but I'm stuck on the code and I don't know what to do exactly. Well this is my progress so far:
pseudocode:
class Customer
Print out “Enter costumer’s name” (Pop up to answer)
Random boolean
If True
print membership type
print current date and time
class Visit
Print out "Have you bought anything?" (Pop up to answer)
if the answer is “no”
print “Have a nice day!”
exit program
if else the answer is “yes”
continue
if else the answer is not “no” nor “yes”
ask again
class Discount
Print "Enter Price of Item:" (Pop up to price)
if customer's membership type is “Premium”
the discount to the price will be 20%
else if customer's membership type is “Gold”
the discount to the price will be 15%
else if customer's membership type is “Silver”
the discount to the price will be 10%
else if customer's membership type “simple”
the discount to the price will be 10%
class Main
Variables: customer, visit, discount
customer = new object
Customer visit = new object
Visit discount = new object Discount
do work with customer
do work with visit
do work with discount
Print customer.name, customer.surname, discount.price, discount.final_price
code:
import java.util.Scanner;
public class Discount
{
public static void main(String[] args)
{
String cust_name;
String cust_surname;
String answer;
String answer2;
float firstPrice, rate_1, D_rate, discount, final_price, prem_disc;
prem_disc = 0;
final_price = 0;
discount = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter Costumer's Name:");
cust_name = in.next();
cust_surname = in.next();
System.out.println("Have you bought anything?");
answer = in.next();
if (answer.equals("no"))
{
System.out.println("Have a good day!");
System.exit(0);
} else if (!answer.equals("no"))
System.out.println("Enter Price of Item:");
firstPrice = in.nextFloat();
System.out
.println("What type of membership do you have? Premium, Gold, Silver or simple?");
answer2 = in.next();
if (answer2.equals("Premium"))
{
prem_disc = 20;
discount = (firstPrice * 20 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("Gold"))
{
prem_disc = 15;
discount = (firstPrice * 15 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("Silver"))
{
prem_disc = 10;
discount = (firstPrice * 10 / 100);
final_price = (firstPrice - discount);
} else if (answer2.equals("simple"))
{
prem_disc = 10;
discount = (firstPrice * 10 / 100);
final_price = (firstPrice - discount);
}
System.out.println("Costumer Name:" + cust_name + " " + cust_surname
+ "\n" + "Discount Rate:" + prem_disc + "\n"
+ "Discounted Price:" + final_price + "\n");
}
}
It's working, but there are many things that are missing. :/

Just take one step at a time, and when that step completely works, proceed to the next step.
An example:
Here's your pseudo-code (which, by the way, is a great way to start):
class Visit
Print out "Have you bought anything?" (Pop up to answer)
if the answer is “no”
print “Have a nice day!”
exit program
if else the answer is “yes”
continue
if else the answer is not “no” nor “yes”
ask again
Let's just implement and test the "is the answer yes-or-no" functionality:
/**
<P>{#code java MyHomeworkMainClass}</P>
**/
public class MyHomeworkMainClass {
public static final void main(String[] ignored) {
System.out.println("Visit.isUserInputYesNo(null)=" + Visit.isUserInputYesNo(null));
System.out.println("Visit.isUserInputYesNo(\"gibberish\")=" + Visit.isUserInputYesNo("gibberish"));
System.out.println("Visit.isUserInputYesNo(\"yes\")=" + Visit.isUserInputYesNo("yes"));
System.out.println("Visit.isUserInputYesNo(\"no\")=" + Visit.isUserInputYesNo("no"));
}
}
class Visit {
public static final boolean isUserInputYesNo(String input) {
return (input != null &&
(input.equals("yes") || input.equals("no")));
}
}
Now run it and see if it does what you want:
[C:\java_code\]java MyHomeworkMainClass
Visit.isUserInputYesNo(null)=false
Visit.isUserInputYesNo("gibberish")=false
Visit.isUserInputYesNo("yes")=true
Visit.isUserInputYesNo("no")=true
It does. Now add something else small to this and just keep going until you're done. For particularly difficult parts, it may be beneficial to create a completely separate class, with its own testing class. Then at the end, merge it all together. And never get rid of your testing functions, which will always be there for diagnosing future problems.
Good luck!

Related

Java Program Quiz [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 13 hours ago.
Improve this question
I am trying to create a 5 questions quiz, after question 4 it automatically prints question 5 and not ask first, and then proceeds on printing the results. here is my code
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name, section;
int score, numQuestions = 5;
System.out.println("Welcome to the Basic Electronics Quiz!");
boolean repeat;
do {
// Get name and section
System.out.print("Enter your name: ");
name = scanner.nextLine().trim();
System.out.print("Enter your section: ");
section = scanner.nextLine().trim();
// Initialize score
score = 0;
// Question 1
System.out.println("\nQuestion 1: What is Ohm's Law?");
System.out.println("A. Voltage = Current x Resistance");
System.out.println("B. Current = Voltage x Resistance");
System.out.println("C. Resistance = Voltage / Current");
System.out.print("Answer: ");
String answer1 = scanner.nextLine().trim().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "A" + ".");
}
System.out.println();
// Question 2
System.out.println("\nQuestion 2: What is the unit of resistance?");
System.out.println("A. Ampere");
System.out.println("B. Volt");
System.out.println("C. Ohm");
System.out.print("Answer: ");
String answer2 = scanner.nextLine().trim().toLowerCase();
if (answer2.equals("c")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "C" + ".");
}
System.out.println();
// Question 3
System.out.println("\nQuestion 3: An LED is a type of resistor. (True/False)");
System.out.print("Answer: ");
String answer3 = scanner.nextLine().trim().toLowerCase();
if (answer3.equals("true")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "True" + ".");
}
System.out.println();
// Question 4
System.out.println("Question 4: What is the total resistance of two 10-ohm resistors in parallel?");
System.out.print("Your answer: ");
try {
double answer4 = scanner.nextDouble();
double expectedAnswer4 = 5.0;
if (Math.abs(answer4 - expectedAnswer4) < 0.0001) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The correct answer is " + expectedAnswer4 + ".");
}
System.out.println();
} catch (Exception e) {
// If there's an error parsing the input, don't add to score
}
// Question 5
System.out.println("\nQuestion 5: What is the term for a circuit that can generate an output signal with a fixed frequency?");
System.out.print("Your answer: ");
String answer5 = scanner.nextLine().trim().toLowerCase();
if (answer5.contains("Occilator") && answer5.contains("occilator")) {
score++;
}
else {
//System.out.println("Wrong. The correct answer is " + "Oscillator" + ".");
}
System.out.println();
// Display results
System.out.printf("\n%s, section %s, your score is %d/%d.\n", name, section, score, numQuestions);
// Ask to repeat
System.out.print("\nDo you want to take the quiz again? (yes/no): ");
String repeatStr = scanner.nextLine().trim().toLowerCase();
repeat = repeatStr.equals("yes") || repeatStr.equals("y");
} while (repeat);
System.out.println("\nThank you for taking the quiz!");
}
}
I tried copying only the question 5 to another file and it works but when i paste it again in the main file it will only proceeds on printing the results instead of asking for question 5
The problem is in using scanner.nextDouble();. You can read here more about why the problem occurs on this line.
You can solve your problem if you use Double.parseDouble(scanner.nextLine()); instead of scanner.nextDouble();.
Also, as Gilbert Le Blanc
has stated in the comments, you need to update the condition in your 5th question from answer5.contains("Occilator") && answer5.contains("occilator") to answer5.contains("Occilator") || answer5.contains("occilator"), otherwise you will never be able to answer the 5th question correctly. Here you also meant to write oscillator and not ocillator.
Here is an example output after implementing the solution:
Welcome to the Basic Electronics Quiz!
Enter your name: Aleksa
Enter your section: 1
Question 1: What is Ohm's Law?
A. Voltage = Current x Resistance
B. Current = Voltage x Resistance
C. Resistance = Voltage / Current
Answer: a
Correct!
Question 2: What is the unit of resistance?
A. Ampere
B. Volt
C. Ohm
Answer: c
Correct!
Question 3: An LED is a type of resistor. (True/False)
Answer: true
Correct!
Question 4: What is the total resistance of two 10-ohm resistors in parallel?
Your answer: 5
Correct!
Question 5: What is the term for a circuit that can generate an output signal with a fixed frequency?
Your answer: occilator
Aleksa, section 1, your score is 5/5.
Do you want to take the quiz again? (yes/no):

is there any way I could make this code shorter?

This is a simple code, however, I wanna know if I could somehow make it shorter, I don't know that much to even know what to look for, so I'm not looking for someone to rewrite if for me, I only want someone to tell me what methods should I use, how do I call a variable the user wrote outside if, or such things that would help me. I'm new to coding, so sorry if I'm making a stupid question.
System.out.println("Write name: ");
name = s.nextLine();
System.out.println("Write last name: ");
lastName = s.nextLine();
System.out.println("Write id: ");
id = s.nextInt();
System.out.println("Write your average GPA: ");
average = s.nextDouble();
System.out.println("Your name is:" +name+ "\nYour last name is: "
+lastName+ "\nYour GPA is: " +average+ "\nYearly tuition is: "
+tuitionCost);
if(average >= 9.0){
System.out.println("Your discount is: 20% off.");
d = 100-20;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else if(average <= 8.99 && average >= 8.5){
System.out.println("Your discount is: 10% off.");
d = 100-10;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else if(average <= 8.49 && average >= 8.0){
System.out.println("Your discount is: 5% off.");
d = 100-5;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
}
else{
System.out.println("You have no discount. Your yearly tuition is: "
+tuitionCost);
}
You could turn your discounts into a class:
class Discount {
private final List<Tier> tiers = List.of(
new Tier(0.0, 0), new Tier(8.0, 5), new Tier(8.5, 10), new Tier(9.0, 20));
private class Tier {
private final double gpa;
private final int discount;
}
private int discount(double gpa) {
return tiers.stream().filter(t -> t.gpa <= gpa)
.mapToDouble(t -> t.discount).max().getAsDouble();
}
public double tuition(double gpa, double base) {
return (1.0 - discount(gpa)/100.0) * base;
}
public String discountMessage(double gpa) {
if (discount(gpa) == 0)
return "You have no discount";
else
return "Your discount is " + discount(gpa) + "%";
}
}
I've left some details out but you get the idea.
This may be overkill - it would depend on how often the tiers might change. But it does satisfy the DRY principle (don't repeat yourself). This makes your code more resilient: it's less likely you will change your code in one place and forget to change it elsewhere.
You mention making your code shorter. I subscribe to the principle that you should look for clarity before brevity.
Well, the logic certainly could be simplified a little: if you are careful to write the if..else if sequence in descending order, your logic could simply be:
/* CAUTION: KEEP IN DESCENDING ORDER! ... yes, add this comment! */
if (average >= 9.0) {
}
else if (average >= 8.5) {
}
... and so on. (Which also makes each of the if-conditions consistent.)
Now, be very careful that your else case does all of the things that all of the other cases do: it should assign values to d and to total. It should "look exactly like all the other ones."
Beyond that, I probably wouldn't change a single thing, and here's why: the logic is now "fairly obvious at first glance," and each of the cases are clearly independent. If "the marketing department" suddenly comes up with a grand new idea which only applies to some of the cases but not others ... (and marketing departments always do) ... you're covered. Future programmers could simply "make small, targeted commits" to this logic and they'd never have to re-write it.
Yes, you could simplify by
int discount = -1;
if(average >= 9.0){
discount = 20;
}
else if(average <= 8.99 && average >= 8.5){
discount = 10;
}
.
.
System.out.printf("Your discount is: %d%% off.%n", discount);
d = 100-discount;
total = (d * tuitionCost)/100;
System.out.println("Your yearly tuition is: " +total);
Note
The if-else could be better as a swtich

my program doesn't run completely [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....

How would you write Junit tests for this code?

Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.

JAVA: Runtime Exception (I think that's what i need to use)

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

Categories

Resources