Answer returning 0 - java

Total beginner in Java. My result keeps turning up as 0 where I want it to turn up as membercount * members (ie if there are 100 members and the weather = 1, the total should be 25). I can't seem to figure out where I'm going wrong. I figure I'm not properly having my program store the information entered by the user so the doubles keep reading as 0. Here is my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package playgolf;
import java.util.Scanner;
import javax.swing.JOptionPane;
/**
* #author Alex
*/
public class PlayGolf {
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
golf total = new golf();
total.display_data();
}
}
class golf {
private double members;
private double weather;
private double temp;
private double membercount;
public double total;
public void getData() {
Scanner input = new Scanner(System.in);
System.out.print("How many members are there?: ");
members = input.nextInt();
System.out.print("What is the weather like? (Enter 1 for sunny, 2 for overcast, 3 for rain): ");
weather = input.nextInt();
System.out.print("What is the temperature? (in Farenheight): ");
temp = input.nextInt();
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
if (temp < 32) {
membercount = 0;
System.out.println("No one will play today, it's too darn cold!");
}
total = (membercount * members);
}
public void display_data() {
System.out.println(" ");
System.out.println("This many members will play today: ");
System.out.println(total);
}
}

You create new object again, it should be:
public static void main(String[] args) {
golf stats = new golf();
stats.getData();
stats.display_data();
}

Bug 1
The code blocks related to your weather logic are messed up; the closing braces are in the wrong place.
Properly indented, your code looks like this:
if (weather == 1) {
membercount = .25;
if (weather == 2) {
membercount = .12;
if (weather == 3) {
membercount = .03;
}
}
}
Now you can probably already see the bug. If weather is 2, the weather == 2 condition will never be reached (weather cannot be 1 and 2 at the same time).
Corrected version:
if (weather == 1) {
membercount = .25;
}
else if (weather == 2) {
membercount = .12;
}
else if (weather == 3) {
membercount = .03;
}
Bug 2
Another bug is in the main method. You should call display_data() on the same object as getData(). This would work:
golf stats = new golf();
stats.getData();
stats.display_data();
Other problems & style issues
display_data is not idiomatic Java method name. Should be displayData.
Likewise, Java class names should start with uppercase letter. Golf, not golf. See e.g. this guide on Java naming conventions.
It's suspicious to use double to represent one of three possible values (weather). Use int, or better yet, an enum. Also for members it is a pretty odd choice of type.

