如何在按回车键时使循环重新开始?

huangapple go评论125阅读模式
英文:

how can i make the loop restart when i press enter?

问题

I understand that you want a translation of the code part without any additional content. Here's the translated code:

using System;
using System.Linq;

class Geeks
{
    // Main Method
    public static void Main()
    {
        //购买
        float kg = 1000;
        string bananas;
        float BananaKgPrice = 1.69f;
        float bananaWeight = 200;
        float WatermelonKgPrice = 3.29f;
        double price;
        string BuyChoice;

        Console.WriteLine("欢迎光临我们的商店!我们出售香蕉和西瓜。");
        Console.WriteLine($"香蕉每公斤售价{BananaKgPrice}欧元,西瓜每公斤售价{WatermelonKgPrice}欧元");
        bool loopBreakBuyChoice = true;
        while (loopBreakBuyChoice)
        {
            Console.WriteLine("您想购买什么?1 - 香蕉,2 - 西瓜");
            BuyChoice = Console.ReadLine();
            switch (BuyChoice)
            {
                case "1":
                    loopBreakBuyChoice = false;
                    Console.WriteLine($"香蕉每公斤价格:{BananaKgPrice}欧元");
                    bool loopBreakBananaDigits = true;
                    while (loopBreakBananaDigits)
                    {
                        Console.WriteLine("您想购买多少香蕉?");
                        bananas = Console.ReadLine();//按回车键
                        bool DigitsBanana = bananas.All(char.IsDigit);
                        if (DigitsBanana != true)
                        {
                            loopBreakBananaDigits = true;
                            Console.WriteLine("请输入香蕉的数量。");
                        }

                        if (DigitsBanana == true)
                        {
                            loopBreakBananaDigits = false;
                            loopBreakBuyChoice = false;
                            price = Math.Round(Convert.ToDouble(bananas) * Convert.ToDouble(bananaWeight) / Convert.ToDouble(kg) * Convert.ToDouble(BananaKgPrice), 2);
                        }
                    }
                    break;
            }
        }
    }
}

This is the translated code portion without any additional content.

英文:

Im learning C#, and i want to repeat part of my code, if person types not a digit. SO, if person types a letter, everything seems fine, and the loop repeats. But, if the person just click enter, program breaks. First loop works correct, if you click enter, it starts again, but the seond, idk why, but it recongises enter(nothing) as true. Because of this, my formula cant multiply nothing, and i get an error. So, if the bool think that nothing IS a digit, how can i fix this? ( the problem is in first case ).

using System;
using System.Text;

class Geeks
{

    // Main Method
    public static void Main()
    {
        //buy
        float kg = 1000;
        string bananas;
        float BananaKgPrice = 1.69f;
        float bananaWeight = 200;
        float WatermelonKgPrice = 3.29f;
        double price;
        string BuyChoice;

        Console.WriteLine("Welcome to our shop! We sell bananas and watermelons.");
        Console.WriteLine($"Kilo of bananas costs {BananaKgPrice} euros, kilo watermelons {WatermelonKgPrice} euros");
        bool loopBreakBuyChoice = true;
        while (loopBreakBuyChoice)
        {
            Console.WriteLine("What do you want to buy? 1 - banans, 2 - watermelons");
            BuyChoice = Console.ReadLine();
            switch (BuyChoice)
            {
                case "1":
                    loopBreakBuyChoice = false;
                    Console.WriteLine($"Price of bananas for kilo.: {BananaKgPrice} euro");
                    bool loopBreakBananaDigits = true;
                    while (loopBreakBananaDigits)
                    {
                        Console.WriteLine("How much bananas do you want to buy?");
                        bananas = Console.ReadLine();//press enter
                        bool DigitsBanana = bananas.All(char.IsDigit);
                        if (DigitsBanana != true)
                        {
                            loopBreakBananaDigits = true;
                            Console.WriteLine("Please insert AMOUNT of bananas.");
                        }

                        if (DigitsBanana == true)
                        {
                            loopBreakBananaDigits = false;
                            loopBreakBuyChoice = false;
                            price = Math.Round(Convert.ToDouble(bananas) * Convert.ToDouble(bananaWeight) / Convert.ToDouble(kg) * Convert.ToDouble(BananaKgPrice), 2);
                        }
                    }
               break;
            }

        }
    }
}

I alredy tried to fix my problem here, but i did some problems in my post, so it was closed. Re-trying to make this post, and fix my problem.

答案1

得分: 2

If you press enter without entering anything Console.ReadLine will return an empty string. Enumerable.All is implemented that it returns ...

