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
Hi all! We have been experiencing an issue on site where threads have been missing the latest postings. The platform host Vanilla are working on this issue. A workaround that has been used by some is to navigate back from 1 to 10+ pages to re-sync the thread and this will then show the latest posts. Thanks, Mike.
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Finding smaller number of 2 numbers inputted by user

24

Comments

  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Still trying too get my head around the difference of the loops so thanks for explaining.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Good use of try/catch?

    {
                GetCarSeatNumber();
            }
    
            static void GetCarSeatNumber()
            {
                try
                {
                    Console.WriteLine("Please enter the numbers 1, 2, or 5 only please");
                    string str = Console.ReadLine();
                    int num = int.Parse(str);
    
                    if (num == 1 || num == 2 || num == 3)
                    {
                        Console.WriteLine("You have entered the correct numbers! ");
    
                    }
                    else
                        Console.WriteLine("That number is incorrect, please try again!");
    
                }
    
                catch (FormatException fe)
                {
                    Console.WriteLine("Please refrain from entering non digit key! ");
                
                }
    


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx

    That parse function can throw more than just FormatException. You should probably handle them all, especially seeing as the user can enter the data.


  • Registered Users, Registered Users 2 Posts: 1,931 ✭✭✭PrzemoF


    Good use of try/catch?
    [..]
    My 2 cents. You should keep as little as possible in the try-catch. I.e. Console.WriteLine will never fail, so no need to have it inside the try-catch. Same for if-else in your example - it won't fail. Only ReadLine/Parse might fail, so I'd keep them in the try-catch, the rest should be out.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    PrzemoF wrote: »
    My 2 cents. You should keep as little as possible in the try-catch. I.e. Console.WriteLine will never fail, so no need to have it inside the try-catch. Same for if-else in your example - it won't fail. Only ReadLine/Parse might fail, so I'd keep them in the try-catch, the rest should be out.

    The examples he showed us had it done that way, hence why I did it that way, I'll give your way a shot.


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    If you're trying to show an example of a try catch your code is fine.

    If you want to catch all exceptions just use
    catch(Exception ex){
    ...
    }
    

    You can have multiple catch blocks so you can catch different exceptions in the try block.
    This allows you to implement different handling behaviour depending on the exception thrown.

    If you have multiple catch blocks and are using the above generic Exception catch make it the last one as the catches are handled sequentially

    +1 on PrzemoF's suggestion on minimising code in the try.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Learning about OO Today, Working with classes, tricky enough!
    class Student
        {
            public string studentName;
            public int studentAge;
            public double mathematicsMark;
            public double irishMark;
            public double englishMark;
            
    
    
            static void Main(string[] args)
    
            {
                Student a = new Student();
                Student b = new Student();
                Student c = new Student();
    
                a.studentName = "John";
                a.studentAge = 31;
                a.mathematicsMark = 60.0;
                a.irishMark = 60.0;
                a.englishMark = 60.0;
    
               
    
                b.studentName = "Kevin";
                b.studentAge = 32;
                b.mathematicsMark = 50.0;
                b.irishMark = 50.0;
                b.englishMark = 51.0;
    
              
    
                c.studentName = "Jerry";
                c.studentAge = 29;
                c.mathematicsMark = 60.0;
                c.irishMark = 60.0;
                c.englishMark = 60.0;
    
                Console.WriteLine(+ a.AverageMark());
                Console.WriteLine(+ b.AverageMark());
                Console.WriteLine(+ c.AverageMark());
    
                a.DisplayStudentDetails();
                b.DisplayStudentDetails();
                c.DisplayStudentDetails();
    
               
                
    
    
            }
    
            public double AverageMark()
    
        {
        
            double TotalAverageMark;
            return TotalAverageMark = (mathematicsMark + irishMark + englishMark) / 3;
        
        }
    
    
               void DisplayStudentDetails()
    
        {
            Console.WriteLine("Student name:" + studentName);
    
            Console.WriteLine("Student age:" + studentAge);
    
            Console.WriteLine("english Mark" + englishMark);
    
            Console.WriteLine("irish Mark" + irishMark);
    
            Console.WriteLine("matheMathics mark" + mathematicsMark);
            
           
           
        }
    
       
           
    
       
    
    
    
    
    
    
    
    
    
    
    
    
    
        }
    }
    


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    PrzemoF wrote: »
    My 2 cents. You should keep as little as possible in the try-catch. I.e. Console.WriteLine will never fail, so no need to have it inside the try-catch. Same for if-else in your example - it won't fail. Only ReadLine/Parse might fail, so I'd keep them in the try-catch, the rest should be out.

    I'd probably disagree, seeing as it will be less readable. There is no performance reason to split it up either.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Would appreciate help here if possible,the calculation is doing what I want it too do, it seems too be only adding and not subtracting
    {
        class Customer
        {
            public string customerName;
            public double debitPurchase;
            public double creditPayment;
            public double openingBalance;
            public double closingBalance;
    
    
    
            public double CalculateCustomerBalance(double creditPayment, double openingBalance, double closingBalance, double debitPurchase)
    {
    
            return closingBalance = openingBalance  + creditPayment - debitPurchase;
    


    {
        class Program
        {
            static void Main(string[] args)
            {
                Customer a1 = new Customer();
                Customer b2 = new Customer();
                Customer c3 = new Customer();
    
                a1.customerName = "Kevin O Sullivan";
                a1.debitPurchase = 2000;
                a1.creditPayment = 2000;
                a1.openingBalance = 10000;
                a1.closingBalance = 0;
    
                Console.WriteLine("Your name is: "+a1.customerName);
                Console.WriteLine("Your opening balance is: "+a1.openingBalance);
                Console.WriteLine("Your new closing balance is:" + a1.CalculateCustomerBalance(a1.openingBalance, a1.debitPurchase,a1.creditPayment, a1.closingBalance));
    
                b2.customerName = "Jerry Murphy";
                b2.debitPurchase = 1000;
                b2.creditPayment = 2000;
                b2.openingBalance = 15000;
                b2.closingBalance = 0;
    
                Console.WriteLine("Your name is: "+b2.customerName);
                Console.WriteLine("Your opening Balance is: "+b2.openingBalance);
                Console.WriteLine("Your new closing Balance is: "+b2.CalculateCustomerBalance(b2.openingBalance, b2.debitPurchase,b2.creditPayment,b2.closingBalance));
                
    


  • Advertisement
  • Registered Users Posts: 986 ✭✭✭Greyian


    Would appreciate help here if possible,the calculation is doing what I want it too do, it seems too be only adding and not subtracting
    {
        class Customer
        {
            public string customerName;
            public double debitPurchase;
            public double creditPayment;
            public double openingBalance;
            public double closingBalance;
    
    
    
            public double CalculateCustomerBalance(double creditPayment, double openingBalance, double closingBalance, double debitPurchase)
    {
    
            return closingBalance = openingBalance  + creditPayment - debitPurchase;
    


    {
        class Program
        {
            static void Main(string[] args)
            {
                Customer a1 = new Customer();
                Customer b2 = new Customer();
                Customer c3 = new Customer();
    
                a1.customerName = "Kevin O Sullivan";
                a1.debitPurchase = 2000;
                a1.creditPayment = 2000;
                a1.openingBalance = 10000;
                a1.closingBalance = 0;
    
                Console.WriteLine("Your name is: "+a1.customerName);
                Console.WriteLine("Your opening balance is: "+a1.openingBalance);
                Console.WriteLine("Your new closing balance is:" + a1.CalculateCustomerBalance(a1.openingBalance, a1.debitPurchase,a1.creditPayment, a1.closingBalance));
    
                b2.customerName = "Jerry Murphy";
                b2.debitPurchase = 1000;
                b2.creditPayment = 2000;
                b2.openingBalance = 15000;
                b2.closingBalance = 0;
    
                Console.WriteLine("Your name is: "+b2.customerName);
                Console.WriteLine("Your opening Balance is: "+b2.openingBalance);
                Console.WriteLine("Your new closing Balance is: "+b2.CalculateCustomerBalance(b2.openingBalance, b2.debitPurchase,b2.creditPayment,b2.closingBalance));
                
    

    Your variables are in the wrong order when you're calling the method.
    To take Kevin O'Sullivan as an example, you have:
    DebitPurchase: 2000
    CreditPayment: 2000
    OpenBalance: 10000

    You'd expect this to give a closing balance of 10000 (2000 DP and 2000 CP cancel each other out, so closing balance is the same as opening balance).
    But you're entering them as follows into the method:
    10000, 2000, 2000, 0.
    This means Var1 = 10000, Var2 = 2000, Var3=2000 and Var4 = 0.
    In the module, your calculation is return value = Var 2 + Var 1 - Var 4.
    This means you're calculating the return value as 2000 + 10000 - 0.

    You need to have your inputs in the correct order.
    If your method has them as credit, opening, closing, debit, you must also put them in that order when calling the method (but you're not, you have them as opening, debit, credit, closing).


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Thank you!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    We were learning about constructs the other day and I don't fully understand why there important or why you would use them, any insight?


  • Registered Users, Registered Users 2 Posts: 6,260 ✭✭✭Buford T Justice


    We were learning about constructs the other day and I don't fully understand why there important or why you would use them, any insight?

    This should help, but if you're struggling with this, then here's a more detailed explanation with examples


  • Registered Users, Registered Users 2 Posts: 6,198 ✭✭✭Talisman


    We were learning about constructs the other day and I don't fully understand why there important or why you would use them, any insight?
    It helps to have an idea of what is happening in the layer below your code.

    Back in 1999, the C# and Java object-oriented platforms were implemented in C. By today's standards C is a low level language. It is a level above assembly language which is the human readable translation of machine code. Machine code is the hexadecimal gibberish that you may have seen if you were ever curious enough to open an executable file in a text editor.

    In C there were just plain old data structures and functions. Because the code is written at a low level the developer has to do a lot of things for themselves, e.g. allocate memory to store data structures, remember to deallocate the memory when finished with it, pass memory pointers to functions etc. There was a lot of stuff that was easy to screw up and nearly always bad things happened as a result.

    The object oriented languages operate at a higher level, a class combines the data structures and the functions to operate on the data into a single entity. In order to use an object, it must first be loaded into memory - this is where the constructor comes into play. The constructor magically allocates the memory for the instance of the class (object) and may also initialise values for class variables etc. so that they are available to use.

    Essentially the constructor is talking to the underlying layer and asks it to do all of the dirty work so that the developer doesn't have to worry about it. The 'new' keyword and the constructor function make object oriented languages sweeter for human use.


  • Registered Users, Registered Users 2 Posts: 1,931 ✭✭✭PrzemoF


    Anima wrote: »
    I'd probably disagree, seeing as it will be less readable. There is no performance reason to split it up either.
    No, there is no real gain in that very example. But if you have the habit of keeping large pieces of code in try-catch you'll sooner or later catch too much.


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Trying too write a program where by the user can select from an option from a menu and then It will bring them too that function where they will enter values and they get calculated, I'm have a problem with my the electrical method, when you select one it just prints "Electrical charge" and doesn't ask the user for input, its driving me demented, any advice please?

    static void Main(string[] args)
            {
                
    
               
                  menuPrompt();
                  ElectricalCharges();
            }
    
                   
                    
    
    
                  
                   
    
            
    
            
    
    
            static void menuPrompt()
            {
                Console.WriteLine("Please enter a selection between 1 and 2 or press 0 too exit");
               
                
    
                 int choice = 0;
                do
                {
    
    
                   
                    
    
    
                    
                    choice = int.Parse(Console.ReadLine());
                    switch (choice)
                    {
                        case 1:
                            Console.WriteLine("Electrial Charges Calculator ");
                            break;
    
                        case 2:
                            Console.WriteLine("Water Charges Calculator");
                            break;
                        case 0: 
                            Console.WriteLine("Thank you! Come again! ");
                            break;
    
                        default:
                            Console.WriteLine("Not a valid selection!");
                            break;
    
                    }
    
    
                    } while (choice != 0);
                    
    
    
    
    
    
    
    
               
    
    
            
    
            
    
    
            
            }
    
               static double ElectricalCharges()
               
               {
    
                   double PerHour = 0.20;
                   double TotalCost = 0;
    
                   Console.WriteLine("Please enter the number of electric units used this month :");
                   double Charge = int.Parse(Console.ReadLine());
    
                   PerHour = PerHour * Charge;
                   return TotalCost;
    
                  
                   }
    


  • Registered Users, Registered Users 2 Posts: 6,260 ✭✭✭Buford T Justice


    To be fair, there's a few things wrong with what you've written. Have a look at the following and see if you can understand it. Note, the return value from the ElectricalCharge method is not handled
            static void Main(string[] args)
            {
                menuPrompt();
            }
            static void menuPrompt()
            {
                int choice =0;
                while (choice != -999)
                {
                Console.WriteLine("Please enter a selection between 1 and 2 or press -999 to exit");
                choice = Convert.ToInt32(Console.ReadLine());
    
                    switch (choice)
                    {
                        case 1:
                            Console.WriteLine("Electrial Charges Calculator ");
                            ElectricalCharges();
                            break;
    
                        case 2:
                            Console.WriteLine("Water Charges Calculator");
                            break;
                        case 0:
                            Console.WriteLine("Thank you! Come again! ");
                            break;
    
                        default:
                            Console.WriteLine("Not a valid selection!");
                            break;
    
                    }
                }
            }
    
            static double ElectricalCharges()
            {
                double PerHour = 0.20;
                double TotalCost = 0;
    
                Console.WriteLine("Please enter the number of electric units used this month :");
                double Charge = int.Parse(Console.ReadLine());
    
                PerHour = PerHour * Charge;
                return TotalCost;
            }
        }
    


  • Registered Users Posts: 986 ✭✭✭Greyian


    Trying too write a program where by the user can select from an option from a menu and then It will bring them too that function where they will enter values and they get calculated, I'm have a problem with my the electrical method, when you select one it just prints "Electrical charge" and doesn't ask the user for input, its driving me demented, any advice please?

    static void Main(string[] args)
    {
    	menuPrompt();
    	ElectricalCharges();
    }
    
    static void menuPrompt()
    {
    	Console.WriteLine("Please enter a selection between 1 and 2 or press 0 too exit");
    	int choice = 0;
    	do
    	{
    		choice = int.Parse(Console.ReadLine());
    		switch (choice)
    		{
    			case 1:
    				Console.WriteLine("Electrial Charges Calculator ");
    				break;
    			case 2:
    				Console.WriteLine("Water Charges Calculator");
    				break;
    			case 0: 
    				Console.WriteLine("Thank you! Come again! ");
    				break;
    			default:
    				Console.WriteLine("Not a valid selection!");
    				break;
    		}
    
    	} while (choice != 0);
    }
    
    static double ElectricalCharges()           
    {
    	double PerHour = 0.20;
    	double TotalCost = 0;
    
    	Console.WriteLine("Please enter the number of electric units used this month :");
    	double Charge = int.Parse(Console.ReadLine());
    
    	PerHour = PerHour * Charge;
    	return TotalCost;
    }
    

    OK, let's work through what your code is doing:

    The Main method is calling menuPrompt, and is then calling ElectricalCharges. It should not call the ElectricalCharges method, as that should be determined by the user's selection inside the menuPrompt method.

    In the menuPrompt functionality, you're asking the user to choose an option. You are then processing the option. If it is 1, you are outputting "Electrical Charges Calculator", but you aren't actually doing anything beyond that. This is where the ElectricalCharges method should be called.

    As it stands, this is the logic your program is carrying out:

    1) The menuPrompt functionality is called.
    2) The user is prompted to select an option. The user provides their input.
    3) The user's input is used to select the option. If the option selected is not 0, output the selected option and then return to Step 2.
    If the option selected is 0, tell the user thank you.
    4) Carry out the ElectricalCharges method, as it takes place after menuPrompt in the Main thread.

    You need to remove ElectricalCharges from the Main thread, and instead have it in the switch statement (under Case 1).


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    the return value from the ElectricalCharge method is not handled

    You mean for an exception?


  • Registered Users, Registered Users 2 Posts: 17,644 ✭✭✭✭Mr. CooL ICE


    I'm kinda confused as to what the program is supposed to be doing.
    You mean for an exception?

    No. As in, you are calling the ElectricalCharge method but not doing anything with it. ElectricalCharge is set to return a value, but the value it is returning is not being assigned to anything.



    Wouldn't it make more sense to call ElectricalCharge from inside the loop? From Inside the switch statement. Think of it this way; user enters the option for ElectricalCharge, so it would make sense to then call ElectricalCharge.


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    I'm kinda confused as to what the program is supposed to be doing.



    Well think of it as a utilities menu, where by you can choose too work out your water charges or your electricity, so when the user chooses lets water it will bring you down too that method the user enters how many litres of water they've used and it calculates it, same idea for the electricity, I want too eventually flesh out then and add other things too it, if that makes sense?


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    How can I separate it this out ? I want too have a one line space after yearly salary?for each employee.

    FE3dwPM.png


    The code in case ye want too have a look
    class Employee
        {
            public string employeeName;
            public int employeeAge;
            public string employeeDepartment;
            public int employeeNumber;
            public int weeklyHours;
            public double taxRate;
            public int yearsOfService;
            public int monthlySalary;
            public int yearlyIncome;
    
            public Employee() {}
    
            public Employee(string inEmployeeName,int inEmployeeAge,string inEmployeeDepartment,int inEmployeeNumber,int inWeeklyHours,double inTaxRate,int inYearsOfService,int inMonthlySalary,int inYearlyIncome)
            {
              employeeName = inEmployeeName;
              employeeAge = inEmployeeAge;
              employeeDepartment = inEmployeeDepartment;
              employeeNumber = inEmployeeNumber;
              weeklyHours = inWeeklyHours;
              taxRate = inTaxRate;
              yearsOfService = inYearsOfService;
              monthlySalary = inMonthlySalary;
              yearlyIncome = inYearlyIncome;
           }
    
            public void EmployeeDetails()
            { 
               Console.WriteLine("Employee's Name             :"+employeeName);
               Console.WriteLine("Employee's Age              :"+employeeAge);
               Console.WriteLine("Employee's Department       :"+employeeDepartment);
               Console.WriteLine("Employee's Number           :"+employeeNumber);
               Console.WriteLine("Employee's Weekly Hours:    :"+weeklyHours); 
               Console.WriteLine("Employee's Tax Rate         :"+taxRate);
               Console.WriteLine("Employee's Years of service :"+yearsOfService);
               Console.WriteLine("Employee's Monthly Salary   :"+monthlySalary);
               Console.WriteLine("Employee's Yearly Salary    :"+yearlyIncome);
    

    namespace Information
    {
        class Program
        {
            static void Main(string[] args)
            {
                Employee a1 = new Employee("Kevin O Sullivan",31,"Software Writer",5667,39,0.20,5,3500,0);
                a1.EmployeeDetails();
    
                Employee b2 = new Employee("Mary Murphy",28,"Software Writer",5442,39,0.20,6,3600,0);
                b2.EmployeeDetails();
    
                Employee c3 = new Employee("John Cusack", 35, "Software Tester", 5876, 39, 0.20, 10, 4000, 0);
                c3.EmployeeDetails();
    
                Employee d4 = new Employee("Teresa O Reilly",30,"Software Tester",5798,39,0.20,7,3800,0);
                d4.EmployeeDetails();
    
                Employee e5 = new Employee("Timmy Jones",35,"Payroll",6723,39,0.42,8,4200,0);
                e5.EmployeeDetails();
    
                Employee f6 = new Employee("Ciara O Mahony",40,"Head Accountant",4432,50,0.42,15,6000,0);
                f6.EmployeeDetails();
    
                Employee g7 = new Employee("Chris Murphy",43,"Technical Writer",3445,40,0.42,12,4500,0);
                g7.EmployeeDetails();
    
    
                Employee h8 = new Employee("Maire Higgins",49,"CEO/Manager",4214,55,0.42,25,7000,0);
                h8.EmployeeDetails();
    


    As always, thanks for the help.


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    Write a blank/null line in EmployeeDetails method


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    begbysback wrote: »
    Write a blank/null line in EmployeeDetails method

    You mean like this consolewriteline("" ) ;?


  • Registered Users, Registered Users 2 Posts: 6,260 ✭✭✭Buford T Justice


    Console.WriteLine("Employee's Yearly Salary    :"+yearlyIncome + "\n");
    


  • Registered Users, Registered Users 2 Posts: 6,198 ✭✭✭Talisman


    This isn't directly related to your question but will help you produce cleaner code.

    Instead of manually padding your strings you can use the optional alignment component to do the work for you. The alignment component is a signed integer which indicates the preferred formatted width.

    The following composite format string left-aligns the field name in a 30-character field. Negative numbers result in left alignment, positive numbers result in right alignment of the value.
    Console.WriteLine("{0,-30} : {1}\n", "Employee's Name", name);
    

    See Composite Formatting in the .NET documentation for more details.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Let say I have a method
    public int Calculate(int num1, int num2);
    
    {
               return answer = num1 +num2;
          
    }
    

    How would I pass the answer too another method too do another calculation with that answer? is it even possible too do it?


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    You've defined a return type (int) so you can do the following.
    int param = Calculate(num1, num2);
    
    AnotherCalculation(param);
    
    

    or you could short cut it
    AnotherCalculation(Calculate(num1, num2));
    


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    Also in your function your return should be just
    return num1+num2
    

    Unless "answer" is a class level variable and you want it to hold the value.

    In that case you can change the return type to void and pass "answer" to your next method.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Remouad wrote: »
    Also in your function your return should be just
    return num1+num2
    

    Unless "answer" is a class level variable and you want it to hold the value.

    In that case you can change the return type to void and pass "answer" to your next method.

    So if the answer = 10, the next method will know this?

    Will that work as well for instance variables?


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    So if the answer = 10, the next method will know this?

    Will that work as well for instance variables?

    Yes & yes.
    All depends on your implementation.
    Rough example below.
        class NumberFidgit
        {
            public int answer;
    
            public void Sum(int num1, int num2)
            {
                answer = num1 + num2;
            }
    
            public void Square()
            {
                answer = answer * answer;
            }
        }
    
        class NumberCaller
        {
            public NumberFidgit fidgit = new NumberFidgit();
            public void populateFigit()
            {
                fidgit.Sum(1, 2);//answer =3
                fidgit.Square();//answer =9
    
                incrementByReference(ref fidgit.answer); //answer =10
                int i = incrementByValue(fidgit.answer);//i=11, answer still 10
                fidgit.answer = incrementByValue(fidgit.answer);//answer = 11
                incrementVariable();//answer=12
            }
    
            public void incrementByReference(ref int i)
            {
                i = i + 1;
            }
    
            public int incrementByValue(int i)
            {
                return i + 1;
            }
    
            public void incrementVariable()
            {
                fidgit.answer += 1;
            }
        }
    
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Thanks alot Remouad!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    I passed my course :) and will be starting a new course 15th of January (Mobile Technologies) can't wait!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    I was messing around with java a bit lately as that's what we'll be using on the new course but I Have a question regarding the code below

    public class Inheritence5 {
    
    	public static class Hero
    	{
    	    protected String Name;
            protected int Age;
            protected String Class;
            protected String Vocation;
            protected int Strenght;
            protected int DamageOutPut;
            protected int HitPoints;
            protected int DefensePoints;
            protected int Intelligence;
            protected int Focus;
            protected Boolean Evil;
            protected Boolean Good;
    	
    	public  void HeroStats()
    	{
    		 System.out.println("Name: " +Name);
    		 System.out.println("Age: " +Age);
    		 System.out.println("Class " + Class);
    		 System.out.println("Vocation: " +Vocation);
    		 System.out.println("Strenght: " +Strenght);
    		 System.out.println("Damage Output: " +DamageOutPut);
    		 System.out.println("HitPoints: " +HitPoints);
    		 System.out.println("DefensePoints: " +DefensePoints);
    		 System.out.println("Focus: " +Focus);
    		 System.out.println("Evil: " +Evil);
    		 System.out.println("Good: " +Good);
    	}
    	
    	}
    	
    	public  static class Warrior extends Hero
    	{
    		 public int Stamina;
             public double CriticalStrike;
             
             public void SpecialStat()
             {
            	 System.out.println("Stamina: " +Stamina);
            	 System.out.println("CriticalStrike" +CriticalStrike);
             }
    	}
    	
    	public static class Wizard extends Hero
    	{
    		protected int MagicalPoints;
    		
    		
    		protected void SpecialStats()
    		{
    			System.out.println("MagicalPoints: " +MagicalPoints);
    			
    		}
    	}
    	
    	
    	public static void main(String[] args) 
    	{
               Warrior Kevin = new Warrior();
               Kevin.Name = "Kevin";
    	  Kevin.Age = 31;
    	  Kevin.Class = "Warrior";
    	 Kevin.Vocation = "Tank";
    	 Kevin.Strenght = 90;
    	Kevin.DamageOutPut = 200;
    	Kevin.HitPoints = 350;
    	Kevin.DefensePoints = 100;
    	Kevin.Intelligence = 50;
    	Kevin.Focus = 56;
            Kevin.Evil = false;
            Kevin.Good = true;
            Kevin.Stamina = 78;
            Kevin.CriticalStrike = 77.5;
            Kevin.HeroStats();
            Kevin.SpecialStat();
           
            System.out.println();
    	    
    	     Wizard Conor = new Wizard();
    	     Conor.Name = "Conor";
    	     Conor.Age = 32;
    	     Conor.Class = "Wizard";
    	     Conor.Vocation = "Healer";
    	     Conor.Strenght = 40;
    	     Conor.DamageOutPut = 300;
    	     Conor.HitPoints = 500;
    	     Conor.DefensePoints = 100;
    	     Conor.Intelligence = 200;
    	     Conor.Focus = 80;
    	     Conor.Evil = false;
    	     Conor.Good = true;
    	     Conor.MagicalPoints = 500;
    	     Conor.HeroStats();
    	     Conor.SpecialStats();
    	     
    	     System.out.println();
    	     
    

    All this program does is print out the stats of a warrior and wizard, my question is where it says public static class wizard or warrior how come I need too have the static in there? If I take it out a red like appears under new Warrior(); and the program won't run.

    I have more or less the same program running in visual studio but there was no need for the static :confused:.


  • Registered Users, Registered Users 2 Posts: 6,260 ✭✭✭Buford T Justice


    Static members and classes are available without an instantiating them, hence no need for the new operator. The caveat is that they are not threadsafe.


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    Visual Studio and Java?

    Java doesn't have static classes like that I don't think. I also don't know why those classes would be made static anyway.


  • Registered Users, Registered Users 2 Posts: 7,498 ✭✭✭BrokenArrows


    The reason new Warrior() goes red is because it is no invalid.
    Warrior and Wizard are extending Hero. Hero is static so Warrior and Wizard must also be static.


  • Registered Users, Registered Users 2 Posts: 7,498 ✭✭✭BrokenArrows


    Anima wrote: »
    Visual Studio and Java?

    Java doesn't have static classes like that I don't think. I also don't know why those classes would be made static anyway.

    I think you can install some extension to support java code in VS.
    Java does have static classes but they must be defined inside a non static class.
    Ya there is no reason to make them static at all. Hero, Wizard and Warrior should have the static removed from them.

    @Sephiroth_dude The reason why you dont want them to be static is because you need them to store their own statistics for each instance of warrior.

    If you created two instances of a static warrior called Jim and Bob they would both report the same statistics always.


  • Registered Users, Registered Users 2 Posts: 6,260 ✭✭✭Buford T Justice


    I think you can install some extension to support java code in VS.
    Java does have static classes but they must be defined inside a non static class.
    Ya there is no reason to make them static at all. Hero, Wizard and Warrior should have the static removed from them.

    @Sephiroth_dude The reason why you dont want them to be static is because you need them to store their own statistics for each instance of warrior.

    If you created two instances of a static warrior called Jim and Bob they would both report the same statistics always.

    Hence, thread safety


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Anima wrote: »
    Visual Studio and Java?

    Java doesn't have static classes like that I don't think. I also don't know why those classes would be made static anyway.

    Just too clarify, I'm using eclipse for java and visual studio for c#.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    If you put final static does that mean the value of age never changes?
    final static int age = 24;
    


  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    If you put final static does that mean the value of age never changes?
    final static int age = 24;
    

    Final, means no changes once set. Static means one instance of that object is shared among all instances of the class.


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    Bonus info:

    Declaring a class as final means it can't be inherited.

    Declaring a method as final means that it can't be overridden by an inheriting class.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Remouad wrote: »
    Bonus info:

    Declaring a class as final means it can't be inherited.

    Declaring a method as final means that it can't be overridden by an inheriting class.

    Decent info there Remouad cheers!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Having a problem with the loop in this program, if I choose option 1, 2 or 3 it will just go into continuous loop and won't stop and I have to exit eclipse to get to stop, any idea? I tried a while loop before trying do and same issue.

    int Choice = 0;
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("Please Pick an option by pressing 1,2,3 or 0 to Exit the program");
    		Choice = sc.nextInt();
    		
    		
    		do{
    			
    			
    			switch(Choice)
    			{
    			case 1:
    			System.out.println("Mr.Red");
    			MrRed();
    			break;
    			
    			case 2:
    			System.out.println("Mr.Blue");
    			MrBlue();
    			break;
    			
    			case 3:
    			System.out.println("Mr.Green");
    			MrGreen();
    			break;
    			
    			case 0:
    			System.out.println("Thank you and goodbye!");
    			break;
    			
    			default:
    				System.out.println("Not a vaild selection!");
    				break;
    			
    				
    			}
    		
    		}while(Choice != 0);
    		
    		
    		
    		
    	}
    
    	
    	
    	
    	public static void MrRed()
    	{
    		System.out.println("Hello Mr  Red");
    	}
    	
    	public static void MrBlue()
    	{
    		System.out.println("Hello Mr  Blue");
    	}
    	
    	public static void MrGreen()
    	{
    	    System.out.println("Hello Mr  Green");
    	}
    	
    	
    }
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    if I choose option 1, 2 or 3 it will just go into continuous loop

    int Choice = 0;
    		
    		Choice = sc.nextInt();
    		
    		
    		do{
    			
    			
    		}while(Choice != 0);
    		
    		
    		
    		
    	}
    
    	
    	
    }
    

    You only read in the input once, and then do...while (or while ... do).

    You somehow need to allow the Choice variable to be updated during the loop.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Idleater wrote: »
    You only read in the input once, and then do...while (or while ... do).

    You somehow need to allow the Choice variable to be updated during the loop.

    Should getting the input be within the loop instead of outside it?


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    Should getting the input be within the loop instead of outside it?

    Yep.
    Otherwise the value will be the same for each iteration.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    When I was using visual studio on my last course when you ran a program it would run it via the command prompt, is it possible to do that in eclipse instead of having programs output to the console?


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,764 Mod ✭✭✭✭Sephiroth_dude


    Just wondering lets say you want the user to enter in a username and password in order for them to progress with the program is it possible in java to have an external file with names and passwords and read them in that way? so if the user typed in a name or password and it didn't exist in the external file you'd get an error message? I'm guessing you would need two files? one for passwords and one for usernames?


  • Advertisement
Advertisement