Loop program if user enters wrong input - .net-core

I just started learning C# and while loops are confusing me. Unlike Java, where I can use a while loop to loop a program if a user entered a invalid input, it's not acting the same way in C#.
using System;
namespace first {
class Program {
static void Main(string[] args) {
Console.WriteLine("Hi! What is your name");
string userName = Console.ReadLine();
Console.WriteLine("oh! you are:" + userName);
Console.WriteLine("let play a game");
string answer="Y";
while (answer == "Y") {
Random random = new Random();
int correntNumber = random.Next(1, 2);
int guess = 0;
Console.WriteLine("Guess a number");
while (guess != correntNumber) {
string userGuess = Console.ReadLine();
//validate input method 1
try {
guess = int.Parse(userGuess);
} catch (Exception e) {
Console.WriteLine("Invalid inout", e);
}
//validate input method 2
//if(!int.TryParse(userGuess, out guess)) {
// Console.WriteLine("invalid input");
//}
if (guess != correntNumber) {
Console.WriteLine("try again!");
}
}
Console.WriteLine("Yes! corrector");
Console.WriteLine("Play again?");
//string answer;
answer = Console.ReadLine().ToUpper();
if(answer == "Y") {
continue;
} else if (answer == "N") {
Console.WriteLine("bye");
return;
} else if (answer != "Y" || answer != "N") {
Console.WriteLine("y or n");
answer = Console.ReadLine().ToUpper();
continue;
}
}
}
}
}
When I enter a value other than y or n, the message appears,Console.WriteLine("Y or n only");, but the game restarts while it shouldn't.
I am sorry this is a simple and rather silly question, but I can't pin point where I am going wrong.

the problem is that after printing to the user "y or n only" message you take the input but you don't actually do anything with it
so the loop just restarts regardless of the input , to fix this issue you could replace the last if part with this code
while(answer != 'Y' && answer != 'N'){
Console.WriteLine("y or n only");
answer = Convert.ToChar(Console.ReadLine().ToUpper());
}
if(answer == 'Y')
{
continue;
}
else if(answer == 'N')
{
Console.WriteLine("goodbye");
return;
}
so after you read the first input answer of him for repeating or no you check if it's a valid input or not and if it's not you keep asking him for "y or n only" till he enters "Y" or "N" and then you process this answer for whether it's a "Y" or "N" in the if part

Related

printf("%s",stringName) prints the wrong text but only once

I have a menu function, in which I input a question and two options, then the user choses one. It works just fine everytime but one ; I call
if (menu("ou est le corps?","interieur ","exterieur")==1)
{
but instead of printing "interieur " It shows "p?"
it works just fine without the space, but I need to make a space and \n does quite the same thing.
I have another call of this function, with \n which works fine so I have no idea about why this wouldn't work. Anyone has got an idea?
PS : the value of choix1 is then sent via bluetooth, and there it stays intact.
PPS : tell me if something is unclear, I'm not naturally english
PPPS(sorry) : tried to run the same code again, it seems to print a random character followed by "?", I had twice "p?", once "?" and once " '?"
[updates] once "#?"
int menu (String texte, String choix1, String choix2)
{
envoye = 0;
rxValue = "0";
while (digitalRead(M5_BUTTON_HOME) != LOW && rxValue == "0")
{
heure();
M5.Lcd.setTextSize(2);
M5.Lcd.print(texte);
M5.Lcd.printf("\n");
if (selec == 0)
{
M5.Lcd.printf("->%s %s", choix1, choix2);
}
else
{
M5.Lcd.printf(" %s ->%s", choix1, choix2);
}
if (M5.BtnB.read() != 0)
{
if (selec == 0)
{
selec = 1;
}
else
{
selec = 0;
}
while (M5.BtnB.read() != 0)
{
if(digitalRead(M5_BUTTON_HOME) == LOW)
{
M5.Lcd.fillScreen(BLACK);
delay(1000);
if(digitalRead(M5_BUTTON_HOME) == LOW)
{
choix=50;
heure();
delay(1000);
return 1;
}
}
}
}
if (deviceConnected && envoye == 0)
{
sendchoix(texte, choix1, choix2);
envoye++;
}
}
if (rxValue != "0")
{
recuble = &rxValue[0];
selec = atoi(recuble) - 1;
rxValue = "0";
}
M5.Lcd.fillScreen(BLACK);
delay(300);
return selec;
}
int menu (String texte, String choix1, String choix2) {
[...]
M5.Lcd.printf("->%s %s", choix1, choix2);
You cannot treat String objects as const char*, which is what the format specifier %s is expecting. String is an Arduino class for storing.. strings/character data, but an object of this class is not equivalent to the raw pointer to the data.
For that, you need to call the c_str() method on the String object to get the C-String pointer to the data, as shown in the documentation [1].
[..]
M5.Lcd.printf("->%s %s", choix1.c_str(), choix2.c_str());
[..]
[1] https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/c_str/

How can i get columns added on column?

heres my code below...
TableColumn tc = new TableColumn();
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}
and i try to override commit method for editing cells.
public void commit(Object val) {
// Get the table
TableView<MainTable> t = this.getTableView();
// Get the selected row/column
MainTable selectedRow = t.getItems().get(this.getTableRow().getIndex());
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
// Get current property name
String propertyName = ((PropertyValueFactory) selectedColumn.getCellValueFactory()).getProperty();
// Create a method name conforming to java standards ( setProperty )
propertyName = ("" + propertyName.charAt(0)).toUpperCase() + propertyName.substring(1);
// Try to run the update
try {
// Type specific checks - could be done inside each setProperty() method
if(val instanceof Double) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, double.class);
method.invoke(selectedRow, (double) val);
}
if(val instanceof String) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, String.class);
method.invoke(selectedRow, (String) val);
}
if(val instanceof Integer) {
Method method = selectedRow.getClass().getMethod("set" + propertyName, int.class);
method.invoke(selectedRow, (int) val);
}
} catch (Exception e) {
e.printStackTrace();
}
// CommitEdit for good luck
commitEdit((String) val);
}
and i got ArrayIndexOutofBoundsException on console view.
so my question is
how can i select getcolumns added other column???
TableColumn<MainTable, ?> selectedColumn = t.getColumns().get(t.getColumns().indexOf(this.getTableColumn()));
i think this code has to be changed...
anyone got ideas??
Nested columns are not part of the TableView.columns list.
If you need the corresponding TableView column, just go up through the hierarchy until you reach a column without a parentColumn:
TableColumn<MainTable, ?> selectedColumn = this.getTableColumn();
TableColumn<MainTable, ?> c = selectedColumn;
while ((c = selectedColumn.getParentColumn()) != null) {
selectedColumn = c;
}
If you just need the column itself, simply use this.getTableColumn(), instead of finding the index of the column in the columns list and then accessing that index in the same list. (I guess the latter is what you need.)
Furthermore, if PropertyValueFactory returns properties of the item class, you could use this property to set the value instead of using reflection:
ObservableValue obs = selectedColumn.getCellObservableValue(this.getIndex());
if (obs instanceof WritableValue) {
((WritableValue) obs).setValue(val);
} else {
// reflecitive approach
}
Furthermore you shouldn't add null as a nested column, but you're doing it here:
TableColumn[] tc2 = new TableColumn[10];
for(int i=0; i<5, i++){
tc.getColumns().add(tc2[i]);
}

