Home > Mobile >  Is it possible to exit if user input negative number
Is it possible to exit if user input negative number

Time:07-09

Upon executing the below program in C#, the program is not compiling, any hints to fix the mistakes

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        int input;
        Console.WriteLine("Input a number:");
        int input=Console.ReadLine();
        while (true)
        {
            input = int.Parse(Console.ReadLine());
            if (input <= 0) break;
        }​

        Console.Write("Your input: ");
        foreach (int number in numbers)
        {
            Console.Write(number   " ");
        }
    }
}

CodePudding user response:

It appears that you are trying to initialise the variable input twice, in lines 7 and also 9. This will prevent your code from compiling.

Also it looks like the variable numbers is not initialised anywhere.

CodePudding user response:

yes, sure you cant declare in the same scope 2 variables with the same name:

your int input is the reason am talking about

int input;  //    <----
Console.WriteLine("Input a number:");
int input=Console.ReadLine();  //   <--- 

CodePudding user response:

You have two variables with the same name, which this is wrong.

int input;
int input=Console.ReadLine();

Also you aren't saving the user inputs, input variable save the last input the user put. It always have one value. You have to declare numbers before using it and storing the user inputs in it to print them in foreach loop.

declare input once as int then use it without redeclaring it. Also declare numbers as list of int and in while loop make this:

input = int.Parse(Console.ReadLine());
if (input <= 0) 
    {break;}
else
    {numbers.add(input);}

To save the first user input outside while loop do this:

int input;
Console.WriteLine("Input numbers:");//As you expect the user to input more than one number
input=int.Parse(Console.ReadLine());
if(input > 0)
{numbers.add(input);}

CodePudding user response:

This must be what you want:

    static void Main()
    {
        string inputText;
        int input;
        Console.WriteLine("Input a number:");
        inputText = Console.ReadLine();
        input = Convert.ToInt32(inputText);
        if (input <= 0)
        {
            return;
        }
        else
        {
            Console.Write("Your input:"   input);
        }
        Console.Read();

    }

First mistake: you declared int input twice. Second: You can't set Console.Readline() value to int variable because it returns as string. Third: numbers is not initialised anywhere and there is no need. Forth: use return instead of break.

  • Related