skip to Main Content

It just displays this instead of the error warning I made:

image

Here is how I want it to be:

image

And here is my code:

Console.Write("Masukkan Tinggi Segitiga: ");
int tinggi = Convert.ToInt32(Console.ReadLine());

if (tinggi > 0)
{
    for (int x = 1; x <= tinggi; x++)
    {
        for (int y = 1; y <= x; y++)
        {
            Console.Write("*");
        }
        Console.WriteLine("");
    }
}
else if (tinggi <= 0)
{
    Console.WriteLine("Input tidak valid! Harus berupa angka & bilangan bulat");
}

2

Answers


  1. The reason why it throws an exception is that you passed in an invalid number string and try to parse it. (i.e. "a" is not a number.)

    Using int.TryParse() and use the returned value to control your condition to output the error message you want:

    Console.WriteLine("=====TP MODUL 3=====");
    Console.Write("Masukkan Tinggi Segitiga: ");
    var parseResult = int.TryParse(Console.ReadLine(), out var tinggi);
    
    if (!parseResult || tinggi <= 0)
    {
        Console.WriteLine("Input tidak valid! Harus berupa angka & bilangan bulat");
    }
    else
    {
        for (int x = 1; x <= tinggi; x++)
        {
            for (int y = 1; y <= x; y++)
            {
                Console.Write("*");
            }
            Console.WriteLine();
        }
    }
    

    Output:

    =====TP MODUL 3=====
    Masukkan Tinggi Segitiga: a
    Input tidak valid! Harus berupa angka & bilangan bulat
    
    Login or Signup to reply.
  2. you could try:

    if (int.TryParse(input, out tinggi))
    {
        ...code here
    }
    else
    {
        Console.WriteLine("something in that language");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search