|
Hello,
Before starting college two weeks ago I didn't even know what C# was; I had never worked with codes other than HTML customization on Tumblr and Wordpress.com.
An exercise I have for school is to create a program that asks for three numbers, the first an even number, the second an odd number, and the third a number that can be evenly divided by 42. (The exercise isn't graded.) We're practicing methods, and I feel like I have the entire program right, except for this one method that I can't seem to get to work, the Add3Numbers method.
What am I doing wrong?
The Add3Numbers() in bold at the end is the problem. The red line disappears if I insert random numbers – like Add3Numbers(1, 2, 3) – but the program still doesn't run? Without the numbers I get the error "method overload. Method has 0 arguments."
Sorry if some of the {} are out of position. I tried to make them in order, but, I did copy and paste this…
class Program
{
static void Main(string[] args)
{
int Input1 = 0;
int Input2 = 0;
int Input3 = 0;
Input1 = GetFirstInPutFromUser();
Input2 = GetSecondInputFromUser();
Input3 = GetThirdInputFromUser();
int Sum = Add3Numbers(Input1, Input2, Input3);
Console.WriteLine("The sum is " + Sum);
Console.ReadLine();
}
static int GetFirstInPutFromUser()
{
Console.WriteLine("Please enter an even number");
int FirstInput = Convert.ToInt32(Console.ReadLine());
bool FirstRepeat = true;
while (FirstRepeat)
{
if (FirstInput % 2 == 0)
{
return FirstInput;
GetSecondInputFromUser();
}
else
{
FirstRepeat = false;
Console.WriteLine("That number is not an even number. Please try again.");
GetFirstInPutFromUser();
}
} while (FirstRepeat);
}
static int GetSecondInputFromUser()
{
Console.WriteLine("Please enter an odd number");
int SecondInput = Convert.ToInt32(Console.ReadLine());
bool SecondRepeat = true;
while (SecondRepeat)
{
if (SecondInput % 2 >= 1)
{
return SecondInput;
GetThirdInputFromUser();
}
else
{
SecondRepeat = false;
Console.WriteLine("That is not an odd number. Please try again");
GetSecondInputFromUser();
}
} while (SecondRepeat);
}
static int GetThirdInputFromUser()
{
Console.WriteLine("Please enter a number evenly divisble by 42");
int ThirdInput = Convert.ToInt32(Console.ReadLine());
bool ThirdRepeat = true;
while (ThirdRepeat)
{
if ((ThirdInput / 42 == 1) || (ThirdInput / 42 == 2))
{
return ThirdInput;
Add3Numbers();
}
else
{
ThirdRepeat = false;
Console.WriteLine("That number is not evenly divisble by 42. Please try again");
GetThirdInputFromUser();
} while (ThirdRepeat);
}
static int Add3Numbers(int One, int Two, int Three)
{
int Return = One + Two + Three;
return Return;
}
}
}
|
|
|
|
|
The only declaration of Add3Numbers you have in that code is this:
static int Add3Numbers(int One, int Two, int Three)
{
int Return = One + Two + Three;
return Return;
} And you only use it twice, once in your Main method:
int Sum = Add3Numbers(Input1, Input2, Input3);
And once in your GetThirdInputFromUser metyhod:
Add3Numbers();
The first use is fine: the method you declare requires three integers as parameters (that is called it's Signature) and your provide three integer values when you call it.
But the second call is different - you don't supply any parameters at all! So the system looks for methods called Add3Numbers, and can only find one, which needs three integers, and says "No overload takes 0 parameters" (or similar).
It's a bit like applying for a passport: You need to supply a recent photo of yourself, a copy of your birth certificate, and a cheque for £72.50. If you supply all three "parameters" then teh passport issuing authority will send you a passport. If you don't supply any one of them, all you will get back is a rude letter!
The passport office only have a Signature that want's three parameters, they don't define a method signature than has none!
There is also the fun that it couldn't be executed anyway:
if ((ThirdInput / 42 == 1) || (ThirdInput / 42 == 2))
{
return ThirdInput;
Add3Numbers();
} The return on the line above is not conditional; it will always exit the method at that point so any code after that will get an error saying "unreachable code detected".
And don't worry about the bracket alignment: once you get a clean compile, you can hold CTRL and press K, then (still holding CTRL) press D - Visual Studio will reformat the document for you.
But there are quite a lot of things you want to sort out first...your loop in GetThirdInputFromUser is rather odd as well:
while (ThirdRepeat)
{
if ((ThirdInput / 42 == 1) || (ThirdInput / 42 == 2))
{
return ThirdInput;
Add3Numbers();
}
else
{
ThirdRepeat = false;
Console.WriteLine("That number is not evenly divisble by 42. Please try again");
GetThirdInputFromUser();
} while (ThirdRepeat);
That's not the right syntax for a while loop: you don't need the "extra" while at the bottom:
while (ThirdRepeat)
{
if ((ThirdInput / 42 == 1) || (ThirdInput / 42 == 2))
{
return ThirdInput;
Add3Numbers();
}
else
{
ThirdRepeat = false;
Console.WriteLine("That number is not evenly divisble by 42. Please try again");
GetThirdInputFromUser();
} And let's be honest, that's not going to loop anyway because either you will use the return to exit, or you will set ThirdRepeat to false which will exit the loop anyway...
It all looks like "I panicked and wrote down anything" code instead of something you sat down and thought about - I'd suggest that you might be better off leaving this alone and starting from the beginning after thinking carefully about what you are trying to achieve.
The way I would do it is like this:
static void Main(string[] args)
{
int even = GetEvenNumber();
int odd = GetOddNumber();
int divisibleBy42 = GetDivisibleNumber(42);
Console.WriteLine("Even : {0}\nOdd : {1}\nDivisible : {2}", even, odd, divisibleBy42);
}
private static int GetEvenNumber()
{
return -1;
}
private static int GetOddNumber()
{
return -1;
}
private static int GetDivisibleNumber(int divisor)
{
return -1;
}
And then get each method in turn working before moving to the next.
I'd probably write a method that got a number from the user, and call it in each of those three then validate the number to see if it is acceptable...
Little hint on the last one - if you use the Modulus operator "%", you can check for divisibility very easily: if it returns 0, the number is exactly divisible...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Hi ;
1-day in the way I urge the base index with the following code automatically .
result : I get a script error.
2- webbrowser1.scripterrorssuppressed = true; I do not get to do when I command string error as above and wait out the succession button7_click icon () do not get any results when I call the incident.
3- button with Button7 and daily as if I click with the mouse, opening the daily index tabs .
I want to run automatically every time I click here. Waiting for your help in this regard.
private void gunluk_Click(object sender, EventArgs e)
{
HtmlElement aaa = webBrowser1.Document.GetElementById("rtsLink");
foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("aa"))
{
if ((item.OuterHtml.ToLower().Contains("gunluk")) || (item.OuterHtml.ToLower().Contains("günlük")))
{
foreach (HtmlElement childItem in item.Children)
{
if (childItem.TagName == "A")
{
childItem.InvokeMember("Click");
break;
}
}
break;
}
}
}
private void button7_Click(object sender, EventArgs e)
{
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
HtmlElement selectF8 = webBrowser1.Document.GetElementById("ctl00_cphMaster_rtsDashboard").All[1];
for (int i = 0; i < selectF8.Children.Count; i++)
{
if ((selectF8.Children[i].InnerText.ToLower().IndexOf("gunluk endeks") > -1) || (selectF8.Children[i].InnerText.ToLower().IndexOf("günlük endeks") > -1))
{
try
{
selectF8.Children[i].InvokeMember("click");
break;
}
catch (Exception)
{
throw;
}
}
}
}
<div id="ctl00_cphMaster_rtsDashboard" class="RadTabStrip RadTabStrip_Outlook RadTabStripTop_Outlook rtsDashboard" style="width: 700px;">
<div class="rtsLevel rtsLevel1">
<ul class="rtsUL"><li class="rtsLI rtsFirst"><a class="rtsLink Home rtsSelected HomeSelected rtsHoverBefore" href="#"><span class="rtsIn"><span class="rtsTxt">Home</span></span></a></li><li class="rtsLI rtsLast"><a class="rtsLink rtsAfter" href="#"><span class="rtsIn"><span class="rtsTxt">Gunluk Endeks</span></span></a></li></ul>
</div><input id="ctl00_cphMaster_rtsDashboard_ClientState" name="ctl00_cphMaster_rtsDashboard_ClientState" type="hidden" autocomplete="off" value="{"selectedIndexes":["0"],"logEntries":[],"scrollState":{}}">
</div>
|
|
|
|
|
I can appreciate that English is not your first language but your post made no sense at all. I have no idea what you're trying to do and what the problem is.
|
|
|
|
|
GetElementsByTagName needs "DIV" or "INPUT" but not "aa"
Cannot understand your question more to help you
|
|
|
|
|
Hi everyone
Please I need your help, I have this exercise the problem is when i run it I get incorrect results
can someone please tell me what i am doing wrong.
I am trying to take the user input and multiply it by a constant I initialized to 7.
and when I enter input i used 5, it returns 371.
the answer is actually 35.
static void Main(String[] args)
{
Console.WriteLine("Enter your dogs age");
const int years = 7;
int dogAge = Console.Read();
int humanYears = dogAge * years;
Console.Write(humanYears);
Console.ReadKey();
|
|
|
|
|
If you input 5 then 35 would be the answer. I suggest you put a breakpoint and debug the code to see what is happening.
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Thank ryan...for your input
|
|
|
|
|
What you are seeing here is the fact that the value you are getting out of Console.Read is not the value you think you're getting. The value that you are getting out of Console.Read here is 53. This is because 53 is the ASCII code for 5. In other words, you're getting a single character out of Console.Read which you are casting to an integer, which gives you the underlying ASCII value. What you want to do is something like this:
int dogAge;
if (!int.TryParse(Console.Read(), out dogAge)) return; This code does the check to see if the user has entered a number, and converts it to an integer if possible.
|
|
|
|
|
Thank peter i will try that.
|
|
|
|
|
|
It worked , i had to tweak it a bit but it worked. Thanks again
|
|
|
|
|
Ah but tweaking is where the fun is, that is where you learn stuff. Give the answer an upvote if you want to show appreciation.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Hi,
I writing code for send and received data by use UDP client the send data is ok but problem in received data
1- I send this data "S11E"to program and in program display received data in label i see only "S" display in label why not display "S11E"
2- I put received code inside code button this mean cannot received any data until press the button .
can be Mark program that reads data automatically
used this code for recived data
byte[] reciveddata= udpClient.Receive(ref ipend);
string returnData = Encoding.ASCII.GetString(reciveddata);
label3.Text = ""+returnData;
in reciveddata only one byte but I send string data .
where is problem?
my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace etherent_send_and_recive_data
{
public partial class Form1 : Form
{
UdpClient udpClient;
IPEndPoint ipend;
public Form1()
{
InitializeComponent();
udpClient = new UdpClient();
}
private void send_data_through_etherent( string send_data_ETH)
{
byte[] senddataETH = ASCIIEncoding.ASCII.GetBytes(send_data_ETH);
udpClient.Send(senddataETH,4);
}
private void button1_Click(object sender, EventArgs e)
{
int port;
button1.Text = "disconnected";
port = int.Parse(textBox2.Text);
ipend = new IPEndPoint(IPAddress.Parse(textBox1.Text), port);
try
{
udpClient.Connect(ipend);
button1.Text = "Connected";
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString());
}
}
private void switch1_StateChanged(object sender, NationalInstruments.UI.ActionEventArgs e)
{
if (switch1.Value == true) send_data_through_etherent("S11E");
else send_data_through_etherent("S10E");
try
{
byte[] reciveddata= udpClient.Receive(ref ipend);
string returnData = Encoding.ASCII.GetString(reciveddata);
label3.Text = ""+returnData;
}
catch (Exception e1)
{
MessageBox.Show("ERROR");
}
}
}
}
modified 8-May-15 3:51am.
|
|
|
|
|
Your code relies on things we don't have access to, but this worked for me, if it works for you too then maybe analyse the differences (button1 connects and button2 sends)
public partial class Form1 : Form
{
Thread listenThread;
UdpClient udpClient;
IPEndPoint ipend;
bool listening;
public Form1()
{
InitializeComponent();
udpClient = new UdpClient();
}
private void send_data_through_etherent(string send_data_ETH)
{
byte[] senddataETH = ASCIIEncoding.ASCII.GetBytes(send_data_ETH);
udpClient.Send(senddataETH, 4);
}
private void button1_Click(object sender, EventArgs e)
{
int port;
button1.Text = "disconnected";
port = int.Parse(textBox2.Text);
ipend = new IPEndPoint(IPAddress.Parse(textBox1.Text), port);
try
{
udpClient.Connect(ipend);
button1.Text = "Connected";
}
catch (Exception e1)
{
MessageBox.Show(e1.ToString());
}
listenThread = new System.Threading.Thread(StartListening);
listenThread.Start();
}
public void StartListening()
{
UdpClient c = new UdpClient(ipend);
string data = string.Empty;
do
{
byte[] reciveddata = c.Receive(ref ipend);
data = Encoding.ASCII.GetString(reciveddata);
System.Diagnostics.Debug.WriteLine(data);
if (listening)
{
label3.Invoke((MethodInvoker)delegate { label3.Text += data; });
}
} while (data != "exit");
}
private void button2_Click(object sender, EventArgs e)
{
send_data_through_etherent("S11E");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
listening = false;
send_data_through_etherent("exit");
}
}
|
|
|
|
|
Think you Dear for help me
Sir when use your code display error message
in code
UdpClient c = new UdpClient(ipend);
in
public void StartListening()
An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Additional information: The requested address is not valid in its context
How can resolve this problem
Regards
|
|
|
|
|
Make sure the IP is in textbox 1 (127.0.0.1 - it connects to itself), an unused port is in textbox2, then click button2 to connect and button2 to send.
|
|
|
|
|
thank you for Reply
Yes I Put IP in textbox1 and port in textbox2 and for check write
MessageBox.Show(textBox1.Text + " " + textBox2.Text);
and when press button the message display IP and port is correct after that also the program connected successfully
the problem when the program input to StartListening() and stop direct in code
UdpClient c = new UdpClient(ipend);
also I have anther problem the form cannot exit from button x
where the problem ?
|
|
|
|
|
Not sure what's happening TBH, it works on my machine. The listener needs to work for the form to exit properly, if it's not working then it can't listen for the command to stop.
|
|
|
|
|
Sir Now resolve the problem
I write this code
UdpClient c = new UdpClient(textBox1.Text, port);
but no any data received in Lable3
Regards
|
|
|
|
|
For sending data i use sockets a bit like this for UDP
IPEndPoint IPE = new IPEndPoint(IPAddress.Parse(this.ServerIP), this.ServerPort);
this.Soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.Soc.Connect(IPE);
Soc.Send(this.Request, SocketFlags.None);
buffer = new byte[2048];
int Size = Soc.Receive(buffer);
this.Reply = new byte[Size];
Soc.Close();
The server needs to look a bit like this
IP4receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IP4receiveEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), ClientPort);
IP4receiveSocket.Bind(IP4receiveEndPoint);
IPAddress IPA = IPAddress.Parse("0.0.0.0");
byte []Buf=new byte[1024];
whilst (ServiceIsRunning)
{
EndPoint RemoteEndPoint = new IPEndPoint(IPA, 0);
int RequestSize = IP4receiveSocket.ReceiveFrom(Buf, ref RemoteEndPoint);
IP4receiveSocket.SendTo(SomeByteData, RemoteEndPoint );
}
if you are using threads to send then watchout for requests that just hanging even if you set time-outs.
You could try killing the thread using an .Abort() but this won't kill them all so the best way is to use the killing thread to call code like shown below and passing in the socket.
public static void ShutMeDown(Socket Soc)
{
try{Soc.Shutdown(SocketShutdown.Both);} catch {;}
try { Soc.Close(); }catch { ;}
}
Hope this helps
|
|
|
|
|
1. there's lots of precedents in .NET itself for having classes that are non-generic (can be instantiated), and that have static "utility" methods.
2. when you write a generic class like this (deliberately abbreviated) example:
public class Node<T> : IEquatable<Node<T>> where T : IEquatable<T>
{
public List<Node<T>> Nodes { set; get; }
public int Level { set; get; }
public int ID { set; get; }
public T Value { set; get; }
public static Func<Node<T>, Node<T>, bool> GatherFunc;
public static Dictionary<int, List<int>> Gather(Node<T> node, GatherMode gathermode, Func<Node<T>, Node<T>, bool> customfunc = null)
{
}
} 3. The issue is that when you want to invoke those static function in the generic class:
a. you can't use Extension methods with generic classes
b. you have to use a rather elaborate syntax to invoke those methods, like:
var result1 = Node<TestClass>.Gather(XNode, Node<TestClass>.GatherMode.Values);
var result2 = Node<TestClass>.Gather(XNode, Node<TestClass>.GatherMode.Names); c. yes, you can using a 'Using directive statement, for example:
using node = May_1_2015_MultiList.Node<May_1_2015_MultiList.TestClass>; and, as you can see, that requires you fully qualify the references, even though all the classes, including Node, are in the same NameSpace.
Is there any other way to invoke the static methods using a simpler syntax ?
«To kill an error's as good a service, sometimes better than, establishing new truth or fact.» Charles Darwin in "Prospero's Precepts"
modified 8-May-15 9:32am.
|
|
|
|
|
Hi Bill,
not sure if I'm missing your point - but why don't you do something like this?:
public enum GatherMode
{
Values,
Names
}
public class TestClass : IEquatable<TestClass>
{ }
public static class NodeExtensions
{
public static Dictionary<int, List<int>> Gather<T>(this Node<T> node, GatherMode gathermode, Func<Node<T>, Node<T>, bool> customfunc = null)
where T : IEquatable<T>
{
if (func == null)
func = (n1, n2) => n1.GatherFunc<T>(n2);
return null;
}
public static bool GatherFunc<T>(this Node<T> node, Node<T> otherNode)
where T : IEquatable<T>
{
return true;
}
}
public class Node<T> : IEquatable<Node<T> where T : IEquatable<T>
{
private void test()
{
var XNode = new Node<TestClass>();
var result1 = XNode.Gather(GatherMode.Values);
var result2 = XNode.Gather(GatherMode.Names);
}
}
/Sascha
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Thanks for taking the time to reply, Sascha. What you suggest cannot be done:
1. If you declare the static class that holds the static Extension with a generic constraint <T> that would not compile: "Extension method can only be declared in non-generic, non-nested static class."
2. If you declare the static class that holds the static Extension with no generic constraint, then the compiler will throw an error because it cannot resolve the generic parameter.
I view this as similar to the compiler constraint that when you create a dynamic instance of Func, or Action, you have to give it Types which can be resolved: which is actually a very cool feature
«To kill an error's as good a service, sometimes better than, establishing new truth or fact.» Charles Darwin in "Prospero's Precepts"
|
|
|
|
|