Java out of scope - java

My program is nearly done except for one problem. I'm having an out of scope problem with the for loop. The goal of the program is to compound monthly interest for a user inputted amount & term.
An example of output at $5000 principal with 5% interest for 3 years would be:
Month: Interest: Principal:
1 $20.83 $5020.83
2 $20.92 $5041.75
etc etc etc
Starting Balance = $ 5000.00 // having problem outputting these w/ for-loop
Final Account Balance = $ 5807.36 // System.out.print keeps repeating multiple times
Total Interest Paid = $ 807.36 // but i can't use variables outside of loop
My problem is that during my for loop, I keep outputting Starting Balance, Final Balance and Total Interest every time the program goes through the loop. but if I try to use the variables outside the loop it goes out of scope and if I try to declare variables outside of the loop I can't use them inside the loop because it's already been declared in the constructor.
Can anyone give me some hints or advice?
My code:
public class Calculator
{
public Calculator()
{
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error){
System.out.print("Please input the following: principal, interest rate, term >> ");
double principal = input.nextDouble();
double interest_rate = input.nextDouble();
int term = input.nextInt();
String Month = input.next();
char dollar_sym = 36;
if (interest_rate <= 0 || term <= 0 || principal <= 0) // input validation
{
System.out.println("The term, interest rate and principal must be greater
than zero");
continue;
}
if (!Month.equals("month")) // input validation
{
System.out.println("Please input month after term");
continue;
}
System.out.println("Month: " + " Interest: " + "Principal: ");
if (Month.equals("month"))
{
for (int month = 1; month <= term; month++)
{
double interest = (principal * interest_rate / 100) / 12;
principal = principal + interest;
System.out.printf("%4d %c%5.2f %c%5.2f\n", month,
dollar_sym, interest, dollar_sym, principal );
double start_principal = principal - interest; // problem
double final_principal = principal; // problem
double total_interest = interest * interest_rate; // problem
System.out.println(" Starting balance = " + start_principal ); // problem
System.out.println("Final account balance = " + final_principal ); // problem
System.out.println("Total Interest Paid = " + total_interest); // problem
}
}
}
}
}

Declare them before the loop begins, so they will exist inside the loop and after it:
double start_principal = 0;
double final_principal = 0;
double total_interest = 0;
Scanner input = new Scanner(System.in);
boolean error = false;
while (!error) {
// ...
}
// ...

In my answer, I am assuming that when you say goes out of scope, you mean that you get a compile time error. (note, it would make the answer easier to address if you provided the error message and the line that is causing the error message).
The scope of a variable refers to where the variable is accessible. For example, if you declare a variable inside of an if statement, the scope is that if statement. Some example code:
public void updateStatus(){
Boolean shouldCheckStatus = true;//this variable is declared inside of the updateStatus method, so that is the scope of the variable
if(shouldCheckStatus == true){
Int hitCounter = 0;//this variable is declared inside of the if statement, so it is only accessible inside of the if statement
//do some work
if(hitCounter > 100){
self.registerHits(hitCounter);//hitCounter is still accessible here, because it is still inside of the if statement
}
else{
shouldCheckStatus = false;
}
}//close the if statement and so close the scope...
//the hitCounter variable is no longer in scope, because we are no longer in the if statement
//but shouldCheckStatus is still in scope, because we are still in the method
if(shouldCheckStatus == true){
self.callAnotherMethod();
}
}
So in your problem, you need to declare your variable above where you want to use it, inside of the scope that you want to use it. And then not declare it again. So declare before the loop.

Related

validation, the users input must equal to his/her account number and pin, is this the correct way? i seem to just be getting errors

