简体   繁体   中英

How do I include a variable in the condition of a while loop if the variable is changed inside said loop in c#

I'm trying to have the user input a number from 1 to 5 and I want to loop back and have the user input another number if it isn't within those bounds. Here is the code:

int charNum = 0;

while(!((charNum > 0) && (charNum < 6)) ) {

    int charNum = Convert.ToInt32(Console.ReadLine());
            
}

The above gives one error which says:

"A local or parameter named 'charNum' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter"

I've tried incorporating multiple variables but seem to encounter the same problem with changing variables inside a loop.

Is there a way to get around this or am I missing an easier solution?

You should never use Convert style methods and always use the TryParse style methods for user input ... Users with dirty little fingers will type the wrong thing...

Here is an example which does all the above and your range check in the one line with a user message on failure

int charNum = 0;

while(!int.TryParse(Console.ReadLine(), out charNum ) || charNum < 0 || charNum >= 6) 
  Console.WriteLine("You had one job, now enter the number correctly");

You are trying to create another variable within your loop with the exact same name as the variable outside of the loop. You just need to assign a value to the variable, not declare it.

int charNum = 0;

while(!((charNum > 0) && (charNum < 6)) ) {

    charNum = Convert.ToInt32(Console.ReadLine());
            
}

EDIT

I would also look at the post above , as it gives great insight into what not to do in this situation.

This is a very simple mistake. You're attempting to re-declare the charNum variable inside the loop. Simply remove the int and it becomes an assignment instead of a declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM