Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jan 2008
    Posts
    17
    Thanks
    2
    Thanked 1 Time in 1 Post

    Variable scope question

    hey guys, i'm completely stumped!

    I've started teaching myself Java this week and i can't work something out:
    I have a method which accepts input from a user and calculates how much they'll earn in a week, it then stores the input into an array at the end they get the option to cycle back through the program, quit the program or view each of the records which have been stored into the array so far. my code works perfectly but i cannot understand how to make it store the input into the NEXT space in the array :S.

    Here's my code so far:
    Code:
    import java.util.*;
    
    public class sainsburys2 {
    	
    	public static void main(String[] args) {
    		rateCalculator();
    	}
    	
    	public static void rateCalculator() {
    		int x = 0;
    		String name;
    		int hours;
    		double pay;
    		double wage;
    		String answer;
    		String[] records;
    		records = new String[10];
    		Scanner in = new Scanner(System.in);
    		
    		System.out.println("******************************************************************");
    		System.out.println("********* Welcome to your personal planner for the week **********");
    		System.out.println("******************************************************************");
    		System.out.println("Please enter your name to begin");
    		System.out.print(">");
    		name = in.next();
    		
    		if (name.equalsIgnoreCase("Ollie")) {
    			System.out.println("\nhey Ollie, you made this program =]");
    		} else {
    			System.out.println("\nhello " + name.toUpperCase() + "\n");
    		}
    		System.out.println("\nPlease enter the amount of hours you will be working this week");
    		System.out.print(">");
    		hours = in.nextInt();
    		if (hours == 0) {
    			System.out.println("\nlazy goat, you should be shot!\n");
    		} else if(hours > 40) {
    			System.out.println("\nYou're working far too many hours!!\n");
    		}
    		System.out.println("\nOkay " + name + ", so you'll be working " + hours + " hours this week\n");
    		System.out.println("\nNow.. if you don't mind me asking, how much do you earn per hour?\n");
    		System.out.print("> $ ");
    		pay = in.nextDouble();
    		if (pay == 0) {
    			System.out.println("\nGet a different job, they're having a laugh\n");
    		} else if(pay >= 6) {
    			System.out.println("\nI wish i was earning as much as you =(\n");
    		}
    		System.out.println("\nOkay then, two seconds while i calculate how much you'll earn\n");
    		
    		wage = pay * hours;
    		
    		System.out.println("\nThis week you will be earning $" + wage);
    		System.out.println("\nwowzers!!\n");
    		records[x] = ("name: " + name.toUpperCase() + "\n hours: " + hours + "\n pay: $" + pay + "\n salary this week: $" + wage + "\n");
    		System.out.println(records[x]);
    		System.out.print("would you like to run through again? y or n please or r to view all records so far > ");
    		answer = in.next();
    		
    		if (answer.equalsIgnoreCase("y")) {
    			System.out.println("n\n\n\n");
                              x++
    			rateCalculator();
    		} else if (answer.equalsIgnoreCase("n")) {
    			System.exit(1);
    		} else if (answer.equalsIgnoreCase("r")) {
    			for (int i = 0;i<records.length;i++) {
    				System.out.println(records[i]);
    			}
    		}
            
    	}
    }
    I realise that my code is probably stupidly convoluted and pointless but it's my first real chunk of Java, the problem is that if they press Y at the end, i need it to increase "x" by one to go to the next space in the array, but obviously as the program reiterates, x is set to 0 again which will overwrite what was stored in the array originally, i need to find a way of making x increase by one every time the program iterates so that if "r" is pressed at the end it'll print every record in the array out.

    Please help guys!

    Ollie.

  • #2
    New Coder
    Join Date
    Apr 2007
    Posts
    34
    Thanks
    1
    Thanked 1 Time in 1 Post
    Ollie,
    Your problem is that every time you call rateCalculator() your x variable gets re-instantiated to 0. So the solution to this is to declare that variable outside of the function as a member variable of the class.
    Code:
    public class sainsburys2 {
    
      private int x = 0; 
     
      public static void main(String[] args) {
        rateCalculator();
      }
    
      public static void rateCalculator() {
        /** All your code without the int x declaration **/
      }
    }
    Also, it is best practice to name your classes with a capital first letter (i.e. Sainsburys2 instead of sainsburys2).
    Last edited by mamamia; 04-22-2008 at 05:32 PM.

  • #3
    New Coder
    Join Date
    Aug 2007
    Posts
    20
    Thanks
    0
    Thanked 1 Time in 1 Post

    Thumbs up

    Hi Ollie,
    Besides initialising the variable 'x', your program is also initializing the String array(records) every time.
    String[] records;
    records = new String[10];
    Hence, every time the user enters option as 'y', the rateCalculate() method is called again, and the above initialization occurs, which flushes the previosly stored values of records[].
    To prevent this, you may intitalise both of these as 'STATIC' during the start of the code and then use the value of 'x' to circulate through the records array.
    Also, when finally printing using the option 'r',the for loop needs to compare with x(number of values stored) and not with records.length(which stores the total length of the string array).
    The new code is attached for your reference :-
    Code:
    import java.util.*;
    
    public class sainsburys2 {
    		static String[] records = new String[100];
    		static int x=0;
    
    		public static void main(String[] args) {
    		rateCalculate(0);
    		}
    
            public static void rateCalculate(int x)
            {
    
    					String name;
    					int hours;
    					double pay;
    					double wage;
    					Scanner in = new Scanner(System.in);
    					String answer;
    					System.out.println("******************************************************************");
    					System.out.println("********* Welcome to your personal planner for the week **********");
    					System.out.println("******************************************************************");
    					System.out.println("Please enter your name to begin");
    					System.out.print(">");
    					name = in.next();
    
    					if (name.equalsIgnoreCase("Ollie")) {
    						System.out.println("\nhey Ollie, you made this program =]");
    					} else {
    						System.out.println("\nhello " + name.toUpperCase() + "\n");
    					}
    
    					System.out.println("\nPlease enter the amount of hours you will be working this week");
    					System.out.print(">");
    					hours = in.nextInt();
    					if (hours == 0) {
    						System.out.println("\nlazy goat, you should be shot!\n");
    					} else if(hours > 40) {
    						System.out.println("\nYou're working far too many hours!!\n");
    					}
    					System.out.println("\nOkay " + name + ", so you'll be working " + hours + " hours this week\n");
    					System.out.println("\nNow.. if you don't mind me asking, how much do you earn per hour?\n");
    					System.out.print("> $ ");
    					pay = in.nextDouble();
    					if (pay == 0) {
    						System.out.println("\nGet a different job, they're having a laugh\n");
    					} else if(pay >= 6) {
    						System.out.println("\nI wish i was earning as much as you =(\n");
    					}
    					System.out.println("\nOkay then, two seconds while i calculate how much you'll earn\n");
    
    					wage = pay * hours;
    
    					System.out.println("\nThis week you will be earning $" + wage);
    					System.out.println("\nwowzers!!\n");
    					records[x]= ("name: " + name.toUpperCase() + "\n hours: " + hours + "\n pay: $" + pay + "\n salary this week: $" + wage + "\n");
    					System.out.println(records[x]);
    					System.out.print("would you like to run through again? y or n please or r to view all records so far > ");
    
    					answer = in.next();					
    					if (answer.equalsIgnoreCase("y")) {
    						System.out.println("n\n\n\n");
    						x++;
    						rateCalculate(x);
    					} else if (answer.equalsIgnoreCase("n")) {
    						System.exit(1);
    					} else if (answer.equalsIgnoreCase("r")) {
    						for (int i = 0;i<=x;i++) {
    					System.out.println(records[i]);
    						}
    					}
    			}
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •