Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java Programming - Loops and Switch

Options
  • 08-10-2011 6:08pm
    #1
    Registered Users Posts: 377 ✭✭


    Hey

    Before I say anything I will admit Java would not be my strong point but am getting by with it on my college course. However I have a quick question on loops and switch statements.

    I have a exercise to do just to practice and am having a slight problem.

    Basically the program promts a user to enter an account type 4 options, money to be invested and term of investement. Each account type has a different interest rate so interest is calculated baed on which option user enters.

    Anyway I have writtten the program based on what I think it should do step by step but saying interest rate has not been initialised. and the x to exit not working.

    I am sure my error is obvious or stupid but have tried mixing it up every which way and to no avail. So any pointer be much appreciated as am not the best am want to be able to be somewhat confident as when examtime comes about and we do it in class I won't be at leisure to think too much or check notes if I am really stuck. Thanks.

    Here is what I have done so far

    import java.util.*;
    public class One
    {
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    char bankAccount;
    double investment;
    int term;
    double interestRate;
    double moneyEarned;
    double total;
    do{
    System.out.println("Enter bankAccount (A,B,C,Y)>");
    bankAccount = sc.next().charAt(0);
    System.out.println("Enter investment>");
    investment = sc.nextDouble();
    System.out.println("Enter the term>");
    term = sc.nextInt();
    moneyEarned = investment*interestRate*term;
    System.out.println("Money Earned is " + moneyEarned);
    total = investment + moneyEarned;
    System.out.println("Total is " + total);
    switch(bankAccount){
    case 'a':
    case 'A': interestRate = .005;
    break;
    case 'b':
    case 'B': interestRate = .013;
    break;
    case 'c':
    case 'C': interestRate = .03;
    break;
    case 'y':
    case 'Y': interestRate = .045;
    break;
    default: System.out.println("X to exit program");
    }
    }while(bankAccount!='X');
    }
    }


