我的错误在哪里? (Do-while循环) [英] Where is my mistake? (Do-while loop)

查看:111
本文介绍了我的错误在哪里? (Do-while循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,(我是初学者)我在do-while循环(do部分)中定义了一个变量(string = userSecondInput),但是我不能在while中使用变量!为什么? :(

请帮帮我:(我是



我尝试了什么:



Hi guys, (i'm a beginner :) i defined a variable (string = userSecondInput) in the do-while loop ("do" part), but i can't use the variable in the "while"! why? :(
please help me :( i'm

What I have tried:

Console.WriteLine("Please Enter Your name: ");
string userInput = Console.ReadLine();
if (string.IsNullOrEmpty(userInput))
{
    do
    {
        Console.WriteLine("invalid value! Please Enter Your name: ");
        string userSecondInput = Console.ReadLine();
    } while (userSecondInput == "");
}
Console.WriteLine("welcome " + userInput);
Console.ReadKey();

推荐答案

这称为范围。当你在花括号的一部分内定义一个变量时({... })然后它在那些括号之外是不可见的。



This is called "scope". When you define a variable inside a section of curly brackets ({ ... }) then it isn't visible outside of those brackets.

do
{
    Console.WriteLine("invalid value! Please Enter Your name: ");
    string userSecondInput = Console.ReadLine(); // defined here
} while (userSecondInput == ""); //can't be seen here as outside of the brackets it is defined in





做类似的事情





Do something like

Console.WriteLine("Please Enter Your name: ");
string userInput = Console.ReadLine();
string userSecondInput = null;
if (string.IsNullOrEmpty(userInput))
{
    do
    {
        Console.WriteLine("invalid value! Please Enter Your name: ");
        userSecondInput = Console.ReadLine();
    } while (userSecondInput == "");
}


无需在循环内创建变量,您应使用现有变量。



No need to create a variable inside the loop, you shall use the existing one.

static void Main(string[] args)
        {
            Console.WriteLine("Please Enter Your name: ");
            string userInput = Console.ReadLine();
            if (string.IsNullOrEmpty(userInput))
            {
                do
                {
                    Console.WriteLine("invalid value! Please Enter Your name: ");
                      userInput = Console.ReadLine();
                } while (userInput == "");
            }
            Console.WriteLine("welcome " + userInput);
            Console.ReadKey();
        }


如果要在循环条件中使用变量,则必须在循环之前创建变量。但是为什么你需要
You have to create a variable before the loop if you want to use it in a loop condition. But why do you need
userSecondInput 

,它从来没有在循环之外使用过。您只想捕获用户的非空输入,只需使用

, it has never been used outside of the loop. You just want to capture none-empty input from the user, just use

userInput

即可。试试这个

		if (string.IsNullOrEmpty(userInput))
{
    do
    {
	 Console.WriteLine("invalid value! Please Enter Your name: ");
	 userInput = Console.ReadLine();
    }
    while (string.IsNullOrEmpty(userInput));
}


这篇关于我的错误在哪里? (Do-while循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