Since your if conditions are nested, if weather != 1, the checks for weather == 2 and weather == 3 are never reached.
As a consequence, membercount is never set and takes the value of zero, yielding your zero result for total.
You should just have something like the following:
switch (weather) {
case 1:
membercount = .25;
break;
case 2:
membercount = .12;
break;
case 3:
membercount = .03;
break;
default:
// Do nothing or, better yet, produce an error
}
if (temp < 32) {
// ...
You could simply use a series of ifs, or an if-else chain. I'm using a switch because it's the safest choice in this case. This assumes that you change weather to be an int, which is actually preferable given your use of the variable. You should also esplicitly initialize the value of weather during declaration (or in the constructor, as you see fit):
private int weather = 0;
As pointed out by the other answers, you have a secondary bug in your listing: you should create only one object and have both calls on that, as follows:
golf stats = new golf();
stats.getData();
stats.display_data();

You are calling getData() on one instance (of golf) and calling display_data() on another one. The stats collects data, but the total does not. Try to call display_data() on stats instance / or call getData() on total instance / or use shared members (statics I mean).
golf stats = new golf();
stats.getData();
stats.display_data();
or
golf total = new golf();
total.getData();
total.display_data();

Related

How to get my rate values to display correctly?

I finally got my program to compile without any errors and the first half is correct the total pay, retirement deduction and net pay were all displaying 0. I saw from a different post that Java doesn't analyze the logic of your if blocks so I edited my code to have my rate assigned to 0 and my if statement to return rate. I'm now getting the error "unexpected return value". How do I get my program to have the appropriate value depending on the user's input?
import java.util.*;
public class AcmePay {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
double hours;
int shift;
int plan;
double rate = 0;
double overtimePay;
double paycheck;
//double retirement;
// double retirement = paycheck - (paycheck * .03);
//double netPay = paycheck - retirement;
System.out.println("How many hours did you work this week?");
hours = keyboard.nextDouble();
if ( hours <= 40 )
{
paycheck = hours * rate;
}
else
{
paycheck = (40 * rate) + ((hours - 40)) * (rate*1.5);
}
System.out.println("What shift did you work? 1, 2, or 3?");
shift = keyboard.nextInt();
if (shift == 1)
{
rate = 17;
return rate;
}
else if (shift == 2)
{
rate = 18.50;
return rate;
}
else if (shift == 3)
{
rate = 22;
return rate;
}
To print the rate, the last part of your code can be like this:
shift = keyboard.nextInt();
if (shift == 1) {
rate = 17;
} else if (shift == 2) {
rate = 18.50;
} else if (shift == 3) {
rate = 22;
}
System.out.println("Rate = " + rate);
i.e. remove the return statements and then print the rate at the end. You can't return a value from a void method like main(), hence the error.
If you want to calculate the rate using a separate method, you would do something like this:
private static double rateForShift(int shift) {
if (shift == 1) {
return 17;
} else if (shift == 2) {
return 18.50;
} else if (shift == 3) {
return 22;
}
return 0;
}
This method returns a double, so now you can (and have to) use return statements.
You would call it from the main method with:
double rate = rateForShift(shift);
It's a good idea to split your code into focused methods, like this, because it makes it easier to read and work with.
I think your code has a "logic" bug in it because you are using the rate variable to calclulate paycheck, but the rate variable is always 0 at the point you use it. You should probably ask both questions before you calculate the paycheck amount.
A full program would look like this:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many hours did you work this week?");
double hours = keyboard.nextDouble();
System.out.println("What shift did you work? 1, 2, or 3?");
int shift = keyboard.nextInt();
double paycheck = calculatePayCheck(rateForShift(shift), hours);
System.out.println("Paycheck = $" + paycheck);
}
private static double calculatePayCheck(double rate, double hours) {
if (hours <= 40) {
return hours * rate;
} else {
return (40 * rate) + ((hours - 40) * (rate * 1.5));
}
}
private static double rateForShift(int shift) {
if (shift == 1) {
return 17;
} else if (shift == 2) {
return 18.50;
} else if (shift == 3) {
return 22;
}
return 0;
}
In Java programs you don't need to declare your variables at the top. The convention is to declare them as you need them.
Example
How many hours did you work this week?
20
What shift did you work? 1, 2, or 3?
2
Paycheck = $370.0
It's also worth mentioning that, although fine for a toy example, in a real system you should not use floating point numbers (like double) to represent money.
ELEVATE covered the code, so I'll cover the theory.
In Java (and in many other programming languages), a method is a block of code that may or may not take in an input and may or may not give an output. Whether or not the method gives an output can be determined by analyzing the method definition. If a primitive type (for example, int or double) or Object (for example, Scanner) is used in the method definition, then that method will return that type as output. If the keyword void is used in the method definition, then that method will return no output.
A key point to understand is this: Once a method is told to return a value, that method will terminate. Thus, you cannot include any code after a return statement, or your compiler will be angry with you and yell at you for including "unreachable code."
Now, to apply this to the specifics. The main method in Java uses the keyword void to indicate that it will not return any sort of output. Thus, return rate; is inappropriate for two reasons:
Returning a double value is indeed some sort of output, which contradicts the method definition of main in which main was set to return no output by the keyword void.
return rate; will cause your program to terminate immediately. Assuming that ELEVATE was correct about how you should reorder your code, leaving a return statement in your answer would cause you further problems by preventing your code from moving on to calculate your paycheck.
Side Note: A method that returns no output can still use the return keyword, but it cannot be used with any sort of value or object. For example, the following method is valid because return isn't paired with any sort of value.
public class ReturnExample {
/*Other stuff.*/
public void returnNothing() {
System.out.println("Now returning nothing.");
return;
}
}
}

