/// <summary> /// Prompts the user for the coefficients of a polynomial, and sets the /// the coefficientList field of the object. /// The isValidPolynomial method is used to check for the validity /// of the polynomial entered by the user, otherwise the field must /// not change. /// The acceptable format of the coefficients received from the user is /// a series of numbers (one for each coefficient) separated by spaces. /// All coefficients values must be entered even those that are zero. /// </summary> /// <returns>True if the polynomial is succeffully set, false otherwise.</returns> public bool SetPolynomial() { //instruction Statement. Console.WriteLine("\nEnter all coefficients for the polynomial seperted by a space (descending order).\nExample: Enter 2 0 3.5 -2 0 for the polynomial (2)*x^4 + (3.5)*x^2 + (-2)*x"); //Converts the input to a char array in order to use DigitReader method from the Arithmatic class. string input = Console.ReadLine(); char[] arr = input.ToCharArray(); //checks for validity, and allows overwriting the set polynomolial. if (IsValidPolynomial(input) && input.Length != 0) { coefficientList.Clear(); } else { return(false); } for (int index = 0; index < arr.Length; index++) { if (arr[index].Equals('-') && Char.IsDigit(arr[index + 1]) && (index == 0 || !char.IsDigit(arr[index - 1]))) { index++; coefficientList.Add(-Arithmetic.DigitReader(arr, ref index)); } else if (Char.IsDigit(arr[index])) { coefficientList.Add(Arithmetic.DigitReader(arr, ref index)); } else if (!char.IsWhiteSpace(arr[index])) { return(false); } } return(true); }
/// <summary> /// Checks if the passed polynomial string is valid. /// The acceptable format of the coefficient string is a series of /// numbers (one for each coefficient) separated by spaces. /// </summary> /// <example> /// Examples of valid strings: "2 3.5 0 ", or "-2 -3.5 0 0" /// Examples of invalid strings: "3..5", or "2x^2+1", or "a b c", or "3 - 5" /// </example> /// <param name="polynomial"> /// A string containing the coefficient of a polynomial. The first value is the /// highest order, and all coefficients exist (even 0's). /// </param> /// <returns>True if a valid polynomial, false otherwise.</returns> public bool IsValidPolynomial(string polynomial) { char[] arr = polynomial.ToCharArray(); for (int index = 0; index < arr.Length; index++) { //DigitReader is used although the return is not save because of its reference index function. if (arr[index].Equals('-') && Char.IsDigit(arr[index + 1]) && (index == 0 || !char.IsDigit(arr[index - 1]))) { index++; Arithmetic.DigitReader(arr, ref index); } else if (Char.IsDigit(arr[index])) { Arithmetic.DigitReader(arr, ref index); } else if (!char.IsWhiteSpace(arr[index])) { return(false); } } return(true); }