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

Finding smaller number of 2 numbers inputted by user

Options
2456

Comments

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


    Not quite sure I understand the question. Since everything is in the main method, all variables that are declared are within scope, so the driverage variable that you read in at the top will still be available at the time you are asking for the claims free driving / at the end of the process.

    Sorry what I meant was after the program does the calculation in the first block of ifs depending on what age range you chose, how do you carry that answer down too the next block so it can take 5% discount off or whatever it may be? atm its just giving me one answer for the first block of ifs and then a separate one for the next, if ya get me?


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


    Sorry what I meant was after the program does the calculation in the first block of ifs depending on what age range you chose, how do you carry that answer down too the next block so it can take 5% discount off or whatever it may be? atm its just giving me one answer for the first block of ifs and then a separate one for the next, if ya get me?
    If I understand you correctly then, you can assign a value to a variable within the condition, within same curly brackets- so if age == 20 then print "stuff";
    newVar = 48;


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


    He gave us another Car insurance exercise where we have too spilt it up in methods, we have too use the same data as the other one I posted, Decided too try and tackle it, below is the age method which is the same as the other one posted, I think it somewhat right, except where you see the ProcessAge in bold it has a red line under and I cant see what I'm doing wrong, if any of ye could have a look and advise I'd be grateful, thanks.

    When I hover over it, it says not all code paths return a value.

    static void Main(string[] args)
            {
                Console.WriteLine(ProcessAge(0.15,0.10,0.22,800,0));
            }
    
            static double [B]ProcessAge[/B](double additionalCharge1, double additionalCharge2, double additionalCharge3,int premium,int age)
            {
                Console.WriteLine("Please enter your age: ");
                int driverAge = int.Parse(Console.ReadLine());
                   
    
                if (driverAge >= 17 && driverAge < 21)
                {
    
                    Console.WriteLine("Your insurance premium is: " + (additionalCharge1 * premium + premium));
                
                }
            
            
            
            }
        
        
        
        
        }
         
    }
    


  • Registered Users Posts: 963 ✭✭✭Greyian


    He gave us another Car insurance exercise where we have too spilt it up in methods, we have too use the same data as the other one I posted, Decided too try and tackle it, below is the age method which is the same as the other one posted, I think it somewhat right, except where you see the ProcessAge in bold it has a red line under and I cant see what I'm doing wrong, if any of ye could have a look and advise I'd be grateful, thanks.

    When I hover over it, it says not all code paths return a value.

    static void Main(string[] args)
            {
                Console.WriteLine(ProcessAge(0.15,0.10,0.22,800,0));
            }
    
            static double [B]ProcessAge[/B](double additionalCharge1, double additionalCharge2, double additionalCharge3,int premium,int age)
            {
                Console.WriteLine("Please enter your age: ");
                int driverAge = int.Parse(Console.ReadLine());
                   
    
                if (driverAge >= 17 && driverAge < 21)
                {
    
                    Console.WriteLine("Your insurance premium is: " + (additionalCharge1 * premium + premium));
                
                }
            
            
            
            }
        
        
        
        
        }
         
    }
    

    The issue with the ProcessAge method is that you have it set up to return a double (static double ProcessAge), but you don't have return any values, you just write to the console.

    Here's an example of how that type of functionality should work:
    static void Main(string[] args)
    {
        int num1 = 1;
        int num2 = 2;
        int sumValue = Sum(num1, num2);
        Console.WriteLine("The sum of " + num1 + " and " + num2 + " is " + sumValue + ".");
    }
    
    static int [B]Sum[/B](int n1, int n2)
    {
        int answer;
        answer = n1+n2;
        return answer;
    }
    

    If your method has a return type (so the double in your ProcessAge example, or the int in my Sum example), you must return a value of that type.

    So just to walk your through how it works:
    • We start in the Main module.
    • We create 2 variables (num1 and num2) and give them values.
    • We then create a 3rd variable (sumValue), and the value of that is the value return from the Sum module.
    • For the Sum module, we require 2 integers as inputs. We are using num1 and num2.
    • So the answer is n1+n2 (or 3).
    • This value is then returned to the main module, and assigned to the sumValue variable.
    • We then write the answer out to the console.


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


    I was just thinking after maybe it was because I had no return values, thank you.


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


    I was just thinking after maybe it was because I had no return values, thank you.

    Visual studio will tell you this if you hover over the red line at the time


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


    If I wanted too put a loop into the program below, would it go in the main method?
    static void Main(string[] args)
            {
                Console.WriteLine("Please enter a number");
                int value = int.Parse(Console.ReadLine());
    
                TestOddOrEven(value);
    
    
                Console.WriteLine("Please enter a mark between 0 - 100: ");
                int mark = int.Parse(Console.ReadLine());
    
                TestResults(mark);
               
    
    
    
            }
            static void TestOddOrEven(int value)
            {
                if (value % 2 == 0)
                {
    
                    Console.WriteLine("Number is even");
    
                }
                else
                {
                    Console.WriteLine("Number is odd");
                
                }
    
                  return;
            
            
            }
    
    
            static void TestResults(int mark)
        
        
        {
           if(mark <= 100 && mark > 85)
        {
          Console.WriteLine("You got an A!");
        }
    
           else if (mark <= 84 && mark > 70)
           {
               Console.WriteLine("You got a B, well done! ");
           
           }
           else if (mark <= 69 && mark > 55)
           {
               Console.WriteLine("You got a C, Not a bad effort! ");
           }
    
           else if (mark <= 54 && mark > 40)
           {
               Console.WriteLine("You got a D, You can do better than that! ");
           }
           else if (mark <= 39 && mark > 25)
           {
               Console.WriteLine("You got an E....Very Poor grade! ");
           }
           else if (mark <= 24 && mark > 0)
           {
               Console.WriteLine("You get no grade!............very poor result! ");
           
           }
           else if (mark <= 0)
           {
               Console.WriteLine("Error invalid number entered! ");
           }
           else if (mark >= 100)
           {
            Console.WriteLine("Error! invalid amount entered! ");
           }     
                
    
    
            return; 
        }
        
    


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


    If I wanted too put a loop into the program below, would it go in the main method?
    static void Main(string[] args)
            {
                Console.WriteLine("Please enter a number");
                int value = int.Parse(Console.ReadLine());
    
                TestOddOrEven(value);
    
    
                Console.WriteLine("Please enter a mark between 0 - 100: ");
                int mark = int.Parse(Console.ReadLine());
    
                TestResults(mark);
               
    
    
    
            }
            static void TestOddOrEven(int value)
            {
                if (value % 2 == 0)
                {
    
                    Console.WriteLine("Number is even");
    
                }
                else
                {
                    Console.WriteLine("Number is odd");
                
                }
    
                  return;
            
            
            }
    
    
            static void TestResults(int mark)
        
        
        {
           if(mark <= 100 && mark > 85)
        {
          Console.WriteLine("You got an A!");
        }
    
           else if (mark <= 84 && mark > 70)
           {
               Console.WriteLine("You got a B, well done! ");
           
           }
           else if (mark <= 69 && mark > 55)
           {
               Console.WriteLine("You got a C, Not a bad effort! ");
           }
    
           else if (mark <= 54 && mark > 40)
           {
               Console.WriteLine("You got a D, You can do better than that! ");
           }
           else if (mark <= 39 && mark > 25)
           {
               Console.WriteLine("You got an E....Very Poor grade! ");
           }
           else if (mark <= 24 && mark > 0)
           {
               Console.WriteLine("You get no grade!............very poor result! ");
           
           }
           else if (mark <= 0)
           {
               Console.WriteLine("Error invalid number entered! ");
           }
           else if (mark >= 100)
           {
            Console.WriteLine("Error! invalid amount entered! ");
           }     
                
    
    
            return; 
        }
        
    

    It really depends on what you want to loop over, and when you want to call the loop......

    can you give some more information?


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


    It really depends on what you want to loop over, and when you want to call the loop......

    can you give some more information?

    When the user enters the input I want the program too loop around again and ask for input again for both questions and I want it too do repeatedly.


  • Registered Users Posts: 974 ✭✭✭Remouad


    When the user enters the input I want the program too loop around again and ask for input again for both questions and I want it too do repeatedly.

    Something like this?
    Give them the option to quit out that doesn't involve ctrl+c.
    I've used inputting q in the example below.
    static void Main(string[] args)
    {
            while(true)
    	{
    		Console.WriteLine("Please enter a number");
    		string value = Console.ReadLine();
    		if(value.Equals("Q",StringComparison.InvariantCultureIgnoreCase))
    		{
    			break;
    		}
    		TestOddOrEven(int.Parse(value));
    
    
    		Console.WriteLine("Please enter a mark between 0 - 100: ");
                    string mark = Console.ReadLine();
                    if (value.Equals("Q", StringComparison.InvariantCultureIgnoreCase))
                    {
                        break;
                    }
    
    		TestResults(int.Parse(mark));
    	}
    
    }    
    


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


    What does break do? Is like the break in a switch statment? never seen it in the context that you wrote it.


  • Registered Users Posts: 974 ✭✭✭Remouad


    break exits the parent loop which in this case is the while loop.

    You can also use continue if you want to skip to the next iteration of the loop.

    Break in a switch statement is to prevent you executing the code in the next case.

    They're basically the same.


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


    When writing methods does it matter if you put public at the start or not? e.g public static void


  • Registered Users Posts: 974 ✭✭✭Remouad


    When writing methods does it matter if you put public at the start or not? e.g public static void

    Yes.

    That is an access modifier

    Basically it defines whether other code can access the method.


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


    When writing methods does it matter if you put public at the start or not? e.g public static void

    As above yes, it does matter. However, for the stage that you're at in learning the chances are all of your methods will begin with public static


  • Registered Users Posts: 974 ✭✭✭Remouad


    As above yes, it does matter. However, for the stage that you're at in learning the chances are all of your methods will begin with public static

    Good point. The modifiers only come into play when your application has multiple classes.


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


    Anyone tell me why this wont print out the "Wrong country entered" when I don't enter in one of the below string variable ? it won't print out the error msg for me at all.
    bool isvalid = false;
                string Country1 = "Ireland";
                string Country2 = "UK";
                string Country3 = "Poland";
    
    
                do
                {
                    try
                    {
    
                        Console.WriteLine("Please enter your Home Country");
                        string country = Console.ReadLine();
    
                        if (Country1 == "Ireland")
                        {
                            Console.WriteLine("Thank you!");
                        }
                        else if (Country2 == "UK")
                        {
                            Console.WriteLine("Thank you");
                        }
                        else if (Country3 == "Poland")
                        {
                            Console.WriteLine("Thank you");
                            isvalid = true;
                        }
    
                        
    
                     
    
    
    
                    }
                    catch (FormatException fe)
                    {
                        Console.WriteLine("Wrong country entered! please try again! ");
                    }
    
    
    
                } while (isvalid == false);
    
            }
        }
    }
    


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


    Country 1,2and 3 conditions are true because you have assigned them values - and are testing those values to see if they are true - what you enter on cmd line is not relevant given that you don't assign that value to any of the variables.

    Sry can't help with the code, only logic


  • Registered Users Posts: 974 ✭✭✭Remouad


    Anyone tell me why this wont print out the "Wrong country entered" when I don't enter in one of the below string variable ? it won't print out the error msg for me at all.
    bool isvalid = false;
                string Country1 = "Ireland";
                string Country2 = "UK";
                string Country3 = "Poland";
    
    
                do
                {
                    try
                    {
    
                        Console.WriteLine("Please enter your Home Country");
                        string country = Console.ReadLine();
    
                        if (Country1 == "Ireland")
                        {
                            Console.WriteLine("Thank you!");
                        }
                        else if (Country2 == "UK")
                        {
                            Console.WriteLine("Thank you");
                        }
                        else if (Country3 == "Poland")
                        {
                            Console.WriteLine("Thank you");
                            isvalid = true;
                        }
    
                        
    
                     
    
    
    
                    }
                    catch (FormatException fe)
                    {
                        Console.WriteLine("Wrong country entered! please try again! ");
                    }
    
    
    
                } while (isvalid == false);
    
            }
        }
    }
    

    1) You should never use exceptions to drive your logic. They should only be used to fail gracefully.

    2) Are you trying to force a FormatException? Your code will not do that.
    Look here for some examples of how to do that
    3)
    You're checking against the variable values not the user input

    should be something like
    if(country.equals(Country1))
    {
      ...... do stuff
    }
    


  • Registered Users Posts: 974 ✭✭✭Remouad


    One more obeservation
    Your loop as is will never exit as the first if will always evaluate to true so you'll never reach the code where you set isvalid = true

    Couple of other tips
    Since isvalid is a bool you don't need to do the comparison in the condition.
    instead do this
                bool invalid=true;
                ....
                do{
                //set invalid to false in here somewhere
                }while(invalid);
    


    Just one other thing to note, which won't make a difference here but is good to know, is the difference between do while and while.
    A while loop checks the condition before executing the logic.
    A do while loop checks the condition after so it always executes at least once even if the condition evaluates to false.


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 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,011 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 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 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,011 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 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,011 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 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,011 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: 963 ✭✭✭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).


Advertisement