Reading user information

Asked

Viewed 912 times

2

I started studying C#, and my first program (except for hello world hahahaha) is an area calculator. In the code below, after I enter the option (choosing which figure I want) the console simply closes.

            Console.WriteLine("Bem vindo a calculadora de áreas!!!");
            Console.WriteLine("A seguir escolha qual figura deseja, digitando o número correspondente a figura correspondente.");
            Console.WriteLine("1 ==> Quadrado");
            Console.WriteLine("2 ==> Triângulo");
            Console.WriteLine("3 ==> Circunferência");
            int opcao = Console.Read();

            switch (opcao)
            {
                case  1:
                    int lado;
                    Console.WriteLine("Digite o valor do lado do quadrado: ");
                    lado = Console.Read();
                    lado = lado * lado;
                    Console.WriteLine("O valor da área do quadrado e: ", lado);
                    break;
                case  2:
                    int base_t, altura, resultado;
                    Console.WriteLine("Digite o valor da base do triângulo: ");
                    base_t = Console.Read();
                    Console.WriteLine("Digite o valor da altura do triângulo: ");
                    altura = Console.Read();
                    resultado = base_t * altura / 2;
                    Console.WriteLine("O valor da área do triângulo é: ", resultado);
                    break;
                case  3:
                    int raio;
                    double area;
                    Console.WriteLine("Digite o valor do raio da circunferência: ");
                    raio = Console.Read();
                    area = Math.PI * (raio * raio);
                    Console.WriteLine("O valor da área do circunferência e: ", area);
                    break;
            }

        }
    }
}
  • Did the posted answer solve your problem? Do you think you can accept it? If you don’t know how to do it, check out [tour]. This would help a lot to indicate that the solution presented was useful to you and to give an indication that it is satisfactory. You can also vote on any and all questions or answers you find useful on the entire site (when you have 15 points). Accepting and voting are separate things.

2 answers

2

The problem is that it is picking up a character. You need to take a text and convert to number to work. I did this to demonstrate, I modernized the code and solved a problem that wasn’t printing the result. Obviously from this can better, can make a loop to ask again when it fails, can generalize the conversion and validation code.

using System;
using static System.Math;
using static System.Console;
                    
public class Program {
    public static void Main() {
        WriteLine("Bem vindo a calculadora de áreas!!!");
        WriteLine("A seguir escolha qual figura deseja, digitando o número correspondente a figura correspondente.");
        WriteLine("1 ==> Quadrado");
        WriteLine("2 ==> Triângulo");
        WriteLine("3 ==> Circunferência");
        string escolha = ReadLine();
        int opcao;
        if (!int.TryParse(escolha, out opcao)) {
            Write("Opção inválida");
            return;
        }
        switch (opcao) {
            case  1:
                int lado;
                WriteLine("Digite o valor do lado do quadrado: ");
                string texto = ReadLine();
                if (!int.TryParse(escolha, out lado)) {
                    Write("Número inválido");
                    return;
                }
                lado = lado * lado;
                WriteLine($"O valor da área do quadrado e: {lado}");
                break;
            case  2:
                int base_t, altura, resultado;
                WriteLine("Digite o valor da base do triângulo: ");
                texto = ReadLine();
                if (!int.TryParse(escolha, out base_t)) {
                    Console.Write("Número inválido");
                    return;
                }
                WriteLine("Digite o valor da altura do triângulo: ");
                texto = ReadLine();
                if (!int.TryParse(escolha, out altura)) {
                    Write("Número inválido");
                    return;
                }
                resultado = base_t * altura / 2;
                WriteLine($"O valor da área do triângulo é: {resultado}");
                break;
            case  3:
                int raio;
                double area;
                WriteLine("Digite o valor do raio da circunferência: ");
                texto = ReadLine();
                if (!int.TryParse(escolha, out raio)) {
                    Write("Número inválido");
                    return;
                }
                area = PI * (raio * raio);
                WriteLine($"O valor da área do circunferência e: {area}");
                break;
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The ReadLine() is the right method to read more complex data (more than one character). Only it always returns a text.Then you have to do the conversion. As you are not sure that a number has been entered the conversion may fail. Then the correct method to convert is the TryParse() who tries to convert, if it doesn’t work, he gives a return indicating this, if it works out he put the converted value in the variable that is passing. If you need more details on this ask a specific question on the subject not to mix.

I know it can be a little heavy for someone who is starting out, but the example cannot be done correctly and simply at the same time. What’s the use of learning to do wrong? I taught you right. Still not totally right to not complicate too much. For exercise is good like this.

Behold Differences between Parse vs Tryparse.

  • Gosh, you can’t just read numbers?

  • There isn’t. Or even there is, but it’s so much more complicated that you’ll prefer this. If even those who are experienced prefer it, imagine who is starting it. As I said, it has the ability to generalize the function to use in several places in a simplified way. But for those who are starting it is not important this, what matters is to understand the functioning.

  • Thank you very much, I read and understand better what each addition you made. Ahh, about this: Console.Writeline("The value of the square area and: ", side); comma and then variable is because of Java

  • Java has the same difficulty of receiving numbers, only it offers a more dirty solution, in my opinion. It may be more practical if everything goes right, but if it goes wrong, and you have to consider that it can, it gets really bad.

1

Hello, as already mentioned in the above answer, Console.Read() reads the next character typed, its code actually, and for what you want, you would need to know the equivalent of those characters to match the options in your switch.

int opcao = Console.Read();

switch(Convert.ToChar(opcao)){
      case '1':
         Console.WriteLine("Primeiro");
         // efectuar calculos aqui e imprimir o resultado
         break;
      case '2':
         Console.WriteLine("Segundo");
         // efectuar calculos aqui e imprimir o resultado
         break;
      default:
         Console.WriteLine("Opcao Invalida");
         break;
}
// caso executes o app sem o modo debug
// para evitar que a console feche automaticamente
Console.Write("Pressione qualquer tecla para sair!");
Console.Read();

Alternatively you could just use the int.TryParse(Console.ReadLine(), variavel) which is the most common, which will return false if the input value is something other than a number and fails to convert, and true if the input value is converted successfully, the Console.ReadLine() always returns a string and can accept any input value.

Browser other questions tagged

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