This part of code is not in a function as I am declaring all values before they can get used by future functions.
Here is a snippet that I'm struggling with
validate if user input is correct
if (userinput.equals(x.indexOf("1234")) && userinput.equals(pinA.indexOf("1223")) ){
{System.out.println(x);
int bal = 500;
System.out.println("your balance is: " + bal);
MainMenu();
}
// that if statement is giving me errors
//here is my variable declaration
public class SimpleBankingApp {
//declare the pins
String pinA = "1223";
int pinB = 1227;
int pinC = 7643;
int pinD = 8554;
// have the users details in strings
public String x = "1234 500";
public String b = "3546 50000";
public String d = "4253 6000";
public String t = "7722 804";
//get user input from user
static {System.out.println("enter your choice");}
Scanner a = new Scanner(System.in);
String userinput = a.nextLine();
if (userinput.equals(x.indexOf("1234")) && userinput.equals(pinA.indexOf("1223")) ){
{System.out.println(x);
int bal = 500;
System.out.println("your balance is: " + bal);
MainMenu();
}
By the declaration of the pins, I tested to see if a string variable would work hence why one of them is a string
You don't need to use indexOf() here. Just use equals like this userinput.equals(pinA), also use "or"(||) instead of "and"(&&) in your if condition or use 2 user inputs if you want to compare 2 separate fields, because 1 field can't be equals to 2 different strings

Eclipse, The local variable cannot be initialized

Ive been working on this program for a few days now and its due tonight at midnight. I cannot for the life of me figure out why I keep getting a " The local variable cannot be initialized" error. This is my first coding class and I do not understand it very well. If someone could help me out by explaining a fix and why this error keeps happening that would be great.
I have put "**" where the errors are ( near the end of the code). Any help would be great! Thanks in advance.
/*This program will determine how much the students
tuition and fees are based on location and classes. It will return the
total tuition, fees, and combined total */
import java.text.DecimalFormat;
import java.util.*;
public class Project2 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//Declaring variables and decimal format
int TotalHours;
int Price;
int CreditCharge;
int CITFee;
int OnlineFee;
int INFCSCFee;
int TotalTuition;
int TotalFee;
int TotalCombined;
DecimalFormat df = new DecimalFormat("$#,###");
//Getting the students First name, Last name, and Date
System.out.print("Enter your first name: ");
String FirstName = in.nextLine();
System.out.print("Enter your last name: ");
String LastName = in.nextLine();
Date d = new Date ( );
//Getting the state of residency. If in Ohio, asking the user if they are Metro
System.out.print("Enter your State of residency as a 2-letter abbreviation: ");
String State = (in.next().toLowerCase());
if (State.equals ("oh") || State.equals("OH")){
System.out.print( "Are you a Cincinnati resident? (Y/N) ");
String Metro = in.next();
if (Metro.equals ("y")) Price = 567;
}
else Price = 750;
if (State.equals ("ky") ){ Price = 375;
}
else if (State.equals ("in")){Price = 375;
}
else {Price = 750;
}
//Getting the number of credit hours the student is taking
System.out.print("Enter the total credit hours for the upcoming semester: ");
TotalHours = in.nextInt();
if (TotalHours <= 12) CreditCharge = (TotalHours * Price);
else {CreditCharge = (Price * 12);
}
//Getting the number of CIT hours the student is taken
System.out.print("Enter the total of CIT credits you are taking: ");
int TotalCITHours = (int) in.nextInt();
CITFee = (TotalCITHours * 40);
//Getting the number of online credit hours the student is taken
System.out.print("Enter the total number on-line credit hours you are taking: ");
int OnLine = (int) in.nextInt();
OnlineFee = (OnLine * CITFee * 35);
//Seeing if the student is taken either INF 120 or CSC 260
System.out.print("Are you taking either INF 120 or CSC 260? (Y/N) ");
String INFCSC = in.next().toLowerCase();
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
//Calculating the tuition, fees, and total combined.
** TotalTuition = CreditCharge;
** TotalFee = INFCSCFee;
** TotalCombined = TotalTuition + INFCSCFee;
//Tuition Statement for FirstName, LastName, Date
System.out.println("\nTuition Statement for " + FirstName + LastName);
System.out.println(d);
System.out.println("Tuition: " + df.format (TotalTuition) );
System.out.println("Fees: " + df.format(TotalFee));
System.out.println("Total: " + df.format(TotalCombined));
}
}
Your variable INFCSCFee was not initialized if they did not answer yes to the question "Are you taking either INF 120 or CSC 260? (Y/N) ". Eclipse will not let you run the program if a variable may not have been initialized. At the top of your code where you have
int INFCSCFee;
replace it with
int INFCSCFee = 0;
or initialize the variable somewhere else or with some other value.
Here is the fault
if (INFCSC.equals ("y")) INFCSCFee = (char) (CITFee * OnlineFee + 60);
This is the only place INFCSCFee can be initialised. So it is possible therefore that it has not been initialised by the time it is used. More generally, this is not allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3; // initialise to 3
// if somecondition was false, x is still unitialised
System.out.println("x is "+x); // Error
You cannot use a variable declared in a method unless the compiler can gaurantee it has been initialised beore you us it. This would be allowed:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else if (somethingElse)
x = 4;
else
x = 5;
// For all outcomes, x has been initalised, so it is safe to use
System.out.println("x is "+x);
This is allowed too:
int x; // declare x - not yet initialised
if (someCondition)
x = 3;
else
return;
// Although someCondition may have been false, if we reach this line of
// code, it is because someCondition was true and therefore x was initialised
System.out.println("x is "+x); // will print x is 3
Finally, you can initalise your variable at declaration time:
int x = 0;
Now, wherever x is used, it is gauranteed to be initalised, so you won't get a compile error. That's not necessarily a good thing, because that compiler error could actually be showing you a bug in your code, and you've suppressed it by giving the variable a default value.

confusion about while loop

I'm just starting to learn my first programming language as of yesterday, so I'm writing simple test programs from my java book.
What I'm attempting to do is to have a user enter a static monthly investment and how many months they will be saving for, then display their total savings after that period of time.
when I compile the program it says that in system.out.println at the end of the program that total has not been initialized. I have tried initializing total in just the loop but I figured that would put the scope of it in the loop So I tried initializing it at the top and figured it runs through the loop until the condition is met but doesn't go back to the top of the program to put the value back in so I make another variable at the end of the loop to hold the total at the end of the loop. What's Wrong with my logic
thank you for the help!
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 0){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}
thanks everyone for the help it now compiles however it seems when going through the math it doesn't take in account the first month of savings for example if I do $100 each month its total at the end is %502.08 which I don't believe is right
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount = 0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown > 1){
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
monthCountDown = monthCountDown - 1;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
set totalAmount = 0,that will instialize it, let me know if this fixes the problem
when you declare it declare it like this double totalAmount = 0;
try 2 steps:
double totalAmount; ==> double totalAmount = 0;
while (monthCountDown > 0); ==> while (monthCountDown-- > 0);
Hava a nice day, my friend.
This problem is a little intricate although the compiler (javac program) provides following helpful message:
Compound.java:33: error: variable totalAmount might not have been
initialized double total = totalAmount;
What could be happening you may wonder. The easy answer is to go to line 20 in your program and initialize the value of totalAmount to 0. Then your program would compile.
The reason the compiler does that is rather complicated, but you can reason about it this way:
What if, just what if the while loop did not get run even once (as written, in your program, opposite is happening as you will soon figure out that you are forgetting something about the loop variable)? Then Java would execute the (next) statement double total = totalAmount; and the way this assignment statement is executed is roughly like this:
read the variable on the right side of =, that is totalAmount in a temporary location
transfer the contents of that location to the memory for the variable on the left side of =, i.e. total.
Now, Java does not like to read a local variable's (such as totalAmount) value that is never written to because it may contain some garbage value. When you initialize it with a value like 0, this problem goes away.
First of all there is no need of using intitalAmount and totalAmount. Because each time you are inserting same values to them. Secondly if you make
monthCountdown > 1
then it will count a month less. Because suppose you are counting for 6 months. Now for monthCountdown > 1 the loop will iterate for 5 times and calculate interest for 5 times. Which I believe is not the logic you want to implement.
So it should be,
monthCountdown > 0
Lastly your mathematical logic is not correct because each time you are calculating the interest on the monthly value and adding it with the previous balance. But it should be like each time interest should be calculated on the total current balance.
while (monthCountDown > 0){
totalAmount = ( amountSavedMonthly + totalAmount ) * monthlyInterestRate;
}
Please let me know if any concern.
First of all, it isn't necessarily the case that totalAmount will not be initialized. However, depending on the user input, it is POSSIBLE that totalAmount will not have been initialized, which will then throw an exception when the program attempts to assign the value of totalAmount to total. To avoid this, you need to ensure that totalAmount gets initialized, which is easy to do. When you declare totalAmount, simply assign 0 as its value.
You also have a problem with your while loop. Because the value of monthCountDown is never changed within the loop, there is no way for the condition monthCountDown > 0 to become false. I'm assuming you intended for monthCountDown to be reduced by 1 each time the loop is run, so you should include monthCountDown--; within the loop to prevent it from becoming an infinite loop.
Initialize totalAmount to 0...
Make in while condition greater than 1..
cricket-007 is right about initializing totalamount = 0; But it looks like your while loop keeps going. Try this!
changed your arrow key from > to <, on the while loop
import java.util.Scanner;
public class CompoundInterestSteadyRate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double monthlyInterestRate = (1 + 0.00417);
System.out.println("please enter amount saved each mounth");
double amountSavedMonthly = input.nextDouble();
System.out.println("please enter amount of months you will be saving for");
int amountOfMonthsSaved = input.nextInt();
int monthCountDown = amountOfMonthsSaved;
double totalAmount =0;
double addMonths;
double intitalAmount = 0;
while (monthCountDown < 0) {
addMonths = amountSavedMonthly * monthlyInterestRate + intitalAmount;
intitalAmount = addMonths;
totalAmount = intitalAmount;
}
double total = totalAmount;
System.out.println("your total after " + " " + amountOfMonthsSaved + " " + "months is:" + " " + "$" + total);
}
}