> true if every element of the source sequence passes the test in the
> specified predicate, or if the sequence is empty; otherwise, false.

So I think this fixes the issue:

bool DigitsBanana = !string.IsNullOrEmpty(bananas) && bananas.All(char.IsDigit);

Another approach would be to use int.TryParse because you are actually trying to parse the banana-count:

int bananaCount = 0;
while (true)
{
    Console.WriteLine("How much bananas do you want to buy?");
    if (int.TryParse(Console.ReadLine(), out int count))
    {
		bananaCount = count;
		break;
    }  

    Console.WriteLine("Please insert AMOUNT of bananas.");                 
}

price = bananaCount * Convert.ToDouble(bananaWeight) / Convert.ToDouble(kg) * Convert.ToDouble(BananaKgPrice), 2);
英文:

If you press enter without entering anything Console.ReadLine will return an empty string. Enumerable.All is implemented that it returns ...

> true if every element of the source sequence passes the test in the
> specified predicate, or if the sequence is empty; otherwise, false.

So i think this fixes the issue:

bool DigitsBanana = !string.IsNullOrEmpty(bananas) && bananas.All(char.IsDigit);

Another approach would be to use int.TryParse because you are actually trying to parse the banana-count:

int bananaCount = 0;
while (true)
{
    Console.WriteLine("How much bananas do you want to buy?");
    if (int.TryParse(Console.ReadLine(), out int count))
    {
		bananaCount = count;
		break;
    }  

    Console.WriteLine("Please insert AMOUNT of bananas.");                 
}

price = bananaCount * Convert.ToDouble(bananaWeight) / Convert.ToDouble(kg) * Convert.ToDouble(BananaKgPrice), 2);

答案2

得分: 0

当编程时,你需要学会抽象概念。在你的示例中,你需要输入一行代码,检查它是否为整数,也许还需要检查它是否在某个范围内。所以你可以实现一个函数来做这些,使用正确的参数调用它,这样你就抽象掉了烦恼,主要的代码看起来更清晰。

你可以实现一个类似这样的方法:

public int GetIntegerFromKeyboard(string prompt, int minimum = 0, int maximum = Int32.MaxValue)
{
    while (true)
    {
        Console.WriteLine(prompt);
        string s = Console.ReadLine();
        bool isInteger = Int32.TryParse(s, out int i);
        if (isInteger)
        {
            if (i >= minimum && i <= maximum)
            {
                return i;
            }
        }
    }
}

然后你可以这样调用它:

int buyChoice = GetIntegerFromKeyboard("你想买什么? 1 - 香蕉,2 - 西瓜", 1, 2);
...
int amount = GetIntegerFromKeyboard("你想购买多少千克的香蕉?", 1);
...

在这些调用之后,你知道返回值是一个有效的整数。

还有一些其他事情:
遵循约定,局部变量以小写字母开头,所以应该是:

float bananaKgPrice = 1.69f;
float watermelonKgPrice = 3.29f;
string buyChoice;

将布尔值与 truefalse 进行比较看起来业余。所以更倾向于:

if (!digitsBanana)

而不是:

if (DigitsBanana != true)
英文:

When programming you need to learn to abstract concepts. In your example you need to input a line, check that it is an integer and maybe check that it's within certain limits. So you implement a function to do that, call it with the right parameters and you've abstracted away the trouble and the main code looks cleaner.
You can implement a method like this:

public int GetIntegerFromKeyboard(string prompt, int minimum = 0, int maximum = Int32.MaxValue)
{
	while (true)
	{
	    Console.WriteLine(prompt);
		string s = Console.ReadLine();
		bool isInteger = Int32.TryParse(s, out int i);
		if (isInteger)
		{
		    if (i&gt;=minimum &amp;&amp; i&lt;=maximum)
			{
			    return i;
			}
		}
	}
}

And you can call it like this:

int buyChoice = GetIntegerFromKeyboard(&quot;What do you want to buy? 1 - banans, 2 - watermelons&quot;, 1, 2);
...
int amount = GetIntegerFromKeyboard(&quot;How many kilograms of bananas do you want to buy?&quot;, 1);
...

After these calls you know that the return value is a valid integer.

Some other things:
Following conventions local variables start with lowercase thus it's

float bananaKgPrice = 1.69f;
float watermelonKgPrice = 3.29f;
string buyChoice;

And comparing a boolean to true or false looks amateurish. So prefer

if (!digitsBanana)

over

if (DigitsBanana != true)

huangapple
  • 本文由 发表于 2023年7月6日 19:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定