How to check for a specific value in List<T> foreach loop

Need help checking for a specific value in List<T> foreach loop. If there is specific value then display a specific string value.
For example how do I…
If (value.something_2 == "Null")
{
value.something_2 == ".";
}
Elseif (value.something_2 == " ")
{
value.something_2 == "0";
}
How would I incorporate the above example within the “foreach” loop?
See code below.
protected void MyReport(string filename, IMyRepository repository)
{
using (FileStream fileStream = new FileStream(Server.MapPath(#"~/Includes/") + filename, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
List<Report> _report = repository.GetMyReport().ToList();
foreach (var value in _report)
{
String row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_1,
values.something_2,
value.something_3);
String row02 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}",
value.somthing_4,
values.something_5,
value.something_6);
Writer.WriteLine(row01);
Writer.WriteLine(row02);
}
}
writer.Close();
}
}
There is no clever built-in String.Format that you can do for this if that's what you have in mind. However, the compiler has some tricks that can reduce the amount of code you need to write e.g.
// if it's null, assign it to "."
var s2 = value.something_2 ?? ".";
// it can never be null here, so if there is whitespace default to "0"
value.something_2 = String.IsNullOrWhitespace(s2) ? "0" : s2;
If I'm understanding what you're saying, it might be easier just to have another function returning the (possibly) modified string and just pass each of your values into it, inline.
Sting row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 8}", myFunc(value.somthing_1), myFunc(values.something_2), myFunc(value.something_3));
and then have this in the same class
private string myFunc(string something){
if (something == “Null”){
return “.“;
} else if (something == “ “) {
return “0”;
} else {
return something;
}
}

Acknowledge Multiple parallel.foreach loop

