Help... While Loop

Help I can't seem to get the loop to function. I need to have the program to ask the user if they want to reuse the calculator and if yes the user input and calculation function will refresh and start over. If no then it should prompt to close. The following is my code which functions fine without the loop.
// Import Java packages
     import java.text.NumberFormat;
     import java.util.Locale;
     import java.text.DecimalFormat;
     import java.util.Date;
     import java.io.*;
     import static java.lang.Math.*;
     public class Mortgage /* Begin program*/
          public static void main (String [] args) throws IOException     /* Create a class instance*/
               //Variables
               String StrPrincpal;          //holds user input for calculation
               String StrIntRate;
               String StrTerm;
               String StrResponse;
               double principal = 0;      // amount to be financed
               double IntRate = 0;          // rate of interest to repay the loan
               double pymt;               // returns the payment amount
               double rate, Calpymt;     // holds calculated values
               int term = 0;               // length of loan in years
               char option;               // holds users text responses (yes or no)
               Date currentDate = new Date();      // Date constructor
               NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);  // create US dollar print out format
               DecimalFormat twoDigits = new DecimalFormat("$0.00");  // formats decimal to 2 place
               BufferedReader dataIn= new BufferedReader(new InputStreamReader(System.in)); //using for numerical data
               BufferedReader myIn= new BufferedReader(new InputStreamReader(System.in)); //using for text/string char
               //Prompt for user input
               System.out.println("Mortgage Calculator");
               System.out.println("Date Created: May 28, 2007");
               System.out.println("Version: 2.0\n");
               System.out.println("This program will determine the monthly mortgage payment.\n");
               //While statement to prompt user to continue to use calculator or to quit.
               while ((option == 'Y') || (option == 'y'))
               {  //begin loop
                    System.out.print("Enter the amount to be financed: $");
                    StrPrincpal = dataIn.readLine (); //Places data into the string StrPrincpal
                    principal = Double.parseDouble (StrPrincpal);
                    System.out.println();
                    System.out.print("Enter the rate: ");
                    StrIntRate = dataIn.readLine (); //Places data into the string StrPrincpal
                    IntRate = Double.parseDouble (StrIntRate);
                    System.out.println();
                    System.out.print("Enter the term of the loan: ");
                    StrTerm = dataIn.readLine (); //Places data into the string StrPrincpal
                    term = Integer.parseInt (StrTerm);
                    System.out.println();
                    //Calculation
                    rate = (IntRate / 100.0) / 12.0;     // converts % to decimal format
                    Calpymt = rate + 1;                         // calculate interest
                    term = 30*12;                              // calculate number of years to number of months
                    pymt = principal * (Math.pow(Calpymt, term) * rate)/ (Math.pow (Calpymt, term) -1);      // formula to calculate monthly payment
                    System.out.println("\nMonthly payment will be: " + moneyFormat.format(pymt) + "\n");  // outputs monthly payment to screen
                    System.out.println("Date of report:" + currentDate);
                   System.out.println("\n");  // create a blank line after output
                   //User response required y or n to refresh the calculator to perform another calculation
                    System.out.println("Do you wish to calculate another mortgage?\n");
                    System.out.print("Please Enter Y or N:\t");
                    System.out.println("\n");
                    //option = (char) System.in.read();
                         StrResponse = dataIn.readLine();
                         option = Character.parseChar(StrResponse);
                         //}  //close while loop
               } //close loop
     }//End method
}     //End ProgramError message: "G:\UOP\POS 406\Java Assignements\Week 3, Assignment 2\MortgageCalcV1.java:91: cannot find symbol
symbol : method parseChar(java.lang.String)
location: class java.lang.Character
                         option = Character.parseChar(StrResponse);
                         ^
1 error
Tool completed with exit code 1"
I have no doubt I'm over looking something very simple. If you respond please just don't give me the correction please include what I'm missing or doing wrong.
Thanks,

