Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
When I use StreamReader` for some reason the file I use isn't read. can I get any help?
I tried deleting the file and putting it in again but it didn't work
line is initialized to "", so the while loop is never entered. The condition should be line != null, not line == null like you currently have.
Your while loop condition is not correct it should be while(line != null), first of all line is initialized to empty string ("") so with current code the loop is never entered, secondary line = b.ReadLine(); should not be null until the file ends - from the StreamReader.ReadLine docs:
Returns String
The next line from the input stream, or null if the end of the input stream is reached.
Also this makes inner check if(line != null) obsolete.
Your while is not correct; just have a look:
...
string line = "";
// line is NOT null (it's empty) that's why
// while will not enter at all
while (line == null)
{
...
}
Let's change while into for, let pesky line (which is declared out of loop, is check in while, in if etc.) be a loop variable:
// Wrap IDisposable into using; do not Close them expplicitly
using (StreamReader b = new StreamReader("students.txt"))
{
...
for (string line = b.ReadLine(); line != null; line = b.ReadLine())
{
if (line == "2") { num2++; }
...
}
...
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
Is there a better way to do this?
var line = sr.ReadLine();
string[] values = line.Split(';');
if (d == "abc"|| d == "def"|| d == "ghi")
{
}
Since I seemed to get an error message regarding this if statement I added && false to every comparison and replaced the == with the equals method, both without positive results, but this turned out irrelevant.
I can recommend this
notice that if d is null no exception is throw
And also you can extend your list for other compare strings if necessary
You do not need to write a large if statement with comparing d for each string
string d = values[10];
var list = new List<string>() { "abc", "def", "ghi" };
if (!list.Contains(d))
{
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am using C# with the Selenium Webdriver. I want to break the loop if the 'if' condition isn't met. My code is below. If the 'if' condition is met I want to continue the loop until it isn't.
for (int i = 0; i < Numara.Items.Count; i++)
{
driveri.Navigate().GoToUrl("https://web.whatsapp.com/send?phone=" + Numara.Items[i].ToString() + "&text=");
Thread.Sleep(3000);
Actions act = new Actions(driveri);
Thread.Sleep(500);
IReadOnlyCollection<IWebElement> rows = driveri.FindElements(By.XPath("//*[#id=\"app\"]/div/span[3]/div/div/div/div/div/div/div[2]/div"));
if (rows == null)
{
...continuation
}
else
{
...if there is an error
rows.ElementAt(0).Click();
}
}
}
This is what you are asking for
if (rows == null)
{
continue;
}
else
{
rows.ElementAt(0).Click();
break;
}
However it'd be better code practice and more efficient to use a while loop implementation instead;
IReadOnlyCollection<IWebElement> rows = null;
bool rowsFound = false;
while (!rowsFound)
{
rows = driveri.FindElements(By.XPath("//*[#id=\"app\"]/div/span[3]/div/div/div/div/div/div/div[2]/div"));
if(rows!=null)
{
rowsFound = true;
}
}
rows.ElementAt(0).Click();
On an unrelated topic, it's also bad practice to be using Thread.Sleep(), unless absolutely necessary. Most, if not all the time you will want to use WebDriverWait implementation. You can find out more about that here: https://seleniumhq.github.io/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Support_UI_WebDriverWait.htm
The OP's issue description is quite confusing
I want to use selenium in c # to close the loop if it fails.
If the error comes out, I want to click on the link and continue the
loop.
If you want to end the loop immediately after encountering an error, use break.
Using continue on the other hand will skip the remaining statements and will go to the next iteration of your loop.
else
{
...if there is an error
rows.ElementAt(0).Click();
break;
}
Away from the topic though , I just noticed your Absolute XPATH usage. Using absolute is not really advisable, be better to use relative-concise and short xpath. An update to webapp, will surely break your xpath's of your script.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So this should be super simple , perhaps indexOf is not the way to go
var incoming = "MDd"; // incoming data
List<string> cities = new List<string>();
cities.Add("MD");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
if(cities.IndexOf(incoming) != 1 )
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
I am seeing "found" with linqpad output , whether it is correct "MD" or "MDd" why? and what do I change to fix this?
From the documentation of IndexOf:
Return Value The zero-based index position of value if that string is
found, or -1 if it is not. If value is String.Empty, the return value
is 0.
When value is not found in the string, it returns -1, otherwise it returns index position, which is greater than or equal to 0. So either check if index is not -1 or check if it >= 0. I personally prefer the latter one:
// if (cities.IndexOf(incoming) != -1)
if (cities.IndexOf(incoming) >= 0)
{
Console.WriteLine("found");
}
This is a typo error. You want to check for -1 rather than 1 in your if statement:
if(cities.IndexOf(incoming) != -1)
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm working on a Trivia C# console game which reads a text file that has a question , answer multiple choices ,the number of the correct choice and answer explanation.There is four question sets .The task is to prompt each question in the file to the console window ,have the user enter the answer then compare the user's answer with the correct one.That should be done for all four questions in the file.
A class that includes question ,multipleAnswewrChoice,correctAnswer and answerExplanation has been created with getters and setters for each field .
What I'm struggle with is how after reading the file ,to assign each question to a certain variable in order to prompt it to the user and also to do this for four sets.
I made an array of size 4 (as I have 4 lines for each question set) to store the lines then assigned each element to each variable above ,but I couldn't figure out how to loop to do the same for all four sets.
The QuestionUnit is the class that contains the question fields.
public void ReadQuestionFile( QuestionUnit unit)
{
string[] arrayReader = new string[4];
string line = "";
int i = 0;
string fileName = "TextFile1.txt";
StreamReader myReader = new StreamReader(fileName);
while ((line = myReader.ReadLine()) != null && i < 4 )
{
arrayReader[i] = line;
// Console.WriteLine(line);
//Console.WriteLine(arrayReader[i]);
i++;
}
unit.M_Question = arrayReader[0];
unit.M_Answers = arrayReader[1];
unit.M_CorrectAnswers = arrayReader[2];
unit.M_Explanation = arrayReader[3];
}
Any ideas about how to do this ?
Because all your data is in the same file, your going to need to take a slightly different approach. Instead of passing in the item to fill out, I would have the function return the list of read questions:
public IEnumerable<QuestionUnit> ReadQuestionFile()
Then, read in a loop until you reach the end of the file. This approach is NOT safe for invalid input, so be careful:
string fileName = "TextFile1.txt";
List<QuestionUnit> readQuestions = new List<QuestionUnit>();
using (StreamReader myReader = new StreamReader(fileName))
{
while (!myReader.EndOfStream)
{
QuestionUnit newQuestion = new QuestionUnit();
newQuestion.M_Question = myReader.ReadLine();
newQuestion.M_Answers = myReader.ReadLine();
newQuestion.M_CorrectAnswers = myReader.ReadLine();
newQuestion.M_Explanation = myReader.ReadLine();
readQuestions.Add(newQuestion);
}
}
return readQuestions;
Basically, you read until the end of the file, reading four lines at a time. You'll get some null values if the input format isn't correct. You don't really need an array here since you can store the values directly in your object, which you then add to the list when you are done populating it (technically you could have done it before as well). Then you return the filled out list to whatever uses it.
You could possibly use a yield return instead of directly adding to a list, but that is a bit of an advanced concept for starting out, and I'm not sure how well it would mesh with the File I/O. It is good to be aware of its existence either way. The only change would be the removal of readQuestions, and the line:
yield return newQuestion;
where the call to Add currently is.
Let me know if I can clarify anything!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I don't know before this asked or not, but I am confuse in below of code block.
CODE 1
if (String.IsNullOrEmpty(control.Text.Trim()))
{
// Code to execute
}
CODE 2
if (control.Text.Trim() == "")
{
// Code to execute
}
CODE 3
if (control.Text.Trim() == null)
{
// Code to execute
}
CODE 4
if (control.Text.Trim() == string.Empty)
{
// Code to execute
}
According to me all are working to me.
I just feeling wonder that what is the different in between in this 4 code block.
Let's start from primitives:
The first block checks if the string control.Text.Trim() is null or String.Empty.
The second block checks if the string control.Text.Trim() is "".
The third block checks if the string control.Text.Trim() is null.
The fourth block checks if the string control.Text.Trim() is String.Empty; this is exactly the same as the second block: "" equals String.Empty.
Fine, that's easy to understand. However, note that String.Trim() will never return null. Thus, the first block is equivalent to control.Text.Trim() == String.Empty. This is same as the second block and the fourth block, again because "" equals String.Empty. The third block will never be hit, ever.
Thus, the first, second and fourth blocks are equivalent to checking if control.Trim the empty string and the third block is useless and impossible to satisfy. Be careful, if control is null or control.Text is null you will hit an exception. Thus, you should strongly consider using `String.IsNullOrWhiteSpace and replacing everything with:
if(control != null && String.IsNullOrWhiteSpace(control.Text)) {
// code to execute
}
(unless you have some sort of guarantee that control is not null, in which case leave off the first part of the if).
More proper would be:
if (String.IsNullOrWhiteSpace(control.Text))
{
// Code to execute
}
that way you avoid null reference exception.
All your examples have the same bug, they will throw exception if variable is null.
You should also see diference between string.empty ("") and null, those are not the same things. Code 4 and code 2 are the same but both would throw if Text is null.
control.Text.Trim() is never going to be null
control might be
control.Text might be
in which case all three versions will blow chunks...
private static bool validControl(Control argControl)
{
return (argControl != null) && (argControl.Text != null) && (argControl.Text.Trim() != ""));
}
if (validControl(control))
{
// code to execute
}
maybe