I have around 450K records in the database on which I have to make a Fuzzy match. I have implemented the Parallel.foreach loop to see if incoming request is matching with any of the 450K records. If during the search I found any match, I stop the foreach loop and give response back to caller with true (It says that match has been found).
I am calling database and store all the 450K records in static object (in memory). The logic for Parallel.foreach is working good. The problem is that it takes almost 40-45 seconds to determine whether it is match or not.
I am planning to run multiple parallel.foreach for 100k data on each loop so that overall time is reduced. My challenge is how would I Stop the execution of other parallel.foreach loops once I get match on one parrallel.foreach?
Below is my code for a single parallel.foreach:
public bool Checkmatch(CheckRequest request)
{
bool isPCCMatch = false;
//This will load all the data in Static object to avoid db call for each request
PolicyInformation.Initialize(request.IsCacheRefresher);
try
{
logger.Debug(MethodBase.GetCurrentMethod().Name + ": Matching alogorithm is started");
Parallel.ForEach(PolicyInformation.Policies, (policy, loopState) =>
{
double state=0, stateF=0;
if (!request.stateF)
{
state= GetPrecentageMatch(request.state, policy.state);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (state== OneFieldSSNPercentage)
{
isPCCMatch = true;
loopState.Stop();
}
}
else
{
stateF= GetPrecentageMatch(request.stateF, policy.stateF);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (stateF== OneFieldFEINPercentage)
{
isPCCMatch = true;
loopState.Stop();
}
}
double SEIN = GetPrecentageMatch(request.SEIN, policy.FEIN);
//this if condtion is for checkibnf first field condtion earily so that it will not get all the perecentage
if (SEIN == OneFieldSEINPercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double WCIRB = GetPrecentageMatch(request.WCIRB, policy.WCIRB);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (WCIRB == OneFieldWCIRBPercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double DUN = GetPrecentageMatch(request.DUNS, policy.DUNS);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (DUN == OneFieldDUNSPercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double legalNames = GetPrecentageMatch(request.LegalName, policy.LegalName);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (legalNames == OneFieldLegalNamePercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double tradeNames = GetPrecentageMatch(request.TradeName, policy.TradeName);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (tradeNames == OneFieldTradeNamePercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double mailingname = GetPrecentageMatch(request.MailingName, policy.MailingName);
//this if condition is for checkibnf first field condition early so that it will not get all the percentage
if (mailingname == OneFieldMailingNamePercentage)
{
isPCCMatch = true;
loopState.Stop();
}
double ownerInfo = GetPrecentageMatch(request.OwnerName, policy.Ownership);
int partitalmatchcount = 0;
int addressmatchcount = 0;
// condtion 2
// get the partial count. if it is not more than 2 then compare the address an
if (GetPartialMatchFieldCount(SSN, FEIN, SEIN, DUN, legalNames, tradeNames, mailingname, ownerInfo, out partitalmatchcount) < 2)
{
// it will be hit if IsAddressmatch is true or count of partitalmatchcount & addressmatchcount is equal or more then 2
if (IsAddressmatch(request, policy, out addressmatchcount, partitalmatchcount) || (addressmatchcount + partitalmatchcount >= 2))
{
logger.Debug(MethodBase.GetCurrentMethod().Name + ": policy matched 2nd condition " + policy.ID);
isPCCMatch = true;
loopState.Stop();
}
}
else
{
isPCCMatch = true;
loopState.Stop();
}
// check for the 3 fields
if (GroupAmatchcount(SSN, FEIN, SEIN) + GroupBmatchcount(legalNames, tradeNames, mailingname) + GroupCMatchCount(request,
policy) + GroupDMatchCount(ownerInfo) >= 3)
{
logger.Debug(MethodBase.GetCurrentMethod().Name + ": policy matched 3rd condition " + policy.ID);
isPCCMatch = true;
loopState.Stop();
}
//else if ()
});
logger.Debug(MethodBase.GetCurrentMethod().Name + ": Matching algorithm is ended");
}
catch (Exception ex)
{
logger.ErrorException(MethodBase.GetCurrentMethod().Name, ex);
throw;
}
// }
return isPCCMatch;
}
I want to run the above loop for 100k records, so it will have 4 parallel.foreach loops. Once I found a match on one loop, I want to stop the execution of other parallel.foreach loops.

RadGrid Custom Filter

I'm trying to add a custom filter to my RadGrid. I have a column, vendNum, which I want to allow users to filter on multiple vendNums with a comma-separated list. Basically, I want the same functionality as an "in" statement in SQL (where vendNum in (X,Y,Z)).
I followed the tutorial on this site and came up with the following code to place in my RadGrid1_ItemCommand event.
protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.FilterCommandName)
{
Pair filterPair = (Pair)e.CommandArgument;
switch (filterPair.Second.ToString())
{
case "vendNum":
TextBox tbPattern = (e.Item as GridFilteringItem)["vendNum"].Controls[0] as TextBox;
if (tbPattern.Text.Contains(","))
{
string[] values = tbPattern.Text.Split(',');
if (values.Length >= 2)
{
e.Canceled = true;
StringBuilder newFilter = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
if (i == values.Length - 1)
newFilter.Append("[vendNum] = " + values[i]);
else
newFilter.Append("[vendNum] = " + values[i] + " OR ");
}
if (RadGrid1.MasterTableView.FilterExpression == "")
RadGrid1.MasterTableView.FilterExpression = newFilter.ToString();
else
RadGrid1.MasterTableView.FilterExpression = "((" + RadGrid1.MasterTableView.FilterExpression + ") AND (" + newFilter.ToString() + "))";
RadGrid1.Rebind();
}
}
break;
default:
break;
}
}
}
Doing this, though, keeps giving me an error "Expression Expected" when I try to filter with a comma separated list. I'm still able to filter a single vendNum. My FilterExpression does come out as expected. The code is failing on the RadGrid1.Rebind() statement. Has anyone dealt with this before? Any help is greatly appreciated.
Thanks,
Aaron
Forgot to Edit This
I solved this problem weeks ago...I had to set the "EnableLinqExpressions" property to false under the RadGrid.
I saw this as a fix for this question somewhere.
Try adding:
RadGrid1.EnableLinqExpressions = false;

Resources