Hi,
I'm not sure what your exact problem is, it may have something to do with that extra new line character at the end, but that not withstanding, I would do a few things differently.
1) I would import and utilize the Scanner class, instead of the bufferred reader
2) I would use strings, and not chars as input from the user, and thus be able to test for "yes" using the StringObj.equalsIgnoreCase("yes"); method, which cuts down on havig to test for "yes", "YES", YeS", etc.
Here is your code, doing what I believe you expected it would, with the import of the Scanner class (I would swap out all instances of your buffered reader for the scanner class):
// Import Java packages
import java.text.NumberFormat;
import java.util.Locale;
import java.text.DecimalFormat;
import java.util.Date;
import java.io.*;
import java.util.Scanner;
import static java.lang.Math.*;
public class Mortgage /* Begin program*/
     public static void main (String [] args) throws IOException     /* Create a class instance*/
          //Variables
          String StrPrincpal;          //holds user input for calculation
          String StrIntRate;
          String StrTerm;
          String StrResponse;
          double principal = 0;      // amount to be financed
          double IntRate = 0;          // rate of interest to repay the loan
          double pymt;               // returns the payment amount
          double rate, Calpymt;     // holds calculated values
          int term = 0;               // length of loan in years
          String option = "yes";               // holds users text responses (yes or no)
          Date currentDate = new Date();      // Date constructor
          NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);  // create US dollar print out format
          DecimalFormat twoDigits = new DecimalFormat("$0.00");  // formats decimal to 2 place
          BufferedReader dataIn= new BufferedReader(new InputStreamReader(System.in)); //using for numerical data
          BufferedReader myIn= new BufferedReader(new InputStreamReader(System.in)); //using for text/string char
          //Prompt for user input
          System.out.println("Mortgage Calculator");
          System.out.println("Date Created: May 28, 2007");
          System.out.println("Version: 2.0\n");
          System.out.println("This program will determine the monthly mortgage payment.\n");
          //While statement to prompt user to continue to use calculator or to quit.
          while (option.equalsIgnoreCase("yes"))
               {  //begin loop
               System.out.print("Enter the amount to be financed: $");
               StrPrincpal = dataIn.readLine (); //Places data into the string StrPrincpal
               principal = Double.parseDouble (StrPrincpal);
               System.out.println();
               System.out.print("Enter the rate: ");
               StrIntRate = dataIn.readLine (); //Places data into the string StrPrincpal
               IntRate = Double.parseDouble (StrIntRate);
               System.out.println();
               System.out.print("Enter the term of the loan: ");
               StrTerm = dataIn.readLine (); //Places data into the string StrPrincpal
               term = Integer.parseInt (StrTerm);
               System.out.println();
               //Calculation
               rate = (IntRate / 100.0) / 12.0;     // converts % to decimal format
               Calpymt = rate + 1;                         // calculate interest
               term = 30*12;                              // calculate number of years to number of months
               pymt = principal * (Math.pow(Calpymt, term) * rate)/ (Math.pow (Calpymt, term) -1);      // formula to calculate monthly payment
               System.out.println("\nMonthly payment will be: " + moneyFormat.format(pymt) + "\n");  // outputs monthly payment to screen
               System.out.println("Date of report:" + currentDate);
               System.out.println("\n");  // create a blank line after output
               //User response required y or n to refresh the calculator to perform another calculation
               System.out.println("Do you wish to calculate another mortgage?\n");
               System.out.print("Please Enter 'yes' to continue:");
               Scanner keyboard = new Scanner(System.in);
               option = keyboard.next();
               } //close loop
     }//End method
}

