I have created a c# program that takes a scan input, and then takes the information from the input. What I have been noticing is that for larger strings, my program for some reason splits the string into two parts (not in half), which screws up the way I get my information. My string has hexadecimal values in it as well.
For example, when I scan a code into my console, it reads the string
[)>065JUN1234567892300167Q205GT21L123 ABC06P123456787Q100PL7Q10PKQ1006P98356877Q100PL7Q5PKQ2006P235265437Q200PL7Q40PKQ5
but it splits that string into:
[)>065JUN1234567892300167Q205GT21L123 ABC06P123456787Q100PL7Q10PKQ1006P98356877Q100"
and
PL7Q5PKQ2006P235265437Q200PL7Q40PKQ5
Any idea how to fix this, or allocate more memory to my variable which reads the console for the input scan?
Here is my code, its kind of long.
static void Main(string[] args)
{
Console.WriteLine("Please enter the date and lane number");
Console.WriteLine("like so: ddmmyylanenumber.");
string lanenum = Console.ReadLine();
Console.WriteLine("When done scanning, please type");
Console.WriteLine("\"finish\" into the console.");
string scanInput;
do
{
Console.Write("Scan now:");
scanInput = Console.ReadLine();
//The number before "JUN" identifies the type of label it is.
int posOfJUN = scanInput.IndexOf("JUN");
//Finding the type of label
string typeOfLabel = scanInput.Substring(posOfJUN - 1, 1);
string label;
if (typeOfLabel == "5")
{
label = "mixed";
}
else if (typeOfLabel == "1")
{
label = "individual";
}
else
{
label = null;
}
switch (label)
{
case "individual":
partNumber = scanInput.Substring(8, 8);
int posOfQ1 = scanInput.IndexOf("Q");
int posOf1JUN = scanInput.IndexOf("1JUN");
//Quantity of the pack
total = scanInput.Substring(posOfQ1 + 1, posOf1JUN - posOfQ1 - 1 - 1);
//number of packs is 1 because individual
numOfPacks = "1";
dunsNumber = scanInput.Substring(posOf1JUN + 4, 9);
//used to find the duns and serial number
posOf20L = scanInput.IndexOf("20L");
posOf21L = scanInput.IndexOf("21L");
//Setting the serial number
if (posOf21L == -1 || posOf20L < posOf21L)
{
serialNumber = scanInput.Substring(posOf1JUN + 4, posOf20L - posOf1JUN - 4 - 1);
}
else if (posOf20L == -1 || posOf21L < posOf20L)
{
serialNumber = scanInput.Substring(posOf1JUN + 4, posOf21L - posOf1JUN - 4 - 2);
}
else
{
serialNumber = null; //else clause if serial number can't be created
Console.WriteLine(new ArgumentException("Error obtaining Serial Number"));
}
partObject part2 = new partObject(partNumber, total, numOfPacks);
newPacks = int.Parse(numOfPacks);
total = total.ToString();
newtotal = int.Parse(total);
part2.callSQL(partNumber, newtotal, newPacks, dunsNumber, serialNumber, lanenum);
break;
case "mixed":
posOfJUN = scanInput.IndexOf("JUN");
dunsNumber = scanInput.Substring(posOfJUN + 3, 9);
int posOf7Q = scanInput.IndexOf("7Q");
posOf20L = scanInput.IndexOf("20L");
posOf21L = scanInput.IndexOf("21L");
//Finding serial number
serialNumber = scanInput.Substring(posOfJUN + 3, posOf7Q - posOfJUN - 3);
//The following lines are to find how many different parts are in the mixed load.
posOfPK = scanInput.IndexOf("PK");
int PKTemp;
int parts = 1;
//Each time a "PK" is seen, it means there is another part so the count increments.
while (scanInput.IndexOf("PK", posOfPK + 1) != -1)
{
PKTemp = scanInput.IndexOf("PK", posOfPK + 1);
posOfPK = PKTemp;
parts++;
}
//Creating an array of size "parts"
int posOf06 = scanInput.IndexOf("06");
int temp06 = scanInput.IndexOf("06", posOf06 + 2);
posOf06 = temp06;
int indexOfP = scanInput.IndexOf("P", posOf06 + 1);
partNumber = scanInput.Substring(indexOfP + 1, 8);
posOfPK = scanInput.IndexOf("PK", indexOfP);
posOfPL = scanInput.IndexOf("PL", indexOfP);
posOf7Q1 = scanInput.IndexOf("7Q", indexOfP);
partObject[] arrayOfParts = new partObject[parts];
for (int i = 0; i < parts; i++)
{
//Finds the different values, creates an object and puts it into the array of parts
partNumber = scanInput.Substring(indexOfP + 1, 8);
total = scanInput.Substring(posOf7Q1 + 2, posOfPL - posOf7Q1 - 2);
numOfPacks = scanInput.Substring(posOfPL + 5, posOfPK - posOfPL - 5);
arrayOfParts[i] = new partObject(partNumber, total, numOfPacks);
//resetting the variables for the next iteration, so a new object can be created with the next part
posOf06 = scanInput.IndexOf("06", temp06 + 1);
indexOfP = scanInput.IndexOf("P", posOf06 + 1);
temp06 = posOf06;
posOfPK = scanInput.IndexOf("PK", indexOfP);
posOfPL = scanInput.IndexOf("PL", indexOfP);
posOf7Q1 = scanInput.IndexOf("7Q", indexOfP);
//putting each object into SQL
newtotal = int.Parse(total);
newPacks = int.Parse(numOfPacks);
serialNumber = serialNumber + "P" + (i + 1);
arrayOfParts[i].callSQL(partNumber, newtotal, newPacks, dunsNumber, serialNumber, lanenum);
}
break;
default:
break;
}
}
} while (scanInput != "finish");
}
The full string is never there right from the start of the code.
If you debug your program I think you will find that the string is all there.
I'm not sure why you think the string is split... a System.String can only hold one string. At some point are you getting a string[] ?
Place a breakpoint after this line scanInput = Console.ReadLine(); and in Visual Studio hover over scanInput, and it will show you the whole string.... or try just printing out the string to show that it is all there.
EDIT: If you're using hexadecimal, try looking up the hex values which cause the anomaly on the ascii table. Perhaps the hex value is resulting in a carriage return or newline.
Related
I am trying to get the last cell address from the excel sheet for merging purposes based on starting address and range using the below code.
I have starting cell address like X and would like to get the end cell address using the given range. For example, starting address is X, and the range is 7, then the end cell address would be AD.
I have tried with the below approach and I am getting wrong end cell address
private static readonly char[] BaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
.Select((c, i) => new { Char = c, Index = i })
.ToDictionary(c => c.Char, c => c.Index);
public static string IntToBase(int value)
{
int targetBase = BaseChars.Length;
// Determine exact number of characters to use.
char[] buffer = new char[Math.Max(
(int)Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];
var i = buffer.Length;
do
{
buffer[--i] = BaseChars[value % targetBase];
value /= targetBase;
}
while (value > 0);
return new string(buffer, i, buffer.Length - i);
}
public static int BaseToInt(string number)
{
_ = number ?? throw new ArgumentNullException(nameof(number));
char[] chrs = number.ToCharArray();
int m = chrs.Length - 1;
int n = BaseChars.Length, x;
int result = 0;
foreach (char c in chrs)
{
x = CharValues[c];
result += x * (int)Math.Pow(n, m--);
}
return result;
}
public static string GetLastCellAddress(string number, int cellCount)
{
int startVal = BaseToInt(number);
return Enumerable.Range(startVal, cellCount).Select(i => IntToBase(i)).Last();
}
And I am using above function like as below
var environmentsLastCellAddress = ExcelBuilderExtensions.GetLastCellAddress(startColumnAddress, spaceTypeLibraryByPropertiesCount);
The above function gives the wrong end address if I have given starting cell address like X and count is 7, and I should get the end cell address as AD instead of I am getting address as BD.
Could anyone please let me know is there anything wrong with the above code? That would be very grateful to me. Many thanks in advance!!
I am hoping the following will work for you.
int to string reference…
Convert an Excel column number to a column name or letter:
string to int reference…
Fastest method to remove Empty rows and Columns From Excel Files using Interop
static void Main(string[] args) {
Console.WriteLine("Start: A + 0: " + GetAddedRange("A", 0));
Console.WriteLine("Start: A + 1: " + GetAddedRange("A", 1));
Console.WriteLine("Start: H + 4: " + GetAddedRange("H", 4));
Console.WriteLine("Start: AA + 26: " + GetAddedRange("AA", 26));
Console.WriteLine("Start: BA + 11: " + GetAddedRange("BA", 11));
Console.WriteLine("Start: CAA + 11: " + GetAddedRange("CAA", 11));
Console.WriteLine("Start: GAA + 11: " + GetAddedRange("GAA", 11));
Console.WriteLine("Start: Z + 11: " + GetAddedRange("Z", 11));
Console.WriteLine("Start: Z - 10: " + GetAddedRange("Z", -10));
Console.ReadKey();
}
private static string ColumnIndexToColumnLetter(int colIndex) {
int div = colIndex;
string colLetter = String.Empty;
int mod = 0;
while (div > 0) {
mod = (div - 1) % 26;
colLetter = (char)(65 + mod) + colLetter;
div = (int)((div - mod) / 26);
}
return colLetter;
}
private static int ParseColHeaderToIndex(string colAdress) {
int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; ++i) {
digits[i] = Convert.ToInt32(colAdress[i]) - 64;
}
int mul = 1;
int res = 0;
for (int pos = digits.Length - 1; pos >= 0; --pos) {
res += digits[pos] * mul;
mul *= 26;
}
return res;
}
private static string GetAddedRange(string startCol, int addedRange) {
int startingCol = ParseColHeaderToIndex(startCol);
return ColumnIndexToColumnLetter(startingCol + addedRange);
}
Also from your second to last comment… X + 7 would be AE… not AD.
If you are in excel, you may also let excel do the job:
Private Function GetColName(ColNr As Integer) As String
Dim parts() As String
parts = Split(Cells(1, ColNr).Address, "$")
GetColName = parts(1)
End Function
Private Function GetColNr(ColName As String) As Long
GetColNr = Range(ColName + "1").Column
End Function
Sub test()
MsgBox GetColName(GetColNr("X") + 7) 'will post AE
End Sub
You may combine this to one function and also add error handling.
So I been working with visual studio and made the program which calculates the SIR model. Once done, it stores the data into an array and writes its into a CSV file. Got it working, however it is not storing my initial values into the array. Any thoughts why?
Here's is the method which allows the user to set the initial conditions: Sj, Ij, and Rj (These are what I want to be added to the Array)
public double SetInit(double Sj, double Ij, double Rj)
{
Console.WriteLine("The variables Suspected (S), Infected (I), and Recover(R) have already been set to {0}, {1}, and {2} respectively. \n", Sj, Ij, Rj);
{
Console.WriteLine("Would you like to reassign the values?[y][n]");
Console.WriteLine("Please enter either y (for yes) or n (for no)");
ConsoleKey response;
do
{
response = Console.ReadKey(false).Key;
if (response != ConsoleKey.Enter)
Console.WriteLine("\n");
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
if (response == ConsoleKey.N)
{
Console.WriteLine("Okay, the conditions wills remain the same\n");
}
if (response == ConsoleKey.Y)
{
Console.WriteLine("Please a assign a value for S");
String Sinput, Iinput, Rinput = "";
Console.WriteLine("");
Sinput = Console.ReadLine();
Sj = Convert.ToSingle(Sinput);
Sj = Math.Round((Double)Sj, 3);
Console.WriteLine("Please a assign a value for I");
Iinput = Console.ReadLine();
Ij = Convert.ToSingle(Iinput);
if (Ij > 0.00)
{
throw new Exception("No initial condition of recovered needs to be l");
}
Rj = Math.Round((Double)Rj, 3);
Ij = Math.Round((Double)Ij, 3);
Console.WriteLine("Please a assign a value for R");
Rinput = Console.ReadLine();
Rj = Convert.ToSingle(Rinput);
if (Rj != 0)
{
throw new Exception("No initial condition of recovered needs to be set to 0.");
}
Rj = Math.Round((Double)Rj, 3);
if (Math.Abs(Sj + Ij + Rj) != 1)
{
throw new Exception("Sum of the initial conditions must equal to 1.");
}
else
{
Console.WriteLine("The new values for S, I, and R are {0}, {1}, and {2} respectively", Sj, Ij, Rj);
}
}
}
return 0;
}
And here is the method which performs the calculation and stores it into the array. Note that xj represents the stepsize, which will also be in stored.
public double[,] Solve()
{
//data plus one
double Sjp1 = 0;
double Ijp1 = 0;
double Rjp1 = 0;
double[,] Array = new double[numsteps, 4];
//values to modify the stepsize
double xj, xjp1;
xj = x0;
Array[0, 0] = 0;
Array[0, 1] = Sj;
Array[0, 2] = Ij;
Array[0, 3] = Rj;
for (i = 0; i < numsteps; i++) //numstep has bee nset to ten
{
//stepsize has been set to 0.001;
xjp1 = xj + Stepsize; //Updates the stepsize
xj = xjp1;//
Array[i, 0] = xj;
Array[i, 1] = Sj;
Array[i, 2] = Ij;
Array[i, 3] = Rj;
//functions used to calculate Suspected, Infected and Recovered
double f1 = FunctionStore.Suspected(Sj, Ij);
double f2 = FunctionStore.Infected(Sj, Ij);
double f3 = FunctionStore.Recovered(Ij);
Sjp1 = Sj + Stepsize * f1;//Updates the value of Suspected
Sj = Sjp1;
Ijp1 = Ij + Stepsize * f2;//Updates the value of Infected
Ij = Ijp1;
Rjp1 = Rj + Stepsize * f3;//Updates the value of Recovered
Rj = Rjp1;
}
return Array;
}
I've been tweaking things for a while now, but having no success. Was considering of just adding the values directly into the method which writes the file but I would ask if there was a more sophisticated approach that I am missing. Let me know if you need more information.
The variables are stored in the SetInit() function only.
The most common way would be to store the variables outside of the function in class variables.
e.g. private double Sj; and then set them inside of SetInit() with this.Sj = Sj;
Based on the code shown.. Am I writing the right coding if i want to compare the data that were being stream in? Basically starting from the part
while(serialPort1.IsOpen)
For instance first string of data received was T 12 29.5 then next string was T 12 29.5 followed by T 20 24.5 and on so.. basically unpredictable what going to be received next.
I want to program to be able to detect/count the number of appearance for the middle value..like...
====================
[number] | [Repeated times]
12 | 2
=================== but when another different number received,
[number] | [Repeated]
20 | 1
=================== the counter for the number will be overwrite and reset whenever a different number was received.
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff");
RxString = serialPort1.ReadLine();
string[] split = RxString.Split('.');
string dp = split[1];
Char c = dp[0];
split[1] = c.ToString();
RxString = split[0] + "." + split[1];
while (serialPort1.IsOpen)
{
string[] number = RxString.Split(' ');
string unit = number[1];
int count = 1;
for(int i = 1; i < unit.Count(); i++)
{
if(unit[i-1] == unit[i])
count++;
else
count = 1;
if(count == 4)
{
//execute some parameters
}
}
}
this.Invoke(new EventHandler(DisplayText));
StreamWriter MyStreamWriter = new StreamWriter(#"C:\Users\acer\Documents\Data3.txt", true);
MyStreamWriter.Write(time + " " + RxString + "\r\n");
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
EDIT V2
Why wont the prog record data which only has count of 1?
string[] number = RxString.Split(' '); //split RxString by ' '
string unit = number[1]; //unit = unit no.
int count = 1;
for (int i = 1; i < unit.Count(); i++)
{
if (unit[i - 1] == unit[i])
count++;
else
{
count = 1;
StreamWriter MyStreamWriter = new StreamWriter(#"C:\Users\acer\Documents\Data3.txt", true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(time + " " + RxString + "\r\n"); //Write time + string
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
You should use a dictionary to store each element and its own count :
var dict = new Dictionary<string, int?>();
while (serialPort1.IsOpen)
{
string[] number = RxString.Split(' ');
string unit = number[1];
if (dict.ContainsKey(unit))
{
if (dict[unit].HasValue)
{
dict[unit]++;
if (dict[unit] == 4)
{
// execute some parameters
dict[unit] = null;
}
}
}
else
{
dict.Add(unit, 1);
}
}
I'd create a special struct for that:
struct DataInfo
{
public string Number { get; set; }
public int Counter { get; set; }
... Other data you require to work with
}
And use either List<DataInfo> or Dictionary<string, DataInfo> to store values;
For example if I have...
string a = "personil";
string b = "personal";
I would like to get...
string c = "person[i]l";
However it is not necessarily a single character. I could be like this too...
string a = "disfuncshunal";
string b = "dysfunctional";
For this case I would want to get...
string c = "d[isfuncshu]nal";
Another example would be... (Notice that the length of both words are different.)
string a = "parralele";
string b = "parallel";
string c = "par[ralele]";
Another example would be...
string a = "ato";
string b = "auto";
string c = "a[]to";
How would I go about doing this?
Edit: The length of the two strings can be different.
Edit: Added additional examples. Credit goes to user Nenad for asking.
I must be very bored today, but I actually made UnitTest that pass all 4 cases (if you did not add some more in the meantime).
Edit: Added 2 edge cases and fix for them.
Edit2: letters that repeat multiple times (and error on those letters)
[Test]
[TestCase("parralele", "parallel", "par[ralele]")]
[TestCase("personil", "personal", "person[i]l")]
[TestCase("disfuncshunal", "dysfunctional", "d[isfuncshu]nal")]
[TestCase("ato", "auto", "a[]to")]
[TestCase("inactioned", "inaction", "inaction[ed]")]
[TestCase("refraction", "fraction", "[re]fraction")]
[TestCase("adiction", "ad[]diction", "ad[]iction")]
public void CompareStringsTest(string attempted, string correct, string expectedResult)
{
int first = -1, last = -1;
string result = null;
int shorterLength = (attempted.Length < correct.Length ? attempted.Length : correct.Length);
// First - [
for (int i = 0; i < shorterLength; i++)
{
if (correct[i] != attempted[i])
{
first = i;
break;
}
}
// Last - ]
var a = correct.Reverse().ToArray();
var b = attempted.Reverse().ToArray();
for (int i = 0; i < shorterLength; i++)
{
if (a[i] != b[i])
{
last = i;
break;
}
}
if (first == -1 && last == -1)
result = attempted;
else
{
var sb = new StringBuilder();
if (first == -1)
first = shorterLength;
if (last == -1)
last = shorterLength;
// If same letter repeats multiple times (ex: addition)
// and error is on that letter, we have to trim trail.
if (first + last > shorterLength)
last = shorterLength - first;
if (first > 0)
sb.Append(attempted.Substring(0, first));
sb.Append("[");
if (last > -1 && last + first < attempted.Length)
sb.Append(attempted.Substring(first, attempted.Length - last - first));
sb.Append("]");
if (last > 0)
sb.Append(attempted.Substring(attempted.Length - last, last));
result = sb.ToString();
}
Assert.AreEqual(expectedResult, result);
}
Have you tried my DiffLib?
With that library, and the following code (running in LINQPad):
void Main()
{
string a = "disfuncshunal";
string b = "dysfunctional";
var diff = new Diff<char>(a, b);
var result = new StringBuilder();
int index1 = 0;
int index2 = 0;
foreach (var part in diff)
{
if (part.Equal)
result.Append(a.Substring(index1, part.Length1));
else
result.Append("[" + a.Substring(index1, part.Length1) + "]");
index1 += part.Length1;
index2 += part.Length2;
}
result.ToString().Dump();
}
You get this output:
d[i]sfunc[shu]nal
To be honest I don't understand what this gives you, as you seem to completely ignore the changed parts in the b string, only dumping the relevant portions of the a string.
Here is a complete and working console application that will work for both examples you gave:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string a = "disfuncshunal";
string b = "dysfunctional";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
{
sb.Append("[");
sb.Append(a[i]);
sb.Append("]");
continue;
}
sb.Append(a[i]);
}
var str = sb.ToString();
var startIndex = str.IndexOf("[");
var endIndex = str.LastIndexOf("]");
var start = str.Substring(0, startIndex + 1);
var mid = str.Substring(startIndex + 1, endIndex - 1);
var end = str.Substring(endIndex);
Console.WriteLine(start + mid.Replace("[", "").Replace("]", "") + end);
}
}
}
it will not work if you want to display more than one entire section of the mismatched word.
You did not specify what to do if the strings were of different lengths, but here is a solution to the problem when the strings are of equal length:
private string Compare(string string1, string string2) {
//This only works if the two strings are the same length..
string output = "";
bool mismatch = false;
for (int i = 0; i < string1.Length; i++) {
char c1 = string1[i];
char c2 = string2[i];
if (c1 == c2) {
if (mismatch) {
output += "]" + c1;
mismatch = false;
} else {
output += c1;
}
} else {
if (mismatch) {
output += c1;
} else {
output += "[" + c1;
mismatch = true;
}
}
}
return output;
}
Not really good approach but as an exercise in using LINQ: task seem to be find matching prefix and suffix for 2 strings, return "prefix + [+ middle of first string + suffix.
So you can match prefix (Zip + TakeWhile(a==b)), than repeat the same for suffix by reversing both strings and reversing result.
var first = "disfuncshunal";
var second = "dysfunctional";
// Prefix
var zipped = first.ToCharArray().Zip(second.ToCharArray(), (f,s)=> new {f,s});
var prefix = string.Join("",
zipped.TakeWhile(c => c.f==c.s).Select(c => c.f));
// Suffix
var zippedReverse = first.ToCharArray().Reverse()
.Zip(second.ToCharArray().Reverse(), (f,s)=> new {f,s});
var suffix = string.Join("",
zippedReverse.TakeWhile(c => c.f==c.s).Reverse().Select(c => c.f));
// Cut and combine.
var middle = first.Substring(prefix.Length,
first.Length - prefix.Length - suffix.Length);
var result = prefix + "[" + middle + "]" + suffix;
Much easier and faster approach is to use 2 for loops (from start to end, and from end to start).
What I basically have is a file that formatted with Name|Value.
There is several different values through the whole file and for each value that matches my if statement I simply want to do total - value and then return the total to do the next calculation, so basically I have a file that is.
1|100
2|200
A|30
B|40
here is what i tried bit it didn't give me what i was looking for, it kept returing alpha and numb as the original value.
int alpha = 1000;
int numb= 500;
int numbtotal = 0;
string[] valu = File.ReadAllLines(subdirectory + "\\" + "values.txt");
foreach (string val in valu)
{
string[] valusplit = val.Split('|');
if(valusplit[0].Equals("1"))
{
numbtotal = Convert.ToInt32(valusplit[1]);
numb = Math.Abs(numb - numbtotal);
}
else if(valueplit[0].Equals("2"))
{
numbtotal = Convert.ToInt32(valusplit[1]);
numb = Math.Abs(numb - numbtotal);
}
}
This basically kept doing 500 - the new valusplit value. When I really wanted to do (500 - 100 = 400) then (400 - 200 = 200) and get the value of 200.
I think that your problem was "splitfilesys" instead of "valusplit" in the "elseif".
int alpha = 1000;
int numb = 500;
int numbtotal = 0;
//string[] values = File.ReadAllLines(subdirectory + "\\" + "values.txt");
string[] values = new String[] { "1|100", "2|200", "A|30", "B|40" };
foreach (string value in values)
{
string[] valueSplit = value.Split('|');
switch (valueSplit[0])
{
case "1":
numb = Math.Abs(numb - Convert.ToInt32(valueSplit[1]));
break;
case "2":
numb = Math.Abs(numb - Convert.ToInt32(valueSplit[1]));
break;
}
}
In your second if statement, you have misspelled valusplit as valueplit. If this code compiles as shown (IE valueplit is indeed a variable defined outside of this code), that would explain why you are getting the wrong result.