Line breaking problems and correctly display real value conversion on C#

Asked

Viewed 108 times

6

I made a simple C# code that asks you to enter name, age, weight, city and state, performs normally only that it appears some problems as instead of the weight being 60.5KG gets 605KG and wanted to know how to break the line to print the part filling the form and printing separately.

// Meu Código
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TerceiroCd
{
    class Program
    {
        static void Main(string[] args)
        {
            String nomeNome, cidadeC, estadoE;
            double peso;
            int idade;

            Console.Write("Digite o seu nome: ");
            nomeNome = Console.ReadLine();
            Console.Write("Digite a sua idade: ");
            idade = int.Parse(Console.ReadLine());
            Console.Write("Digite o seu peso: ");
            peso = double.Parse(Console.ReadLine());

            Console.Write("Digite sua cidade: ");
            cidadeC = Console.ReadLine();
            Console.Write("Digite o seu estado: ");
            estadoE = Console.ReadLine();

            Console.WriteLine($"Seu nome é {nomeNome}");
            Console.WriteLine($"Possui {idade} de idade e pesa {peso}KG");
            Console.WriteLine($"Mora na cidade de {cidadeC} no estado de {estadoE}");

            Console.ReadKey();
        }
    }
}
// A impressão fica assim
Digite seu nome: Alex F.
Digite sua idade: 20
Digite o seu peso: 60.5
Digite sua cidade: Guanambi
Digite o seu estado: Bahia
Seu nome é Alex F.
Possui 20 anos de idade e pesa 605KG // Valor errado
Mora na cidade de Guanambi no estado da Bahia
// Queria que fosse assim:
Digite seu nome: Alex F.
Digite sua idade: 20
Digite o seu peso: 60.5
Digite sua cidade: Guanambi
Digite o seu estado: Bahia

Seu nome é Alex F.
Possui 20 anos de idade e pesa 60.5KG
Mora na cidade de Guanambi no estado da Bahia

2 answers

7


Line breaker

Put a WriteLine() Wherever you jump a line, so you have printed nothing but a line break, after all the method calls WriteLine.

It is also possible \n in the text that is the character that jumps line.

Data conversion

As to the Parse() will break your application when you type something wrong. It’s good to read too What is the main difference between int. Parse() and Convert.Toint32()? because the other answer makes the same mistake.

Note that the person needs to type within the format of the current culture that the thread has at the moment, if nothing is specified then it is the one that is configured in the operating system. As it should be in the format pt-BR then you must enter the comma as the decimal separator.

To ensure certain format it is necessary to configure the method of parse in the specific format that accepts or not, then you should use the signature of the most complete method that asks for the style and culture. In the case maybe the style Float should solve the issue and not accept the decimal point (I did a quick test and it worked but would need a more extensive test and better evaluation), it would be something like this:

double.TryParse("60.5", NumberStyles.Float, CultureInfo.CurrentCulture, out var peso)

I put in the Github for future reference.

It was commented to give a Replace(). This is a huge gambit. This should not be done, this is asking for future problems.

First, rare cases that change the data the person typed is a good idea. I’m going to say it again because I know everybody does it: it’s a rare good idea to change something that a person has typed, and yes almost everyone gets it wrong. It is even possible in some cases to change, show the user in one way or another the modified value and let them confirm this data or not, the exact way to do this depends on the context. Want to make have all this work? If that’s the case you can do so using this pattern.