Return more than one variable from a Java method

Your program must read the id number and gpa and transfer the data into two separate arrays. You can assume there will never be more than 1000 students in the file. Do you know why you must use two separate arrays? You may find it useful in this program to create additional arrays to complete the requirements of the program as described next.
Your program must do two distinctly different things correctly for full credit:
You must create a simple diagram to show how many students fall into each of 8 different categories. This type of diagram is known as a histogram and it is generally useful to show how data is distributed across a range.
For each student in the input file, you must display their S-number, gpa, and class rank. The S-number and gpa will already be in your arrays; however, you must calculate their class rank.
Here is the code I have so far:
public static void main(String[] args) throws Exception
{
Scanner gpadata;
String snum;
double gpa;
int groupNumber;
gpadata = new Scanner(new File("studentdata.txt"));
while (gpadata.hasNext())
{
snum = gpadata.next();
gpa = gpadata.nextDouble();
groupNumber = gpaGroup(gpa);
System.out.println("Student number, GPA, and group number"
+ " is: " + snum +
" " + gpa + " " + groupNumber);
}
}
//Method to categorize students GPA into 1 of 8 groups
public static int gpaGroup(double gpa)
{
//Declare all variables
int gpaGroup;
//Assign GPA a group number
if (gpa >= 0.0 && gpa < 0.5)
gpaGroup = 1;
else if (gpa >= 0.5 && gpa < 1.0)
gpaGroup = 2;
else if (gpa >= 1.0 && gpa < 1.5)
gpaGroup = 3;
else if (gpa >= 1.5 && gpa < 2.0)
gpaGroup = 3;
else if (gpa >= 2.0 && gpa < 2.5)
gpaGroup = 4;
else if (gpa >= 2.5 && gpa < 3.0)
gpaGroup = 5;
else if (gpa >= 3.0 && gpa < 3.5)
gpaGroup = 6;
else
gpaGroup = 7;
//Return int value of group number
return gpaGroup;
}
//Method to find number of students in each group
public static void studentsInGroup(int gpaGroup)
{
//Declare all variables
int gpaGroup1 = 0;
int gpaGroup2 = 0;
int gpaGroup3 = 0;
int gpaGroup4 = 0;
int gpaGroup5 = 0;
int gpaGroup6 = 0;
int gpaGroup7 = 0;
int gpaGroup8 = 0;
//Total students in each GPA group
if (gpaGroup == 1)
gpaGroup1++;
else if (gpaGroup == 2)
gpaGroup2++;
else if (gpaGroup == 3)
gpaGroup3++;
else if (gpaGroup == 4)
gpaGroup4++;
else if (gpaGroup == 5)
gpaGroup5++;
else if (gpaGroup == 6)
gpaGroup6++;
else if (gpaGroup == 7)
gpaGroup7++;
else
gpaGroup8++;
}
Can I modify my method to return more than one variable from a method (in public static void studentsInGroup(int gpaGroup) return values of number of students in each group)? Is this where arrays start to come in? From here I would write another method to round number of students in each category to the nearest ten, then use this to write a method for creating a histogram etc etc.
I have been trying my hardest to understand the concepts, but I have been struggling lately. This is one of my last assignments for the semester and I'd like to keep my A, and also understand what I'm doing.
Can I modify my method to return more than one variable from a method (in public static void studentsInGroup(int gpaGroup) return values of number of students in each group)?
Yes, you can. You can create an object that contains two variables. However, the instructions suggest a different solution.
Inside your loop, read the id and gpa, and immediately stick them in two separate arrays.
Here is a fragment:
snums = [];
gpas = [];
while (gpadata.hasNext())
{
snum = gpadata.next();
gpa = gpadata.nextDouble();
snums.append(snum);
gpas.append(gpa);
}
ensure you are doing the following. I'm not giving away any code here. Also not sure why they want you to use array only!?!
Breakdown your requirement and see what you need to achieve.
Start with reading each line from file
each line is separated by " " and has id_number and gpa
from the requirement, the file will not contain more than 1000 students(1000 lines). You may declare this as a static class level variable static String[] idnum_array = new String[1000]; and another array for gpa which is Double[]
read each line and then separate by using String.split(" ") method. The first variable is your id number and 2nd will be your gpa. you follow ?
maintain a separate counter to increment the array position each time you set these values in the two arrays you created in step 3.
Integer i = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] splitString = line.split(" ");
idnum_array[i] = String.valueOf(splitString[0]);
gpa_array[i] = Double.valueOf(splitString[1]);
i++;
}
Do you agree that if we do idnum_array[7] to return it's corresponding gpa result from gpa_array[7] for that student ?
How you choose to count the number of people in a certain group is upto you.
I would do the following
create a static class level variable static Integer[] group_array = new Integer[]{0,0,0,0,0,0,0,0}; // there are only 8 groups!
loop my gpa_array
have an if/else inside the loop to check which group it falls in
increment the value at that index by 1. group_array[index]++;
In the end I will have an array of 8 elements which will correspond to the 8 groups. [0,200,300,200,0,300,0,0,0]
You should end up with nearly 4 methods similar to this.
1. readDataFromFile(String fileName)
2. groupGPAIntoCategory()
3. drawHistogram()
4. calculateRank()
I would personally create a Student object from the very beginning.
It's just cleaner and readable. Make sure you have your try catch block to print your exceptions and always comment!

