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,
Vanilla are planning an update to the site on April 24th (next Wednesday). It is a major PHP8 update which is expected to boost performance across the site. The site will be down from 7pm and it is expected to take about an hour to complete. We appreciate your patience during the update.
Thanks all.

Finding smaller number of 2 numbers inputted by user

1356

Comments

  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 79,956 Mod ✭✭✭✭Sephiroth_dude


    Thank you!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 79,956 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 Posts: 6,250 ✭✭✭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 Posts: 5,989 ✭✭✭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 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: 79,956 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 Posts: 6,250 ✭✭✭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: 956 ✭✭✭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: 79,956 Mod ✭✭✭✭Sephiroth_dude


    the return value from the ElectricalCharge method is not handled

    You mean for an exception?


  • Registered Users Posts: 17,486 ✭✭✭✭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: 79,956 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: 79,956 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: 79,956 Mod ✭✭✭✭Sephiroth_dude


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

    You mean like this consolewriteline("" ) ;?


  • Registered Users Posts: 6,250 ✭✭✭Buford T Justice


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


  • Registered Users Posts: 5,989 ✭✭✭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: 79,956 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 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 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: 79,956 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 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: 79,956 Mod ✭✭✭✭Sephiroth_dude


    Thanks alot Remouad!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 79,956 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: 79,956 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 Posts: 6,250 ✭✭✭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 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 Posts: 7,500 ✭✭✭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 Posts: 7,500 ✭✭✭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 Posts: 6,250 ✭✭✭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: 79,956 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#.


Advertisement