Java scanner class - What to do in C# - c#

public void checkInt(Scanner MemberNrSC)
{
MemberNrSC = new Scanner(txtMemberNr.getText());
while (!MemberNrSC.hasNextInt())
{
string correctedMemberNr = Interaction.InputBox(null,"Medlemsnummer skal være et nummer, indtast det rigtige");
if (correctedMemberNr == null)
{
MemberNrCancelled = true;
break;
}
txtMemberNr.setText(correctedMemberNr);
MemberNrSC = new Scanner(txtMemberNr.getText());
MemberNrCancelled = false;
}
}
This is my java checker, for if there is only numbers in the textbox..
But as there is no scanner in C# - how would i get this method converted correct?
I have my other methods needing a scanner class - but i was hoping i could have some help in here.
BTW: i am using a visual basic inputbox - as i do not know if there is a similar way in C#.
Thanks in advance ;-)
/Rasmus
Denmark

Try this maybe
class Scanner : System.IO.StringReader
{
string currentWord;
public Scanner(string source) : base(source)
{
readNextWord();
}
private void readNextWord()
{
System.Text.StringBuilder sb = new StringBuilder();
char nextChar;
int next;
do
{
next = this.Read();
if (next < 0)
break;
nextChar = (char)next;
if (char.IsWhiteSpace(nextChar))
break;
sb.Append(nextChar);
} while (true);
while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
this.Read();
if (sb.Length > 0)
currentWord = sb.ToString();
else
currentWord = null;
}
public bool hasNextInt()
{
if (currentWord == null)
return false;
int dummy;
return int.TryParse(currentWord, out dummy);
}
public int nextInt()
{
try
{
return int.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNextDouble()
{
if (currentWord == null)
return false;
double dummy;
return double.TryParse(currentWord, out dummy);
}
public double nextDouble()
{
try
{
return double.Parse(currentWord);
}
finally
{
readNextWord();
}
}
public bool hasNext()
{
return currentWord != null;
}
}
source: https://stackoverflow.com/a/722524/1714342

string Str = txtMemberNr.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
{
// CODE IS HERE
}
else
{
MessageBox.Show("Brugernavn skal kun indeholde tal, prøv igen!", "advarsel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
This was the most simple way - checking whether or not there is an int/string in the textbox field.
I was hoping that you/or someone who have option for making this solved.
Thank you for your help - but i could not make it work as wanted - even though there was good use of the scanner.. thank you.

How about
public static IEnumerable<string> Scanner(this string tgt, char delim)
{
var sb = new StringBuilder();
foreach (var c in tgt)
{
if (c == delim)
{
yield return sb.ToString();
sb.Clear();
}
else sb.Append(c);
}
}

Related

Output binary tree (inorder traversal iterative) doesn't work

I need to output tree. But this output is incorrect.
My tree is:
`
public class ElTree
{
public int L;
public string inf;
public bool PR;
public ElTree(string inf)
{
this.inf = inf;
this.PR = false;
this.L = -1;
}
}
`
Class Tree is (Here other methods that I do with Tree, the method that output Tree in in the end. I`ve also tried to do output with recursion and it work correctly, so method Add() works correctly. But I have a task to do output in iterative way). For example, when I add tree lake "k"-root, "r"-right elem, "l"-left elem then my recursive method output "lkr" but iterative method output just "ll":
`
public class Tree
{
public ElTree[] T;
public int Coun { get { return _count; } }
private int _count;
public Tree(string inf)
{
ElTree temp = new ElTree(inf);
T = new ElTree[1];
T[T.Length-1] = temp;
}
public int Find(int V, string inf)
{
if (V == T.Length) return -1;
if (V != -1)
{
if (T[V].inf == inf) return V;
int temp = Find(T[V].L, inf);
if (temp != -1)
return temp;
return temp = Find(V + 1, inf);
}
return -1;
}
public bool Empty()
{
if (Coun == 0)
{
return true;
}
else
return false;
}
public bool Add(int i, string inf, char s)
{
ElTree temp = new ElTree(inf);
switch (s)
{
case 'L':
if (T[i].L == -1)
{
Array.Resize(ref T, T.Length + 1);
T[T.Length - 1] = temp;
T[i].L = T.Length - 1;
_count++;
return true;
}
else return false;
case 'R':
if (!T[i].PR)
{
Array.Resize(ref T, T.Length + 1);
T[T.Length - 1] = temp;
T[i].PR = true;
_count++;
return true;
}
else return false;
}
return false;
}
public void TreeInStringit(int i, ref string s)//iterative output
{
Stack<int> stack = new Stack<int>();
//int i = 0;
stack.Push(i);
do
{
while (T[i].L != -1 && i < T.Length)
{
i = T[i].L;
stack.Push(i);
}
s += T[i].inf;
while (T[i].PR && i < T.Length)
{
i++;
stack.Push(i);
}
if (stack.Count != 0) stack.Pop();
} while (stack.Count != 0);
}
public void String(int V, ref string s)//recursive output
{
ElTree temp = T[V];
if (temp.L != -1)
String(temp.L, ref s);
s += temp.inf;
if (temp.PR)
String(V+1, ref s);
}
`
When I add tree like root with two elements (one on left side and one on right) it output left side of tree 2 times. But I need output all tree.

How to have multiple argument's in a C# if statement

[That title may be wrong for the question, please inform me if so]
I'm coding a little maths quiz in C#, and I was wondering how to make an if statement that says something similiar to:
"if the user responds with 'this' or ' this'
{
do blahblahblah
}
But I don't know how to say the OR bit in C#, I looked through the C# operators page, but kind of got lost in the technical jargon (I'm a rookie).
This is what I have so far:
Console.WriteLine("What is 200 / 5?");
string sFirstAnswer = Console.ReadLine();
if (sFirstAnswer == "40" || " 40")
{
sUser1Score++;
Console.WriteLine("\n Correct, 200 / 5 = 40. You have been awarded 1 point.");
Console.ReadLine();
}
Write
if (sFirstAnswer == "40" || sFirstAnswer == " 40")
or better yet, trim the answer:
if (sFirstAnswer.Trim() == "40")
if (sFirstAnswer == "40" || sFirstAnswer == "40")
You can create a list of allowed answers and then check it's in the list.
var correctFirstAnswers = new List<string>{"40", " 40"};
if (correctFirstAnswers.Contains(sFirstAnswer))
this is more readable than || when there are multiple possible answers.
I thought I might give an (over-the-top) example of what I meant to make it a bit more Dynamic
A few classes now help to ask you the questions, and with a few functions built around it, you can easily show your questions in a menu format, and then ask the question, with random nr's (only whole number division was a bit more annoying :))
You could make it easier that the Generate method limits the range a bit more, but I just thought I wanted to give you an idea of how it could look like
using System;
using System.Collections.Generic;
namespace MathQuiz
{
class Program
{
interface IExercise
{
string Title { get; }
void Generate();
}
abstract class Exercise<TResult> : IExercise
{
public virtual string Title
{
get
{
return "Exercise";
}
}
public abstract bool isCorrect(TResult reply);
public abstract TResult Solve();
public abstract bool TryParse(string value, out TResult result);
public abstract void Generate();
}
abstract class ExerciseWith2Items<TSource, TResult> : Exercise<TResult>
{
public virtual TSource Item1 { get; set; }
public virtual TSource Item2 { get; set; }
public abstract string Operator { get; }
public override string ToString()
{
return string.Format("{0} {1} {2}", Item1, Operator, Item2);
}
}
abstract class WholeNumberExercise : ExerciseWith2Items<int, int>
{
public override void Generate()
{
Random next = new Random();
Item1 = next.Next(100) + 15;
Item2 = next.Next(100) + 15;
}
public override bool TryParse(string value, out int result)
{
return int.TryParse(value, out result);
}
}
class Division : WholeNumberExercise
{
protected bool IsPrime(int nr)
{
int max = (int)Math.Sqrt(nr);
if (nr <= 2)
{
return true;
}
for (int i = 2; i < max; i++)
{
if (nr % i == 0)
{
return false;
}
}
return true;
}
public override int Item1
{
get
{
return base.Item1;
}
set
{
// primes cannot be divived, so increase the value until we don't have a prime
while (IsPrime(value))
{
value++;
}
base.Item1 = value;
}
}
public override int Item2
{
get
{
return base.Item2;
}
set
{
if (value <= 0)
{
// minimum 2
value = 2;
}
// small override: we only want whole number division, so change the nr to the closest nr that has no rest after division
int closest = 0;
while ((value - closest > 1 && Item1 % (value - closest) != 0) ||
(value + closest < Item1 && Item1 % (value + closest) != 0))
{
closest++;
}
// in case closest == 0, it doesn't really change anything
if (Item1 % (value - closest) == 0)
{
value -= closest;
}
else
{
value += closest;
}
base.Item2 = value;
}
}
public override string Operator
{
get { return "/"; }
}
public override bool isCorrect(int reply)
{
return reply == (Item1 / Item2);
}
public override void Generate()
{
Random r = new Random();
Item1 = r.Next(500) + 100;
Item2 = r.Next(50) + 2;
}
public override int Solve()
{
return (Item1 / Item2);
}
}
class Multiplication : WholeNumberExercise
{
public override string Operator
{
get { return "*"; }
}
public override bool isCorrect(int reply)
{
return reply == (Item1 * Item2);
}
public override int Solve()
{
return (Item1 * Item2);
}
}
class Addition : WholeNumberExercise
{
public override string Operator
{
get { return "+"; }
}
public override bool isCorrect(int reply)
{
return reply == (Item1 + Item2);
}
public override int Solve()
{
return (Item1 + Item2);
}
}
class Subtraction : WholeNumberExercise
{
public override string Operator
{
get { return "-"; }
}
public override bool isCorrect(int reply)
{
return reply == (Item1 - Item2);
}
public override int Solve()
{
return (Item1 - Item2);
}
}
static IExercise ShowMenu(IList<IExercise> exercises)
{
int menu;
do
{
Console.Clear();
Console.WriteLine("Test your match skills :)\r\n");
for (int i = 0; i < exercises.Count; i++)
{
Console.WriteLine("\t{0}\t{1}", i, exercises[i].GetType().Name);
}
Console.WriteLine("\r\n\t99\tExit\r\n");
Console.Write("Please enter your choice: ");
if (!int.TryParse(Console.ReadLine(), out menu))
{
// wrong input
menu = -1;
}
if (menu != 99)
{
if (menu >= exercises.Count)
{
menu = -1;
}
}
} while (menu < 0);
IExercise result = null;
if (menu != 99)
{
result = exercises[menu];
}
return result;
}
static void Solve(IExercise exercise)
{
if (exercise == null)
{
return;
}
if (!(exercise is WholeNumberExercise))
{
Console.WriteLine("Don't know how to solve this exercise, please contact developer :)");
Console.ReadLine();
return;
}
var solvable = exercise as WholeNumberExercise;
solvable.Generate();
Console.Write("{0}: '{1}' = ", solvable.GetType().Name, exercise);
int reply;
bool validAnswerGiven;
do
{
validAnswerGiven = solvable.TryParse(Console.ReadLine(), out reply);
if (validAnswerGiven)
{
if (solvable.isCorrect(reply))
{
Console.WriteLine("Correct!");
}
else
{
Console.WriteLine("Incorrect, the correct result is {0}", solvable.Solve());
}
}
else
{
Console.WriteLine("Please enter valid value (whole number)!");
}
} while (!validAnswerGiven);
Console.ReadLine();
}
static void Main(string[] args)
{
IList<IExercise> potentialExercises = new List<IExercise>()
{
new Addition(),
new Subtraction(),
new Division(),
new Multiplication()
};
IExercise selectedExercise;
do
{
selectedExercise = ShowMenu(potentialExercises);
Solve(selectedExercise);
} while (selectedExercise != null);
Console.WriteLine("Program completed!");
}
}
}
it is runnable code, so copy and paste in visual studio console project should do the trick ;)
In addition to the above you could also try to convert the string to an integer
int number = 0
bool result = Int32.TryParse(Console.ReadLine(), out number);
if (number== 40){
...
}
number will be 0 if conversion fails to int and result false but for your case you dont care its not 40...
MSDN Int TryParse
Since you're validating an answer from an equation, you want to Parse it and get it into a numeric form pronto.
var answer = Convert.ToInt32(sFirstAnswer.Trim());
var expected = 40;
if(answer == expected){
//gold ribbon
}

Return a finite set matching a regex expression

Something similar to http://regexio.com/prototype.html, I'm trying to get a set matching a particular regex.
Basically, you need to parse the regular expression and then, instead of reading input while walking the parsed expression, output the variants.
I have hacked the following program doing what you need for a very simple regular expression (only alternate options using |, iteration using *, grouping using (), and escaping using \ is supported). Note that the iteration is done simply 0–5 times, conversion to possibly infinite iteration left as an exercise for the reader ;-).
I have used a straightforward recursive-descent parser building an abstract syntax tree in memory; this tree is in the end walked and all possible sets are built. The solution is probably not optimal at all, but it works. Enjoy:
public class TestPrg
{
static void Main()
{
var expression = new RegexParser("a(b|c)*d").Parse();
foreach (var item in expression.Generate())
{
Console.WriteLine(item);
}
}
}
public static class EnumerableExtensions
{
// Build a Cartesian product of a sequence of sequences
// Code by Eric Lippert, copied from <http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx>
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}
}
public class RegexParser
{
private const char EOF = '\x0000';
private readonly string str;
private char curr;
private int pos;
public RegexParser(string s)
{
str = s;
}
public RegExpression Parse()
{
pos = -1;
Read();
return ParseExpression();
}
private void Read()
{
++pos;
curr = pos < str.Length ? str[pos] : EOF;
}
private RegExpression ParseExpression()
{
var term = ParseTerm();
if (curr == '|')
{
Read();
var secondExpr = ParseExpression();
return new Variants(term, secondExpr);
}
else
{
return term;
}
}
private RegExpression ParseTerm()
{
var factor = ParseFactor();
if (curr != '|' && curr != '+' && curr != '*' && curr != ')' && curr != EOF)
{
var secondTerm = ParseTerm();
return new Concatenation(factor, secondTerm);
}
else
{
return factor;
}
}
private RegExpression ParseFactor()
{
var element = ParseElement();
if (curr == '*')
{
Read();
return new Repeat(element);
}
else
{
return element;
}
}
private RegExpression ParseElement()
{
switch (curr)
{
case '(':
Read();
var expr = ParseExpression();
if (curr != ')') throw new FormatException("Closing paren expected");
Read();
return expr;
case '\\':
Read();
var escapedChar = curr;
Read();
return new Literal(escapedChar);
default:
var literal = curr;
Read();
return new Literal(literal);
}
}
}
public abstract class RegExpression
{
protected static IEnumerable<RegExpression> Merge<T>(RegExpression head, RegExpression tail, Func<T, IEnumerable<RegExpression>> selector)
where T : RegExpression
{
var other = tail as T;
if (other != null)
{
return new[] { head }.Concat(selector(other));
}
else
{
return new[] { head, tail };
}
}
public abstract IEnumerable<string> Generate();
}
public class Variants : RegExpression
{
public IEnumerable<RegExpression> Subexpressions { get; private set; }
public Variants(RegExpression term, RegExpression rest)
{
Subexpressions = Merge<Variants>(term, rest, c => c.Subexpressions);
}
public override IEnumerable<string> Generate()
{
return Subexpressions.SelectMany(sub => sub.Generate());
}
}
public class Concatenation : RegExpression
{
public IEnumerable<RegExpression> Subexpressions { get; private set; }
public Concatenation(RegExpression factor, RegExpression rest)
{
Subexpressions = Merge<Concatenation>(factor, rest, c => c.Subexpressions);
}
public override IEnumerable<string> Generate()
{
foreach (var variant in Subexpressions.Select(sub => sub.Generate()).CartesianProduct())
{
var builder = new StringBuilder();
foreach (var item in variant) builder.Append(item);
yield return builder.ToString();
}
}
}
public class Repeat : RegExpression
{
public RegExpression Expr { get; private set; }
public Repeat(RegExpression expr)
{
Expr = expr;
}
public override IEnumerable<string> Generate()
{
foreach (var subexpr in Expr.Generate())
{
for (int cnt = 0; cnt < 5; ++cnt)
{
var builder = new StringBuilder(subexpr.Length * cnt);
for (int i = 0; i < cnt; ++i) builder.Append(subexpr);
yield return builder.ToString();
}
}
}
}
public class Literal : RegExpression
{
public char Ch { get; private set; }
public Literal(char c)
{
Ch = c;
}
public override IEnumerable<string> Generate()
{
yield return new string(Ch, 1);
}
}
My answer to a similar question might work for you. If the regex doesn't involve
any * operations (so that the language it recognizes is finite), it should be easy
to rewrite the regex as a BNF grammar, then do a bottom-up analysis producing
the finite sets corresponding to each nonterminal symbol until you reach the
start symbol, at which point you're done.

Odd Reflector Decompile with Invalid Token Error

Would some kind person help me sort out the output of .Net Reflector v6.5 that does not compile? I think that the symbols are out of whack but global search and replace might fix that. I don't get the odd class definition. Ideas?
[CompilerGenerated]
private sealed class <ApplicationTaskIterator>d__0 : IEnumerable<ApplicationTask>, IEnumerable, IEnumerator<ApplicationTask>, IEnumerator, IDisposable
{
private int <>1__state;
private ApplicationTask <>2__current;
public SessionMetrics <>3__sm;
public Dictionary<int, ThreadMetrics> <>7__wrap3;
public Dictionary<int, ThreadMetrics>.ValueCollection.Enumerator <>7__wrap4;
public ApplicationTask <currentTask>5__1;
public ThreadMetrics <tm>5__2;
public SessionMetrics sm;
[DebuggerHidden]
public <ApplicationTaskIterator>d__0(int <>1__state)
{
this.<>1__state = <>1__state;
}
private bool MoveNext()
{
try
{
switch (this.<>1__state)
{
case 0:
this.<>1__state = -1;
Monitor.Enter(this.<>7__wrap3 = ThreadMetrics._allThreadMetrics);
this.<>1__state = 1;
this.<>7__wrap4 = ThreadMetrics._allThreadMetrics.Values.GetEnumerator();
this.<>1__state = 2;
while (this.<>7__wrap4.MoveNext())
{
this.<tm>5__2 = this.<>7__wrap4.Current;
if ((((this.<tm>5__2._managedThread.ThreadState == System.Threading.ThreadState.Stopped) || object.ReferenceEquals(this.<tm>5__2._managedThread, Thread.CurrentThread)) || ((this.<currentTask>5__1 = this.<tm>5__2.CurrentApplicationTask) == null)) || ((this.sm != null) && !this.<currentTask>5__1.CurrentSessionMetrics.SessionGUID.Equals(this.sm.SessionGUID)))
{
continue;
}
this.<currentTask>5__1.Active = !this.<tm>5__2.Suspended;
this.<>2__current = this.<currentTask>5__1;
this.<>1__state = 3;
return true;
Label_010C:
this.<>1__state = 2;
}
this.<>1__state = 1;
this.<>7__wrap4.Dispose();
this.<>1__state = -1;
Monitor.Exit(this.<>7__wrap3);
break;
case 3:
goto Label_010C;
}
return false;
}
fault
{
((IDisposable) this).Dispose();
}
}
}
Used like this:
internal static IEnumerable<ApplicationTask> ApplicationTaskIterator(SessionMetrics sm)
{
return new <ApplicationTaskIterator>d__0(-2) { <>3__sm = sm };
}
That's simply what the C# compiler transforms a method containing yield return statements to.
If you want to make the code compile, you can either try to decipher what the method is doing and recreate the original version with yield return statements; or you can rename the class and all members to valid C# names.
The original method probably looked like this:
internal static IEnumerable<ApplicationTask> ApplicationTaskIterator(SessionMetrics sm)
{
lock (ThreadMetrics._allThreadMetrics)
{
foreach (var tm in ThreadMetrics._allThreadMetrics.Values)
{
if (tm._managedThread.ThreadState != ThreadState.Stopped)
{
if (!object.ReferenceEquals(tm._managedThread, Thread.CurrentThread))
{
ApplicationTask currentTask;
if ((currentTask = tm.CurrentApplicationTask) != null)
{
if (sm == null || !currentTask.CurrentSessionMetrics.SessionGUID.Equals(sm.SessionGUID))
{
currentTask.Active = !tm.Suspended;
yield return currentTask;
}
}
}
}
}
}
}

How can I override TryParse?

I would like to override bool's TryParse method to accept "yes" and "no." I know the method I want to use (below) but I don't know how to override bool's method.
... bool TryParse(string value, out bool result)
{
if (value == "yes")
{
result = true;
return true;
}
else if (value == "no")
{
result = false;
return true;
}
else
{
return bool.TryParse(value, result);
}
}
You can't override a static method. You could however create an extension method.
public static bool TryParse(this string value, out bool result)
{
// For a case-insensitive compare, I recommend using
// "yes".Equals(value, StringComparison.OrdinalIgnoreCase);
if (value == "yes")
{
result = true;
return true;
}
if (value == "no")
{
result = false;
return true;
}
return bool.TryParse(value, out result);
}
Put this in a static class, and call your code like this:
string a = "yes";
bool isTrue;
bool canParse = a.TryParse(out isTrue);
TryParse is a static method. You can't override a static method.
TryParse is a static method and you can't override static methods.
You could always try to create an extension method for strings to do what you want:
public static bool ParseYesNo(this string str, out bool val)
{
if(str.ToLowerInvariant() == "yes")
{
val = true;
return true;
}
else if (str.ToLowerInvariant() == "no")
{
val = false;
return true;
}
return bool.TryParse(str, out val);
}
You cannot override TryParse. However, you could create an extension method on string for convenience.
public static class StringExtension
{
public static bool TryParseToBoolean(this string value, bool acceptYesNo, out bool result)
{
if (acceptYesNo)
{
string upper = value.ToUpper();
if (upper == "YES")
{
result = true;
return true;
}
if (upper == "NO")
{
result = false;
return true;
}
}
return bool.TryParse(value, out result);
}
}
And then it would be used like so:
public static class Program
{
public static void Main(string[] args)
{
bool result;
string value = "yes";
if (value.TryParseToBoolean(true, out result))
{
Console.WriteLine("good input");
}
else
{
Console.WriteLine("bad input");
}
}
}
This is not possible.

Categories

Resources