How to fix a variable from a class not being subtracted in a method?

The gist of this assignment is that there are two players who take a stick out of a pile. I made a class that has the number of sticks available. There is a method that is called to remove sticks. However when I try to remove sticks the number of sticks doesn't change. Therefore the game not being able to end because there are still sticks "left".
I've tried using int sticks to be subtracted. The total amount of sticks changes but only in the method in which they are subtracted. The number of sticks don't change in the main method.
I decided to make use classes as I saw on this site that that is how this issue can be fixed. I've had no success with it.
So I made a class that has the amount of sticks so now the number of sticks is the same for each method. The same issue persists. One that changes the number of sticks in the getSticksRemove() method but not main() or getSticksLeft().
//Main Class
public class Main {
//Method to remove sticks which considers different scenarios.
public static int getSticksRemove(int sticks) {
sticks = StickPile.getValue(StickPile.value);
Scanner input = new Scanner(System.in);
print ("How many sticks to remove?(1-3)");
int x = input.nextInt();
if( x>=1 && x<=3) {
sticks -= x;
}else if(sticks < 3 && x ==2 ) {
print("Not enough sticks left.");
getSticksRemove(sticks);
}else if (x>3) {
sticks -=3;
}else { `enter code here`
sticks-=1;
}
print(sticks);
return sticks;
}
//Main method
public static void main(String [] args) {
StickPile stickPile = new StickPile();
int turnP1 = 0;
int turnP2 = 0;
int sticks = 0;
print("How many sticks are there initially? (1-100)");
StickPile.setValue();
sticks = StickPile.getValue(StickPile.value);
//This is the loop that determines when to stop the game
while(sticks != 0) {
System.out.print("Player 1: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP1++;
System.out.print("Player 2: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP2++;
}
if(turnP1 % 2 == 0 && turnP2 % 2 == 1) {
System.out.println("P2 Loses");
}else {
System.out.println("P1 Loses");
}
}
}
// This StickPile class is the one I made to store the number of sticks.
public class StickPile {
static Scanner input = new Scanner(System.in);
public static int value;
public static void setValue() {
value = input.nextInt();
}
public static int getValue(int x) {
x = value;
System.out.println(x);
return x;
}
I expect to enter a number of sticks to remove from the pile. Ex. PileAmount: 20--> Remove: 12--> PileAmount: 8.
However, I get Ex. PileAmoun: 20 --> Remove: 5--> PileAmount: 20,
You're ignoring the return of getSticksRemove. You can't reassign the parameter to effect the number outside of the function.
Just use the return value:
sticks = getSticksRemove(sticks)
Make that change in both places.

How to have a range of numbers in an if/else statement Java

I'm learning Java through a series of explanations and exercises, and one of them was to create a program that would display a number grade (0-5) in accordance to a number of points (0–29, 30–34, 35–39, 40–44, 45–49, 50–60).
System.out.println("Type the points [0-60]: ");
double points = reader.nextDouble();
reader.nextLine();
if (points < 29) {
System.out.println("Grade: FAILED.");
} else if (points <= 34) {
System.out.println("Grade: 1.");
} else if (points <= 39) {
System.out.println("Grade: 2.");
} else if (points <= 44) {
System.out.println("Grade: 3.");
} else if (points <= 49) {
System.out.println("Grade: 4.");
} else if (points >= 50) {
System.out.println("Grade: 5.");
}
The program works in that it'll give the correct grade because of the overlap in commands, but is there any way to create a range of numbers or strings that could meet the condition of the if/else statement? For example, if the number entered is between 40-44 and so on. Detailed answer would be appreciated since I'm new.
Divide the number by five, and make an array of twelve strings with the textual representation of the grade:
private static final String GRADE_FAILED = "FAILED";
private static final String GRADE_1 = "1";
private static final String GRADE_2 = "2";
private static final String GRADE_3 = "3";
private static final String GRADE_4 = "4";
private static final String GRADE_5 = "5";
private static String GradeStr[] = new {
GRADE_FAILED // 0..4
, GRADE_FAILED // 5..9
, GRADE_FAILED // 10..14
, GRADE_FAILED // 15..19
, GRADE_FAILED // 20..24
, GRADE_FAILED // 25..29
, GRADE_1 // 30..34
, GRADE_2 // 35..39
, GRADE_3 // 40..44
, GRADE_4 // 45..49
, GRADE_5 // 50..54
, GRADE_5 // 55..59
, GRADE_5 // 60..64 // Only sixty matters
};
System.out.println("Grade:"+GradeStr[points/5]+".");
If you need more granularity, make a bigger array, divide by a smaller number or skip the division altogether, and set the constants in the positions that correspond to the grades that need to be printed. This lets you avoid the conditionals altogether.
Important disclaimer: this approach works best when the number of options is small - up to a hundred or so. When your problem allows for this approach, it is the fastest approach by far. In many cases, it is also the easiest one to read.
You can use a NavigableMap, most commonly a TreeMap. The method used below is floorEntry. Quoting Javadoc:
Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
Note: Your code was missing an = sign on the 29 boundary, and the points value should be an integer.
Changed to use a grade (0-5), instead of the string used in question.
// Grade boundary is lower-inclusive (grade is 0-60)
TreeMap<Integer, Integer> gradeMap = new TreeMap<>();
gradeMap.put( 0, 0); // 0–29
gradeMap.put(30, 1); // 30–34
gradeMap.put(35, 2); // 35–39
gradeMap.put(40, 3); // 40–44
gradeMap.put(45, 4); // 45–49
gradeMap.put(50, 5); // 50+
System.out.println("Type the points [0-60]: ");
int points = reader.nextInt();
reader.nextLine();
int grade = gradeMap.floorEntry(points).getValue();
System.out.println("Grade: " + grade);
If you want to test if number is between some values use logical operator AND for if statements like:
if(points>=40 && points <=45)
To get more clarity I would suggest you to make a control inversion like this:
int grade;
if(points >49){
grade=5;
}else if(points >44){
grade=4;
}else if(points >39){
grade=3;
}else if(points >34){
grade=2;
}else if(points >29){
grade=1;
}else{
grade=0;
}
System.out.println("Gr: "+grade); //grade=0 = not passed
I think you might be looking for
if( points<=44 && points>=40 )
If you want to check if a number is between two values, you would use an and in your if statement:
if (points >= 40 && points <= 44) {
System.out.println("Grade: 3.");
}
If you want to check for a range within an if statement, you can do this:
if(points >= 0 && points <= 29)
This is by using && (and) operator by combining conditions together.
But you don't really need to check for a range in any of the if-statements.
Doing what you currently have will be suffice.

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