Getting java.lang.NullPointerException whenever I run my code [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
To practice my basic programming skills over the summer I decided to write a 1dimensional motion physics problem solver. I am getting a java.lang.Nullpointerexception error whenever I try to run the program. I can't figure out what I've written incorrectly to give me the error. NOTE: Right now I am assuming the input for the solveFor variable will be "acceleration" for the sake of fixing this error:
import java.util.Scanner;
public class PhysicsProblem
{
private double vI; // initial velocity
private double vF; // final velocity
private double t; // time
private double deltaX; // change in the x value
private double accel;
private String missingVar;
public PhysicsProblem (double acceleration, double initialV, double finalV, double time, double changePosition)
{
acceleration = accel;
initialV = vI;
finalV = vF;
time = t;
changePosition = deltaX;
}
Scanner scan = new Scanner(System.in);
public void getUnknownsAccel()
{
//-----------
// checks for another unknown value that is not accel
//-----------
if (missingVar.equalsIgnoreCase("time"))
{
System.out.println("Please enter the value for time: ");
t = scan.nextDouble();
while (t <= 0 || !scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
t = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("initial velocity"))
{
System.out.println("Please enter the value for initial velocity: ");
vI = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
vI = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("final velocity"))
{
System.out.println("Please enter the value for final velocity: ");
vF = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
vF = scan.nextDouble();
}
}
if (missingVar.equalsIgnoreCase("delta X"))
{
System.out.println("Please enter the value for delta X: ");
deltaX = scan.nextDouble();
while (!scan.hasNextDouble())
{
System.out.println("That is not an acceptable value!");
deltaX = scan.nextDouble();
}
}
}
This is the class file for the program. I'm getting an error in the line 36:
"if (missingVar.equalsIgnoreCase("time"))"
As well as getting an error in line 40 of the main program body:
"problem1.getUnknownsAccel();"
public static void main (String[] args)
{
String missingVar; // other missing variable
double vI = 0;
double vF = 0;
double t = 0;
double deltaX = 0;
double accel = 0;
Scanner scan = new Scanner(System.in);
PhysicsProblem problem1 = new PhysicsProblem (accel, vI, vF, t, deltaX);
System.out.println("Which variable are you solving for? ");
String solveFor = scan.nextLine();
// after receiving solveFor input, assesses data accordingly
if (solveFor.equalsIgnoreCase("acceleration"))
{
System.out.println("Solving for Acceleration!");
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.nextLine();
do
{
problem1.getUnknownsAccel();
System.out.println("Are there any other unknowns? (enter 'none' or the name " +
"of the variable)");
missingVar = scan.nextLine();
}
while (!missingVar.equalsIgnoreCase("none") || !missingVar.equalsIgnoreCase("acceleration"));
if (missingVar == "none");
{
// Write code for finding solutions
System.out.println("Assuming you have given correct values, the solution is: ");
}
}
Why is it throwing an exception?
missingVar is obviously null. Look back in the code to find out why. And doing this, ask yourself where do you ever give the variable a String in the PhysicsProblem class?
Answer: you don't!
Note that two variables with the same name declared in different scopes are not the same variable. Just because your two classes have a missingVar String variable does not mean that they share the same variable, and as you're finding out, they in fact don't. The solution: set the missingVar variable in the PhysicsProblem class before trying to use it. Give the class a setter method for this.
i.e.,
public void setMissingVar(String missingVar) {
this.missingVar = missingVar;
}
And then call the method before using the variable.
You never initialize missingVar to anything, so it's null. You need to assign it something so it's not null.
Incidentally, you can switch the order in your call to avoid a NullPointerException here:
while (!"none".equalsIgnoreCase(missingVar) ||
!"accelmissingVar".equalsIgnoreCase(missingVar));
Also, on this line
if (missingVar == "none");
Remove the semicolon, because that semicolon is interpreted to be the body of the if block, causing your actual block below to not be associated with if (it would then always be executed, regardless of the condition in your if).
Don't compare string values with ==, which compares two objects references to see if they refer to the same object. Use the equals method:
if ("none".equals(missingVar))

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