You can do an extra validation and not allow the input of the data in this format, but that’s exactly what the above command does. Then you give the most appropriate treatment for the case, usually the TryParse() is used as a condition of a if, and inside it you can do whatever you want, for example you can give a hint to the user about the error. Unfortunately `Tryparse() does not give more details of which specific error occurred, may be a fault of it, but the way to solve this is to make your own parser, simple or complex to find the error and give a more specific hint. in this example you can verify that you are using a comma culture as decimal separator and show the user that it is using dot. It takes work for a simple case like this I wouldn’t do.

In this case if you change the point by the comma if the person type the point as a thousand separator or for any other crazy reason, if he put random things will give a nice problem.

Do you want a robust system or one that accepts anything and breaks? If you want the second, ok, just tell the user that he has to type right and accept when he type wrong. In a real system in production this is not acceptable. If you want something robust then you have to think of all cases, not just some.

There are other things that can be simplified in the code.

  • My variable weight when typed 60.5 appears 605 in print, how does it solve this?

  • I cannot reproduce the problem, the application breaks every time and the answer already talks about it.

  • But the code runs, it’s only showing the weight value wrong

  • I edited, you have to do something else not to accept the point.

  • If you put 60.5 goes normal, but real numbers in programming do not use comma

  • 2

    That’s not programming, that’s data input.

  • You can replace "." and replace it with ",". Example: weight = double.Parse(Console.Readline(). Replace(".",","))

  • 1

    @Lucas this is gambiarra, it’s a way to adjust if the person goes wrong, but it generates an ambiguity, what if the person uses a thousand separator? People never think about real use. It’s what I always say, people don’t want to do the right thing, they just want to see it work, then someone does something out of the ordinary and it’s trouble. It is even possible to do a personalized analysis and give a message to the person indicating that probably she is typing wrong as a tip to enter the data correctly, but not as validation, and mainly not as a change cumpulsória and automatic.

  • In this case there is no problem. But its data entries need to be validated correctly. You could do this using a Tryparse

  • 1

    It generates problem yes, the fact that you do not see problem does not mean that it does not generate, I wrote a case that generates problem.

  • @Lucas using Replace() worked, but could be a problem in the future.

  • which? It will cause problems if you type an alphanumeric string. What can happen with other inputs. But if validate with a Tryparse() from to treat this. Any different type of string can generate error when entering an input, it is important to validate the input types

  • @Alexf. Exactly what I said, it worked a case, not all, https://i.stack.Imgur.com/jgk8Q.png

  • @Lucas went to try to get the comma out by only getting one point, but the IDE accused that Replace() needs 2 arguments to work.

  • Yes, the Replace() method uses 2 arguments. The first indicates the string you want to replace, the second indicates the string that will be in place. If you do not find the string to be replaced, it changes nothing.

  • 2

    "In this case there is no problem" = gambiarra. I recommend that people who insist too much on this line of reasoning try something in the area of humanities, like fine arts, theater, and other things that give space for personal interpretations. For exact it is kind of risky to work like this, it harms the client (it is even better to rethink more widely and improve the procedures, of course).

  • @Maniero, you like the solution, show! Sure it’s better this way, but otherwise he wouldn’t have a problem either, if he used Tryparse(), as you did.

  • @Bacco, thanks for the feedback. I just tried to help the friend, this was the solution I had in mind. Now, I learned a new technique from Maniero.

  • 1

    @Lucas, quite rightly, proposing something that may not be ideal happens quite often and with a lot of people, what you cannot do is settle for the solution and stay in it. As long as you understand the problem that it generates and improve with each "iteration", everything is within normality. Obviously, in our things, we take the liberty of going out of our way to solve immediate problems, but whenever teaching a third party, it is important to make the problem clear (or really focus only on the proper technical way)

Show 14 more comments

0

// Meu Código
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TerceiroCd
{
    class Program
    {
        static void Main(string[] args)
        {
            String nomeNome, cidadeC, estadoE;
            double peso;
            int idade;

            Console.Write("Digite o seu nome: ");
            nomeNome = Console.ReadLine();
            Console.Write("Digite a sua idade: ");
            idade = Convert.ToInt32(Console.ReadLine());
            Console.Write("Digite o seu peso: ");
            peso = Convert.ToDouble(Console.ReadLine());

            Console.Write("Digite sua cidade: ");
            cidadeC = Console.ReadLine();
            Console.Write("Digite o seu estado: ");
            estadoE = Console.ReadLine();

            Console.WriteLine($"\n Seu nome é {nomeNome}. \n Possui {idade} anos de idade e pesa {Convert.ToString(peso).Replace(",", ".")} Kg. \n Mora na cidade de {cidadeC}, estado de(a) {estadoE}.");

            // Use o \n para quebrar a linha dentro de uma string
            // Ao invés de Parse tente o Convert
            // Ao invés de um ponto tente usar uma virgula ao inserir o peso
            // Replace() => Substitui um caracter por outro

            Console.ReadKey();
        }
    }
}

  • Would you have any problem putting Convert.Toint16 instead of Convert.Toint32?

  • Basically, int 16 = supports values from 32,768 to +32,767, int 32 = supports values from 2,147,483,648 to +2,147,483,647, int 64 = supports values from 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

  • Still still showing 605KG instead of 60.5KG :(

  • The solution I thought of for this case is Replace(). If you validate the correct entries, you will have no problem with this use.

  • I used the comma instead of the stitch to insert the weight, it worked perfectly.

  • Real values in C# use semicolons?

  • 1

    @Alexf. I edited mine, this is not solution, I tried to leave as complete as possible. You still don’t understand what code is and what data input is, don’t mix the concepts.

  • 1

    @Alexf. internally the language uses neither one thing nor the other, what happens is that you have a problem in the interface with the user data. Internal storage is language-specific, the source code is something else, you use the decimal point in virtually any common language, no thousands separator, and here comes a third thing, which is the place where the user types (whether console or graphic field) - This already depends on the user’s language settings, in the case of C#, which is precisely the situation foreseen in Maniero’s reply.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.