Similar Messages

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • Need help on a while loop

    Hi...I am somewhat new to Java and I am trying to do a nested while loop. Basically I have a result set from a query and I want to loop though that result set BUT I need a second loop to put together 150 of the results at a time and add them to a GeoCodeRequest to send to MapInfo.....this is how I think the code should look, I need some advice if it is the proper way to loop through....
    ArrayList aal = new ArrayList();
    ServiceMessage sm = new ServiceMessage();
    ServiceMessage rsm = new ServiceMessage();
    while (rset.next())
    statRecord = statRecord + currentRecord;
    while (rset.next() && currentRecord <= 150)
    AddressEx a = new AddressEx(rset.getString(6));
    ContentColumn cc = new ContentColumn("mmhid");
    cc.setValue(rset.getString(1));
    StreetAddress streetAddress = new StreetAddress(rset.getString(3));
    streetAddress.setBuildingName(rset.getString(2));
    a.setCountrySubdivision(rset.getString(5));
    a.setMunicipality(rset.getString(4));
    a.setPostalCode(rset.getString(6));
    a.setContentColumn(0,cc);
    aal.add(a);
    currentRecord++;
    System.out.println("Inside inner while loop now..");
    System.out.println("Add 150 to request...");
    GeocodeRequestEx gr = new GeocodeRequestEx("","3.0","id",(AddressEx[])aal.toArray());
    gr.setGeocodePreference(pref);
    sm.addRequest(gr);
    System.out.println("going to geocode now...");
    try{
    LocationUtilityServiceLocator lus = new LocationUtilityServiceLocator();
    LocationUtility lu = lus.getLocationUtility(new URL(url));
    XLSType xr = lu.perform(sm.toXLS());
    rsm = new ServiceMessage(xr);......
    code goes on to do oter things but this is the basis..............
    I hope that all made since.....please help.

    I am not sure if there is a problem, that is what I am
    asking......if I have the logic correct.
    I haven't been able to test it correct because I am
    getting an:
    Exception in thread "main"
    java.lang.ClassCastException: [Ljava.lang.Object; at
    geoClient.main(geoClient.java:127)
    That means you don't have it correct.  :-)> on the following line:> > GeocodeRequestEx gr = new> GeocodeRequestEx("","3.0","id",(AddressEx[)aal.toArray
    and I haven't figured out to correct that yet......You need to use toArray(Object[]).

  • Help with a while loop condition

    I'm trying to write to a File. I ask the user for input, then I enter a while loop and test the condition. The loop works, but it won't stop. I've tried everything. Here is my code please help!!
    thanks
    inputline = keyboard.readLine();//read the keyboard
    try{
    while( inputline != null ){
    DiskOut.println( inputline );
    DiskOut.flush();
    inputline = keyboard.readLine();//read the keyboard again
    }//end while
    }//end try
    catch (IOException e) { 
    e.printStackTrace();
    }//end catch
    also i've tried these while loop conditions:
    while(inputline != "\n" || inputline != "\r") and the sort

    while(inputline != "\n" || inputline != "\r")The condition
    X!=Y OR X!=Z (given Y != Z)
    is always true. X will always not be equal to at least one of the values. So you'll want to use:
    while(!inputline.equals("\n") && !inputline.equals("\r"))In other words, "while inputline is not equal to either of them". Note the use of && instead of ||.
    If "keyboard" is simply a BufferedReader on top of System.in (and not your own class), the trailing line feeds and carriage returns won't even be in the string returned by readLine(). Your best bet is this:
    while(null != inputline && 0 != inputline.length())Make sure you type the two parts of that AND condition in the order above. If for whatever reason there are trailing \r and \n on the strings, you'll want to accomodate for platforms that may include both characters.
    // trim the trailing newline characters
    while(inputline.endsWith("\r") ||
          inputline.endsWith("\n")) {
       inputline = inputline.substring(0,inputline.length()-1);
    // or maybe this will work if you don't mind losing
    //  the whitespace at the beginning of the string:
    inputline = inputline.trim();Hope that helps somewhat.

  • Need help w/ for loop, a do loop, and a do-while loop.

    Hello I have been trying to write a program that uses a for, do, and a do-while loop, but I am having trouble. I need the program that will prompt the user to enter two numbers. The first number must be less than the second number. I need to use a "for loop", a "do loop", and a "do-while loop" to display the odd numbers between the first number and the second number. For example, if the user entered 1 and 8, the program would display 3,5,7 three different times (one for each of the loops). Please help if you can. Thanks.

    boolean2009 wrote:
    Thank all of you all for responding.Youre welcome.
    Yes this is my homework, but my major does not even involve java i just have to take the class.Not our problem.
    And yes we are suppose to have all three in one program I do not know why,So you can learn all three types of loops (there is also an enhanced for loop to learn later on).
    but I just do not understand programming nor do i really want to.Once again not our problem.
    If anybody could help it would be much appreciated. thanks.Yes, a lot of people are willing to help you. No, none of them will do it for you. What you need to do is attempt the code and when you get stuck, post your code using the code button, include error messages, indicate which lines in your code genereate those error messages and ask specific questions.

  • Need help with while loops

    Hello let me first explain what im trying to achive:
    I want a moving square that you control with the arrow keys on the keyboard. It has to be smooth ie able to move fast without looking like its jumping and it has to be able to move diagonaly aswell. Think of that arcade game Raiden ...you know the birds-eye view plane flying game...another thing! I'd prefer if it didnt use timers - i made one already using 4 timers and it works great but 4 timers is a little extreme - SO NO TIMERS !
    I was thinking while loops, but i cant seem to get it working. I dont want to put in all the code so ill just say that I have 4 booleans: up, down, left right and the following code:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    up = true;
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    down = true;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    left = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    right = true;
    repaint();
    For the KeyReleased part i have the same as above exept it sets the booleans to false.
    Soooo in theory if i set up a while loop like this (using the up direction as an example) :
    while (up == true) {
    [move square up]
    So therefore when i press and hold the up arrow the loop will keep going untill i realease it right? WRONG ! it just keeps repeating indefinatly and it doesnt even do the " [move square up] " bit. I put a System.out.print in the loop to test and it kept printing out the message but it still didnt do the actual " [move square up] " bit.
    Im not sure if im putting the while loop in the right place either....If anyone has any idea on how to use while loops in this way please heeeelp ! Its so annoying because it just doesnt work ive tried so many ways...
    any help would be greatly apreciated !!!!

    Maybe you want something like this? You have to pause during the loop to allow for other events to happen, like if y ou release a key or whatever.
    while( true )
       if( up ) moveUp();
       else if( down ) moveDown();
       if( left ) moveLeft();
       else if( right ) moveRight();
       try
          Thread.currentThread().sleep(10);
       catch( InterruptedException e )
          System.out.println( "Thread interrupted!");
    }

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

  • Help with while loop program

    I am working on this program that when inputing two integers: firstNum and secondNum, the program will output all odd numbers between firstNum and secondNum.
    This program will be using a while loop and I can't find any similar examples in my book on how to write the code.
    any help would be greatly appreciated

    you asked for it...
    //This program will prompt the user to input two integers.
    //Output all odd numbers between firstnum and secondnum.
    //Output the sum of all even numbers between firstnum and secondnum.
    //Ouput the numbers and their square between 1 and 10.
    //Output the sum of the square of odd numbers between firstnum and secondnum.
    //Output all uppercase letters.
    import java.io.*;
    public class Program8
              static BufferedReader keyboard = new
                        BufferedReader(new InputStreamReader(System.in));
              public static void main(String[] args) throws IOException
              //Declare all variables
              int firstNum;
              int secondNum;
              System.out.print("Input first Integer: ");
              firstNum = Integer.parseInt(keyboard.readLine());
              System.out.println();
              System.out.print("Input second Integer: ");
              secondNum = Integer.parseInt(keyboard.readLine());
              System.out.println();
    As you can see, I don't have a clue where to begin after this...

  • Need help with while loop and shift registers

    I have a large data set and need to read in the data at maybe 200 samples at a time, process these samples through my VI, and have it append and concatenate a separate lvm file.  The part where I am confused is the shift registers. How do I limit the number of samples read in an iteration? How do I get the while loop to stop when all the data are read in?
    I've attached my diagram, maybe there is something wrong with my technique?
    Solved!
    Go to Solution.
    Attachments:
    shiftreg.JPG ‏56 KB

    This will give you an idea.  There are plenty of other (probably more efficient) methods.  This is a basic, quick and dirty solution to help you grasp the overall concept.
    Using LabVIEW: 7.1.1, 8.5.1 & 2013
    Attachments:
    ShiftRegLoop.JPG ‏54 KB

  • Help learning while/do while loops

    Hi everyone, glad to see there are resources out here like this where newbies with Java can get help and learn from the gurues!
    I am having a problem with constructing a while loop that is going to compute the sinx without using the Math.sin function....so given this
    sinx = x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ......
    It seems I need to use the Math.pow function. So the sinx is alternating signs between each new set of parenthesis and the power and factorial are increasing by 2..starting with 3. I think this is were I am having my trouble.
    I was going to use a do-while loop for cosx which is
    cosx = x - (x^2/2!) + (x^4/4!) - (x^6/6!) + ......
    I think my problem is that I can't figure out how I would go about writing this. If I can get the sinx with the while loop, I can probably get the cos on a do-while statement since they are similar. I did get factorial(n) defined below.
    I have another main class which I am using to get the input of sin/cos x using computeSin and computeCos functions I am trying to build here.
    import javax.swing.*;
    public class NewMath
    public static double computeSin(double x)
    double result = x;
              // Going to use A WHILE LOOP
    return result;
         public static double computeCos(double x)
    double result = 1;
              // Going to use a DO-WHILE loop
    return result;
    private double factorial(int x) {
    if (x <= 1) return 1.0;
    else return x * factorial(x - 1);
    Any tibits of help would be nice. If I think I got it working before someone else posts, I'll post my results. Thanks.

    Any tibits of help would be nice. If I think I got
    it working before someone else posts, I'll post my
    results. Thanks.You already have your own tidbits, as you've observed the pattern of alternating adding/subtracting, as well as how the power and factorial factors relate. Any more "tidbits" here would just result in doing it for you, it seems. So get to it, and if you run into specific problems, you can ask.

  • Help with while loops

    Im trying to create a while loop that outputs the revers of a string, eg nice one
    would be "eno ecin" Assuming i already have declared a variable intital string that holds the string, how do i go about this does anyone have any problem solving techniques. The charAt method needs to be used.

    i have a exam on saturday and it was a previous exam question that im trying to get help with i need to understand the course material thanks, i know how to use while loops but have trouble getting my head around this question. ill show you my code however i know its completely wrong.
    now i know i hvae to use the charAt method to return a character located at the integer i
    so i must go down after each case has been tested true therefore i want i=i-1;
    until i=0;
    String initialString="tucan";
    int i=initialString.length();
    while(i>0)
         return charAt();
         i=i-1;
         }

  • FUNCTION Cursor / WHILE LOOP vs LOOP / Logic help (RESOLVED)

    (I HAVE RESOLVED - making it more efficient, I hope - see FUNCTION) if anyone has a different =, more efficient way to write this, please share...
    I need help with a Function:
    I am trying to get a handle on a rate. This table has and employee column this is usually populated with 'ALL'. On the off chance that it has an actual employee number, I want that rate; otherwise, the rate with ALL. Everything in both records will be the same except the employee field. (if there happens to be an ALL rate and an individual employee rate. Usually there will only be one record).
    As I started to write this, I tested the WHILE loop logic and did not get a value back, but when I test a simple loop, I do. I have not finished the entire logic only getting a handle on a record that has the employee.
    I would like help:
    Understanding why WHILE loop isn't working
    How to go about testing if CURSOR c_job_payroll_rate_emp FOUND - get this value and EXIT otherwise IF NOT FOUND then get value from c_job_payroll_rate_all
    Start to my function is below w/ testing comments(** THIS IS THE RESOLVED FUNCTION.
    FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
                        in_job_code IN jobpayrate.jpr_job_code%TYPE,
                             in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
                                  in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
                                  in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
                                  in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
    RETURN jobpayrate.jpr_billing_rate%TYPE
    IS
    v_val jobpayrate.jpr_billing_rate%TYPE;
    CURSOR c_job_payroll_rate_all IS     
         SELECT max(jpr_billing_rate) rate
         FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
         AND jpr_job_code = in_job_code
         AND jpr_trd_code = in_trd_code      
         AND jpr_phs_code = in_phs_code
         AND jpr_cat_code = in_cat_code
         AND jpr_emp_no <> in_emp_code;     
    CURSOR c_job_payroll_rate_emp IS     
         SELECT max(jpr_billing_rate) rate
         FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
         AND jpr_job_code = in_job_code
         AND jpr_trd_code = in_trd_code
         AND jpr_phs_code = in_phs_code
         AND jpr_cat_code = in_cat_code
         AND jpr_emp_no = in_emp_code;     
    BEGIN
    FOR rec_e IN c_job_payroll_rate_emp LOOP
    v_val := rec_e.rate;
    IF rec_e.rate IS NULL THEN
    FOR rec_a IN c_job_payroll_rate_all LOOP
    v_val := rec_a.rate;
    END LOOP;
    END IF;
    END LOOP;
    RETURN v_val;
    END job_pay_rate;
    Message was edited by:
    KB

    Rather than using cursors for zero or 1 row queries, use SELECT ... INTO
    Untested
    FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
    in_job_code IN jobpayrate.jpr_job_code%TYPE,
    in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
    in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
    in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
    in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
    RETURN jobpayrate.jpr_billing_rate%TYPE
    IS
    v_val jobpayrate.jpr_billing_rate%TYPE;
    BEGIN
    SELECT max(jpr_billing_rate) rate INTO v_val
    FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
    AND jpr_job_code = in_job_code
    AND jpr_trd_code = in_trd_code
    AND jpr_phs_code = in_phs_code
    AND jpr_cat_code = in_cat_code
    AND jpr_emp_no = in_emp_code;
    RETURN v_val;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        SELECT max(jpr_billing_rate) rate INTO v_val
        FROM jobpayrate
        WHERE jpr_comp_code = in_comp_code
        AND jpr_job_code = in_job_code
        AND jpr_trd_code = in_trd_code
        AND jpr_phs_code = in_phs_code
        AND jpr_cat_code = in_cat_code
        AND jpr_emp_no <> in_emp_code;
        RETURN v_val;
    --OTHER EXCEPTION HANDLING
    END;

  • Problems with a while loop within a method... (please help so I can sleep)

    Crud, I keep getting the wrong outputs for the reverseArray. I keep getting "9 7 5 7 9" instead of "9 7 5 3 1". Can you guys figure it out? T.I.A (been trying to figure this prog out for quite some time now)
    * AWT Sample application
    * @author Weili Guan
    * @version 1999999999.2541a 04/02/26
    public class ArrayMethods{
       private static int counter, counter2, ndx, checker, sum, a, size, zero;
       private static int length;
       private static int [] output2, output3, reverse, array;
       private static double output;
       private static double dblsum, dblchecker, average;
       public static void main(String[] args) {
          //int
          //int [] reverse;
          System.out.println("Testing with array with the values [1,3,5,7,9]");
          size = 5;
          array = new int [size];
          reverse = new int [size];
          array[0] = 1;
          array[1] = 3;
          array[2] = 5;
          array[3] = 7;
          array[4] = 9;
          System.out.println("Testing with sumArray...");
          output = sumArray(array);
          System.out.println("Sum of the array: " + sum);
          System.out.println();
          System.out.println("Testing with countArray...");
          output = countArray(array);
          System.out.println("Sum of the elements : " + checker);
          System.out.println();
          System.out.println("Testing with averageArray...");
          output = averageArray(array);
          System.out.println("The average of the array : " + average);
          System.out.println();
          System.out.println("Testing with reverseArray...");
          output2 = reverseArray(array);
          output3 = reverseArray(reverse);
          //System.out.print(reverse[4]);
          System.out.print("The reverse of the array : ");
          for(ndx = 0; ndx < array.length; ndx++){
             System.out.print(reverse[ndx] + " ");
       private ArrayMethods(){
       public static int sumArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if (array[ndx] > 0){
                checker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                sum += array[ndx];
                ndx++;
             return sum;
          else{
             sum = 0;
             return sum;
        /*Computes the sum of the elements of an int array. A null input, or a
        zero-length array are summed to zero.
        Parameters:
            array - an array of ints to be summed.
        Returns:
            The sum of the elements.*/
       public static int countArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if(array[ndx] > 0 && array[ndx] != 0){
                checker++;
             counter++;
          return checker;
        /*Computes the count of elements in an int array. The count of a
        null reference is taken to be zero.
        Parameters:
            array - an array of ints to be counted.
        Returns:
            The count of the elements.*/
       public static double averageArray(int[] array){
          dblchecker = 0;
          ndx = 0;
          counter = 0;
          dblsum = 0;
          while(counter < array.length){
             if(array[ndx] > 0){
                dblchecker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                dblsum += array[ndx];
                ndx++;
             average = dblsum / dblchecker;
             return (int) average;
          else{
             average = 0;
             return average;
        /*Computes the average of the elements of an int array. A null input,
        or a zero-length array are averaged to zero.
        Parameters:
            array - an array of ints to be averaged.
        Returns:
            The average of the elements.*/
       public static int[] reverseArray(int[] array){
          ndx = 0;
          counter = 0;
          counter2 = 0;
          if(array.length == 0){
             array[0] = 0;
             return array;
          else{
                //reverse = array;
             while(ndx <= size - 1){
                   reverse[ndx] = array[4 - counter];
                   counter++;
                   ndx++;
                   System.out.print("H ");
          return reverse;
        /*Returns a new array with the same elements as the input array, but
        in reversed order. In the event the input is a null reference, a
        null reference is returned. In the event the input is a zero-length array,
        the same reference is returned, rather than a new one.
        Parameters:
            array - an array of ints to be reversed.
        Returns:
            A reference to the new array.*/
    }

    What was the original question? I thought it was
    getting the desired output, " 9 7 5 3 1."
    He didn't ask for improving the while loop or the
    reverseArray method, did he?
    By removing "output3 = reverseArray(reverse):," you
    get the desired output.Okay, cranky-pants. Your solution provides the OP with the desired output. However, it only addresses the symptom rather than the underlying problem. If you'd bother yourself to look at the overall design, you might see that hard-coding magic numbers and returning static arrays as the result of reversing an array passed as an argument probably isn't such a great idea. That's why I attempted to help by providing a complete, working example of a method that "reverses" an int[].
    Removing everything and providing "System.out.println("9 7 5 3 1");" gets him the desired output as well, but (like your solution) does nothing to address the logic problems inherent in the method itself and the class as a whole.

  • While Loop Help...I think

    All,
    I have a fairly simple VI that grabs the units of measure (send a "A") from a MARK-10 test stand and MARK-10 force gauge. I'm struggling with how, or where, I should place my While Loop. What I would like the VI to do is if the units of measure are not correct, change the units (send a "U") and retry the comparison.
    Thanks in advance.
    Solved!
    Go to Solution.
    Attachments:
    Untitled 1.vi ‏12 KB

    That looks like it would do what you want it to do. I have two observations that may improve your design.
    1. Is it guaranteed that the unit will be two bytes long at the beginning at index 7? I would recommend using the match pattern vi and if the substring is not found the offset past match will be -1.
    2. The close port probably should be outside of the loop and shift registers are good too unless you want to loose any previous error details.
    -Nate

  • Noob Help with While Loop

    Sorry for the "Noob"-ness on this one. I am working on a program for class and I am having a problem with a while loop. So I opened a new document and began to code a while loop that is basic to test my while looping skill. Apparrently, I have none. Can anyone tell me why this While Loop will not work:
    public class test
         public static void main(String[] args)
         int LoanTerm = 0;
              while (LoanTerm < 3);
                   System.out.println (LoanTerm);
                   LoanTerm++;
    Thanks.
    FatherVic

    to explain, the ; means that the while loop body is empty, and you will just spin forever testing whether LoanTerm < 3, without doing anything else.

Maybe you are looking for

  • Problem with open in new window for second level tab

    Hi Friends, I am using 2 level tabs in my application. In my second level tab when i right click and select *open in new window* it is giving Page not found error. But for the first level tabs it is working correctly. How can i fix this so that eithe

  • Build a SQL 2008 R2 Failover clustering

    Hi, Am looking for a 2 node active passive SQL server clustering for testing purpose I believe that for building a cluster we need a AD, DNS and DHCP and shared disk .. I have searched in Internet and as of now I haven't found a complete solution for

  • TS1424 The iTunes store is temporarily unavailable. Please try again later.

    I can't to login to my account via iTunes on my PC.  When I enter the apple id and password, I get an error that says "The iTunes store is temporarily unavailable. Please try again later."  If I purposely enter a wrong password, iTunes will recognize

  • WindowsXP shuts down when iPod Touch 2nd gen 8gb is connected

    Everything was operating fine for the first day I was using my new iPod Touch. on the second day, I think I might have disconnected the iPod too early? The iPod itself is currently operating normally, however, every time I connect it to my PC/iTunes,

  • What if I have 2 firefox sync accounts?

    What if I have 2 separate firefox sync accounts from different computers? If I log out of one and try to log on the other on the same computer, it says it will merge the 2. How does that work?