Comments

  • Closed Accounts Posts: 816 ✭✭✭Opinicus


    You're probably getting the initialise error for interestRate because the first time the loop runs the interestRate has not been set. You try and use it to calculate moneyEarned before assigning it a value.

    I don't know why you have a system.println as your default case for the switch. I would just include "X to exit" in the "Enter Bank Account" line.

    Are you typing a capital X to check your exit clause? You could have been typing in just an x. I would set the default in the switch to change bankAccount to capital X then you wouldn't have to check upper and lower case.


  • Closed Accounts Posts: 5,482 ✭✭✭Kidchameleon


    Have a look at this:
    import java.util.*;
    
    public class One
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            
            // its a good habit to initialise your variables.
            // if you dont, java will give them a default value (0.0 in the case of a double)
            // this is the reason you were getting a compile error, line 34 was multiplying by zero
            // i alway initialise ALL variables, it saves allot of headaches
            char bankAccount = 'a';
            double investment;
            int term;
            double interestRate = .005;
            double moneyEarned;
            double total;
    
            do
            {
                System.out.println("Enter bankAccount (A,B,C,Y)> (enter X to exit)");
                bankAccount = sc.next().charAt(0);
                
                //code to actually exit the program when the user decides
                if(bankAccount == 'x' || bankAccount == 'X')
                {
                    System.exit(0);
                }
                
                System.out.println("Enter investment>");
                investment = sc.nextDouble();
                System.out.println("Enter the term>");
                term = sc.nextInt();
                moneyEarned = investment * interestRate * term;
                System.out.println("Money Earned is " + moneyEarned);
                total = investment + moneyEarned;
                
                //added "\n" to make the layout nicer
                System.out.println("Total is " + total + "\n");
    
                switch(bankAccount)
                {
                    case 'a':
                    case 'A': interestRate = .005;
                    break;
                    case 'b':
                    case 'B': interestRate = .013;
                    break;
                    case 'c':
                    case 'C': interestRate = .03;
                    break;
                    case 'y':
                    case 'Y': interestRate = .045;
                    break;
                }
            }while(bankAccount!='X' && bankAccount != 'x');
            
        }
    }
    
    


  • Registered Users Posts: 377 ✭✭libra02


    Have a look at this:
    
    import java.util.*;
    
    public class One
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            
            // its a good habit to initialise your variables.
            // if you dont, java will give them a default value (0.0 in the case of a double)
            // this is the reason you were getting a compile error, line 34 was multiplying by zero
            // i alway initialise ALL variables, it saves allot of headaches
            char bankAccount = 'a';
            double investment;
            int term;
            double interestRate = .005;
            double moneyEarned;
            double total;
    
            do
            {
                System.out.println("Enter bankAccount (A,B,C,Y)> (enter X to exit)");
                bankAccount = sc.next().charAt(0);
                
                //code to actually exit the program when the user decides
                if(bankAccount == 'x' || bankAccount == 'X')
                {
                    System.exit(0);
                }
                
                System.out.println("Enter investment>");
                investment = sc.nextDouble();
                System.out.println("Enter the term>");
                term = sc.nextInt();
                moneyEarned = investment * interestRate * term;
                System.out.println("Money Earned is " + moneyEarned);
                total = investment + moneyEarned;
                
                //added "\n" to make the layout nicer
                System.out.println("Total is " + total + "\n");
    
                switch(bankAccount)
                {
                    case 'a':
                    case 'A': interestRate = .005;
                    break;
                    case 'b':
                    case 'B': interestRate = .013;
                    break;
                    case 'c':
                    case 'C': interestRate = .03;
                    break;
                    case 'y':
                    case 'Y': interestRate = .045;
                    break;
                }
            }while(bankAccount!='X' && bankAccount != 'x');
            
        }
    }
    
    


    Thanks for the reply. However I gave the variables values like you suggested above and it did complie with no errors. However it did not pick up the switch of interest rates based on account entered and just calculated the interest as the .005.

    So that obviously is not correct. I am working on another example like this, but no looping invloved, and same complier error.

    It really bugging me now as have tried different varaitaion and that to no avail. : (


  • Registered Users Posts: 2,534 ✭✭✭FruitLover


    You're trying to use the value of interestRate (in the statement moneyEarned = investment*interestRate*term; ) before you set the relevant value in the switch, which obviously isn't going to work.

    You'll need to restructure your code so that you assign the relevant value to interestRate before you go and do any calculations with it.


  • Registered Users Posts: 377 ✭✭libra02


    FruitLover wrote: »
    You're trying to use the value of interestRate (in the statement moneyEarned = investment*interestRate*term; ) before you set the relevant value in the switch, which obviously isn't going to work.

    You'll need to restructure your code so that you assign the relevant value to interestRate before you go and do any calculations with it.


    Thanks but that is what I have been doing and I know I am going wrong someplace and it is probably so stupid and easy but am still not having any luck at all.

    I have changed the do while loop placement, the switch statement placement and that blooming error still appears. For example I put the swtich statement right after the prompt to enter bank account.

    I know I am probably coming across as thick but any other prompt in right direction be greatly appeciated. I have been playing about with it all morning.


  • Advertisement
  • Registered Users Posts: 2,534 ✭✭✭FruitLover


    libra02 wrote: »
    For example I put the swtich statement right after the prompt to enter bank account.

    OK, this sounds like you're getting closer to the answer. Post up this version of the code (please use [code] tags!) and we'll have a look at what's still wrong.

    The most important thing is to make sure you're thinking logically about what happens at each line of your program, and not just moving things around randomly, hoping that it will fix the problem.


  • Registered Users Posts: 377 ✭✭libra02


    FruitLover wrote: »
    OK, this sounds like you're getting closer to the answer. Post up this version of the code (please use [code] tags!) and we'll have a look at what's still wrong.

    The most important thing is to make sure you're thinking logically about what happens at each line of your program, and not just moving things around randomly, hoping that it will fix the problem.


    Ok here is what I have changed it to

    import java.util.*;
    public class Deposit
    {
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    char bankAccount;
    double investment;
    int term;
    double interestRate;
    double moneyEarned;
    double total;
    do{
    System.out.println("Enter bankAccount (A,B,C,Y)> (X to exit)");
    bankAccount = sc.next().charAt(0);
    switch(bankAccount){ // interest rate varies per bank account
    case 'a':
    case 'A': interestRate = .005;
    break;
    case 'b':
    case 'B': interestRate = .013;
    break;
    case 'c':
    case 'C': interestRate = .03;
    break;
    case 'y':
    case 'Y': interestRate = .045;
    break;
    }
    System.out.println("Enter investment>");
    investment = sc.nextDouble();
    System.out.println("Enter the term>"); // years of the investment
    term = sc.nextInt();
    moneyEarned = investment*interestRate*term; // calculate interest earned
    System.out.println("Money Earned is " + moneyEarned);
    total = investment + moneyEarned;
    System.out.println("Total is " + total);
    }while(bankAccount!='X' && bankAccount != 'x'); // loop until exit
    }
    } // end of class


  • Registered Users Posts: 2,534 ✭✭✭FruitLover


    The new code looks better (although it's hard to read - please use [code] tags when posting code to make it easier to read). I'm not familiar with the Scanner object though, so I have no idea whether it's being used correctly here.

    Please post up any compiler or run-time errors you get.


  • Moderators, Technology & Internet Moderators Posts: 1,335 Mod ✭✭✭✭croo


    ask yourself; what would happen if someone entered a value other than a,b,c or y?
    The compiler is doing this and finding that in some scenarios it will be using the interestRate when it was never set to a value.

    tip: case has a default: clause! ;)

    ps. you should wrap your code in the code clauses when posting then it keeps it format!


  • Registered Users Posts: 2,089 ✭✭✭henryporter


    I think you should still initialize the interestRate value for starters.

    Also the sentinel 'X' will only exit the program after it has gone through another iteration, ie it will run once more using 'X' or 'x' as the interestRate determinant.

    Try using a debugger to step through the program - it will make some things more obvious.


  • Advertisement
  • Closed Accounts Posts: 2 Evbevmagevbof


    Scanner.next() (and scanner.nextInt() etc...) doesn't read the "/n" at the end of a line. So when you next say scanner.nextInt() it sees the newline character and returns 0. You need to put scanner.nextLine() for the scanner to read from the next line.

    bankAccount = sc.next().charAt(0);
    sc.nextLine();

    You need to do this for all of them.

    Hope this helps!


  • Registered Users Posts: 377 ✭✭libra02


    FruitLover wrote: »
    The new code looks better (although it's hard to read - please use [code] tags when posting code to make it easier to read). I'm not familiar with the Scanner object though, so I have no idea whether it's being used correctly here.

    Please post up any compiler or run-time errors you get.


    Error I get is java.35 variable interestRate might not have been initialised
    moneyEarned is = investmentRate*interestRate*term;

    Sorry I am not familiar with code tags.

    The scanner object is correct I do know that.


  • Registered Users Posts: 339 ✭✭duffman85


    libra02 wrote: »
    Error I get is java.35 variable interestRate might not have been initialised
    moneyEarned is = investmentRate*interestRate*term;

    Sorry I am not familiar with code tags.

    The scanner object is correct I do know that.

    all your variables are local to the main method
    local variables are never initialised -> you must always initialise local variables before using them.

    the code tags are just an option for formatting code when posting on boards

    in your post type
    [HTML]
    paste your code here
    
    [/HTML]

    and you get something like this:
    import java.util.*;
    public class Deposit
    {
    public static void main(String[] args)
    {
    ....
    my code goes here
    ...
    ...
    ...
    }
    } // end of class
    

    you can also use the PHP tags in similar way to make it more colourful
    [HTML][PHP]
    paste your code here
    [/PHP][/HTML]

    [PHP]import java.util.*;
    public class Deposit
    {
    public static void main(String[] args)
    {
    ....
    my code goes here
    ...
    ...
    ...
    }
    } // end of class[/PHP]


  • Registered Users Posts: 377 ✭✭libra02


    Thanks for the advice everyone think I have got it working. Just need to add in code for the x to exit and it is done.

    Actually while I am here quick question can you use arrays to find out number of days/nights between two dates?

    Was reading something that arrays can be used for this but book never gave an example of code to indicate how this can be done.

    I take it you would need user to enter day, month and year or arrival and then same for departure date. These be taking in from keyboard and then you would need to use an array to hold numbers of days in each month but after dont'i understaand how you go about couting the time especially if you have dates which are in two different years? I think maybe some kind of for loop ?


  • Closed Accounts Posts: 816 ✭✭✭Opinicus


    Look for Gregorian Calendar in the API. That should simplify matters, unless you have to use arrays in the way you specified.


  • Registered Users Posts: 377 ✭✭libra02


    Opinicus wrote: »
    Look for Gregorian Calendar in the API. That should simplify matters, unless you have to use arrays in the way you specified.


    It def be arrays that be used be hardest way first and then go onto the easier way.

    So I know you would have to have an index to store numbers of days in each month and also have to get the user to enter the day month and year of arrival and departure.
    I take it some loops have to be involveed but seems that it could get very complicated - maybe that is just me.


  • Closed Accounts Posts: 577 ✭✭✭Galtee


    libra02 wrote: »
    It def be arrays that be used be hardest way first and then go onto the easier way.

    So I know you would have to have an index to store numbers of days in each month and also have to get the user to enter the day month and year of arrival and departure.
    I take it some loops have to be involveed but seems that it could get very complicated - maybe that is just me.

    It's not really very complicated and you're on the right track. Outside of validation of inputs (Where departure date needs to be greater than arrival date) with regard to the date parameters there are really only two special cases you have to concern yourself with and you have one of them already which is the potential difference in year. To say it in english (which I find helps) the algorithm you need to write must count the days FROM any day in any month in any year TO any day in any month in any year. Think about it.


  • Registered Users Posts: 377 ✭✭libra02


    Galtee wrote: »
    It's not really very complicated and you're on the right track. Outside of validation of inputs (Where departure date needs to be greater than arrival date) with regard to the date parameters there are really only two special cases you have to concern yourself with and you have one of them already which is the potential difference in year. To say it in english (which I find helps) the algorithm you need to write must count the days FROM any day in any month in any year TO any day in any month in any year. Think about it.


    I know what you are getting at alright and that you do need a coutning loop / facility to count the days from arrival to departure. Just with what I know so far I cannot see how this can be achieved.

    We have not started arrays let but will in next week I figure unless we skip and do something else but want to try to get a bit ahead given that it not my strongest ability. As I said I know what an array is and how you assign numbers/ letters to it.
    As I said given no example was given hard to get head around concept a small bit.


  • Registered Users Posts: 3,532 ✭✭✭Unregistered.


    libra02 wrote: »
    I know what you are getting at alright and that you do need a coutning loop / facility to count the days from arrival to departure. Just with what I know so far I cannot see how this can be achieved.
    Where there is a will, there is a way.

    Consider this:

    The first of January 2011 (01/01/2011) is day 0. The 31st of December (31/12/2011) is day 364, i.e. 365 days inclusive. Assume all days from day 0 to day 364 are numbered sequentially.


Advertisement