This is probably a simple fix, however I've spent a few hours trying to get this code to work. For my homework assignment, I have to open a text file and place it's data in an ArrayList. I did just that, but then I realized that I am required to do so but creating a method called ReadFileAndStoreInArrayList. Now here is where I am having trouble.
{
class Program
{
static void Main(string[] args)
{
*//This string variable "file" is saying it has been
//assigned but never used.*
string file = #"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";
}
*//Here is where I attempted to pass the variable by value*.
public void ReadFileAndStoreInArrayList(string file)
{
ArrayList FamousWords = new ArrayList();
using (StreamReader path = new StreamReader(file))
{
string line;
while ((line = path.ReadLine()) != null)
{
FamousWords.Add(line);
}
}
foreach (string line in FamousWords)
{
Console.Write(line);
}
}
}
}
I am fairly new to this, and I have done my research and still can not find what I am doing wrong. Is it the way I called the method? Note: The code works when placed in one method, however I am required to create a method. I attempted to use just the ReadFileAndStoreInArrayList method but the compiler is making me use the main method as well.
Use static keyword for the method you want to call from your main function, or else you won't be able to call it.
public static void ReadFileAndStoreInArrayList(string file)
{
ArrayList FamousWords = new ArrayList();
using (StreamReader path = new StreamReader(file))
{
string line;
while ((line = path.ReadLine()) != null)
{
FamousWords.Add(line);
}
}
foreach (string line in FamousWords)
{
Console.Write(line);
}
}
And then you can call it just like:
ReadFileAndStoreInArrayList(file);
in your main function which should look like:
static void Main(string[] args)
{
*//This string variable "file" is saying it has been
//assigned but never used.*
string file = #"C:\Users\Latoy\Documents\Schoolwork\IT 232\Unit 5\FamousWords.txt";
ReadFileAndStoreInArrayList(file);
}
You're not actually calling your method anywhere. You're missing a call to:
ReadFileAndStoreInArrayList(file);
Related
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.
/* Excersice: use with stringbuilder
* cat becomes littlecat
* dog becomes littledog
* mouse becomes littlemouse
* words the must be replace by a
* do not use a loop*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Opgavens_leerpad_3_oefening
{
class Program
{
static string Main(string[] args)
{
StringBuilder sb = new StringBuilder();
string dogCat = new string("Can the cat find the mouse without waking the dog.");
static string replacethisstring(string dogCat);
{
hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("dog", "littldog");
hondKat = dogCat.Replace("mouse", "littlemouse");
hondKat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )
Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )
The method declaration ends with ; that’s the reason for CS8112
The Main method has to return void (or ‘int’ )you’ve modified it to string, that’s the reason for CS5001
If you want the program to print the output on the console use:
using System;
....
Console.WriteLine(output)
Your main should have a void as return type. string is not allowed but int is an option (see reference)
You cannot have ; at the end of a function declaration that has a body to it.
You have to declare a variable before you can use it ... string hondKat;
See the use of StringBuilder in the below code instead of string.
namespace Opgavens_leerpad_3_oefening
{
class Program
{
public static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
sb.Append("Can the cat find the mouse without waking the dog.");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine(); // To Stop the Console from closing.
static StringBuilder replacethisstring(StringBuilder dogCat)
{
dogCat = dogCat.Replace("cat", "littlecat");
dogCat = dogCat.Replace("dog", "littldog");
dogCat = dogCat.Replace("mouse", "littlemouse");
dogCat = dogCat.Replace("the", "a");
return dogCat;
}
}
}
}
You can place the function within the Main or outside. Normally you would find functions outside of the Main class.
public static void Main(string[] args)
{
...
}
public static string replacethisstring(string dogCat)
{
...
}
Having several issues like typos, syntax error etc.
Additionally, the excercise having a condition that needs to use with stringbuilder.
So, try this.
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("Can the cat find the mouse without waking the dog?");
sb = replacethisstring(sb);
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
static StringBuilder replacethisstring(StringBuilder dogCat)
{
StringBuilder hondKat = dogCat.Replace("cat", "littlecat");
hondKat = dogCat.Replace("the", "a");
hondKat = dogCat.Replace("dog", "littledog");
hondKat = dogCat.Replace("mouse", "littlemouse");
return hondKat;
}
Rookie here so please be nice!! I have had so much fun learning to program and gotten some great help along the way when google failed me. But alas, I'm stuck again.
I have a C# program that looks like this (It's MWS if anyone is familiar)
I've tried so many different ways to get this to effectively loop through a list of values in a text file. The problem I'm having is that the Main function is where I have to set the loop, but the BuildClass is where I need to cycle through the values in the text file (sentinel). I've included some stuff that probably isn't necessary just in case it is messing my code up and I don't realize it.
Here's what I've tried:
setting the loop inside the BuildClass - didn't expect it to work but it threw an exception before getting to the sentinel.
Reference the sentinel within the main function by changing the "using" or "var" in the main function sentinel to public - turned EVERYTHING red in visual studio
moving the string sentinel outside the main function so that the function and the BuildClass would recognize it - main function did not recognize it anymore.
I've tried so many other things unsuccessfully. I've gotten it to loop with the same sentinel value passed from BuildClass to the function over and over again but that's about it.
What I think I need:
A destructive version of streamReader that will remove the value from the text file when reading it. I'll put this inside the BuildClass, so that the next loop of the main function, the next value will be read and passed into the main function until the file is empty, terminating the loop.
an understanding of why changing sentinel to public destroys the code so badly. I have a decent understanding of why the other attempts wouldn't work.
namespace MainSpace
{
public class MainClass
{
int i;
public static void Main(string[] args)
{
ClientClass client = new ClientInterface(appName, appVersion, password, config);
MainClass sample = new MainClass(client);
string sentinel;
using (var streamReader = new StreamReader(#"sample.txt", true))
while((sentinel = streamReader.ReadLine()) != null)
{
try
{
//stuff
response = sample.InvokeBuild();
Console.WriteLine("Response Stuff");
string responseXml = response.ToXML();
Console.WriteLine(responseXml);
StreamWriter FileWrite = new StreamWriter("FileTest.xml", true);
FileWrite.WriteLine(responseXml);
FileWrite.Close();
}
catch (ExceptionsClass)
{
// Exception stuff
throw ex;
}
}
}
private readonly ClientInterface client;
public MainClass(ClientInterface client)
{
this.client = client;
}
public BuildClass InvokeBuild()
{
{
using (var streamReader = new StreamReader("sample.txt", true))
{
string sentinel = streamReader.ReadLine();
Thread.Sleep(6000);
i++;
Console.WriteLine("attempt " + i);
// Create a request.
RequestClass request = new RequestClass();
//Password Stuff
request.IdType = idType;
IdListType idList = new IdListType();
idList.Id.Add(sentinel);
request.IdList = idList;
return this.client.RequestClass(request);
}
}
}
}
I am making a windows application.
At first I declared var and it contains another class method.
var ExtList = ExtTarget.GetExtTargets();
And GetExtTargets() is like this
public static List<ExtTarget> GetExtTargets()
{
var dt = SqlHelper.ExecuteDataTable(QueryHelper.ConnectionString,
#"
SELECT [seq],[SourceKind],[ExtKind],[DBKind],[ConnectionString]
,[FilePath],[TableName],[FileKind],[RowSplitter],[ColumnSplitter]
,[Title],[GroupName],[SyncOrder],[RepeatKind],[RepeatMonth]
,[RepeatDay],[RepeatHour],[RepeatMin],[RepeatWeek],[RepeatWeekNum]
,[LastSyncExecDate]
FROM [ExtTarget]
order by GroupName,SyncOrder");
return dt.Rows.Cast<DataRow>().Select<DataRow, ExtTarget>(a => ExtTarget.RowToModel(a)).ToList();
}
Then, I used it to foreach and then I want to pass Ext to another method's parameter.
Code is like this.
public void ProcessExtSync(object obj)
{
while (IsProcessGoing)
{
Thread.Sleep(ThreadDelay);
if (!IsProcessGoing) return;
var ExtList = ExtTarget.GetExtTargets();
foreach (var Ext in ExtList) // I want to use this Ext as parameter
{
while (IsSourceSyncGoing)
{
Thread.Sleep(ThreadDelay);
}
IsExtSyncGoing = true;
bool ExtSyncForceToRun = ConfigSettingHelper.Instance.IsServiceConfig(Words.ExtSyncForceToRun);
bool ExtSyncForceToRunOnlyError = ConfigSettingHelper.Instance.IsServiceConfig(Words.ExtSyncForceToRunOnlyError);
bool ExtSyncNeedToRun = ConfigSettingHelper.Instance.GetNextExecutingTime(Ext) < DateTime.Now;
if (ExtSyncForceToRun || ExtSyncNeedToRun)
{
//I want to pass Ext as parameter to this method
ServiceProcess.Instance.SyncExt();
if (ExtSyncForceToRun)
{
ConfigSettingHelper.Instance.SetServiceConfig(Words.ExtSyncForceToRun, false);
}
if (ExtSyncForceToRunOnlyError)
{
ConfigSettingHelper.Instance.SetServiceConfig(Words.ExtSyncForceToRunOnlyError, false);
}
}
if (!IsProcessGoing) return;
}
IsExtSyncGoing = false;
}
}
How can I modify that code? Please help me.
var is just a shortcut way of implicitly typing a variable. It saves some typing, but sometimes makes code harder to read when the reader can't determine the type. The compiler can figure out the strong type, though (or you'll get a compiler error), and if you hover over it in Visual Studio, the compiler will tell you the actual type.
With that out of the way, all you need to do is make sure that the method you want to pass your variable to takes in the type that you want to pass it (remember the type is not var, but in your case it is an ExtTarget).
The method you're calling should have a signature similar to this (although it may return any type):
public void SyncExt(ExtTarget extTarget)
{
// Implementation code here
}
Then in your code above you can call:
ServiceProcess.Instance.SyncExt(Ext);
I'm new to C#. I wrote a foreach loop,but how can I recall the variables outside the loop. Thanks for your help.
Here is my code:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element in IDico.Keys)
{
var outPut=IDico[element]
}
}
var call=outPut // How can I call outPut outside the for loop?Because the outPut doesn't exist for this row.
}
This is your code
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut=IDico[element]
}
}
//Do stuff with outPut
}
however i think you may be trying to find tempo in the dictionary so really you should just do this:
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
float outPut = 0.0;
if(IDico.Contains(tempo))
{
outPut=IDico[tempo];
}
//Do stuff with outPut
}
static void Main(string[] args)
{
IDictionary<string,float> IDico=new Dictionary<string,float>();
IDico.Add("D1",1);
IDico.Add("D2",2);
IDico.Add("D3",3);
string tempo="D2";
string outPut = string.Empty;
foreach(var element in IDico.Keys)
{
if(tempo.Contains(element))
{
outPut = IDico[element]
}
}
var call = outPut;
}
If outPut can contain more than one element from your dictionary consider using and array or list. If you want to stop iterating after you find a match use a break; in the if statement so that after the match is found the loop will stop.
Also, you're going to want to declare outPut outside of loop so it doesn't re declare itself on each iteration of the loop.
I also fixed the contains statement for you as well as you were using improper syntax.
I'm new to C# programming and I'm trying to use good code practices. I know it is poor coding to use global variables in my example below, but I'm having a hard time figuring this out. So,I'm trying to accomplish two things with this question.
first of all, I am trying to figure out how to pass the text from a multi-line textbox to a function and have it return an array that I can then pass to another function for output (display/printing/saving to a file).
Second, Make my code more re-usable (by moving the globals inside the function that they are actually used in).
My question is.. How do I pass a string to a function and return an array that can then be passed to another function?
public partial class Form1 : Form
{
string[] SignalStrengthInputArray450;
string[] SignalStrengthOutputVar450 = new string[7];
// cut out other functions
private void Submit_450_Click(object sender, EventArgs e)
{
// ensure that input textbox is not null then call Load function
// SignalStrenthInput_450 is the object name of a multi-line textbox
if (!String.IsNullOrWhiteSpace(SignalStrengthInput_450.Text))
{
Load_Signal_Strength_Array();
}
else
{
// do something different
}
// additonal code for other textboxes
}
private void Load_Signal_Strength_Array()
{
// Processing Signal Strength textbox
SignalStrengthInputArray450 = SignalStrengthInput_450.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string a in SignalStrengthInputArray450)
{
// loads some stuff into the SignalStrengthOutputArray450 array
}
}
}
You need a parameter and return type (string array), you may need to read more about Passing Parameters and return statement for returning values.
private string[] Load_Signal_Strength_Array(string signalStrengthInput_450)
{
string[] SignalStrengthInputArray450 = SignalStrengthInput_450.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string a in SignalStrengthInputArray450)
{
// loads some stuff into the SignalStrengthOutputArray450 array
}
return SignalStrengthInputArray450;
}
Method call would be like
string[] signalStrengthArray = Load_Signal_Strength_Array(SignalStrengthInput_450.Text);
You can return array from function:
public string[] f1(string s)
{
return s.Split('/');
}
You can pass return value to anoter function:
public void f2(string[] p)
{
foreach(var item in p)
Console.WriteLine(item);
}
Use like:
public void main()
{
f2(f1("some/delimited/string");
}
Why not
have the Load_Signal_Strength_Array be a function which takes a local string as a parameter and return the reprocessed output (as array here but IList could be better)
call this function with a simple Load_Signal_Strength_Array(SignalStrengthInput_450.Text)
Example:
private string[] Load_Signal_Strength_Array(string text)
{
// Processing text
var inputs = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
var outputs = new List<string>();
foreach (string a in inputs)
{
// loads some stuff into the output array
// example:
if (!string.IsNullOrEmpty(a)) outputs.add(a);
}
return outputs.ToArray();
}