I'm trying to get user input from the user until the user enters nothing (so a enter key press) but it doesn't seem to be working properly. The user should be able to add as many numbers as they'd like and it should display them once they hit the enter key with no number entered.
Code:
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
namespace Lab2
{
class Program
{
static void Main(string[] args)
{
List<string> numbersInput = new List<string>();
Console.WriteLine("Please enter an integer");
string input = Console.ReadLine();
numbersInput.Add(input);
while (input != "")
{
Console.WriteLine("Please enter another integer: ");
input = Console.ReadLine();
}
if (input == "")
{
Console.WriteLine("The number you have entered is: " + " " + input);
numbersInput.Add(input);
foreach (string value in numbersInput)
{
Console.WriteLine("The number that was added to the list is : " + " " + value);
}
Console.ReadLine();
}
}
}
}
Do not compare strings to "", instead use string.IsNullOrEmpty() or string.IsNullOrWhitespace() (assuming you are targeting .NET Framework 2.0 or later.)
You have unnecessary code (final if statement) which does not provide any value.
Aside from that, your code needs to be restructured.
This is probably what you're looking for:
HTH
You're not adding anything to the
numbersInput
list except empty strings.numbersInput.Add(input)
needs to be in the while block instead.Try this
Edit: For summing
Change your List declaration.
Then parse the numbers out and add them to the list. If the parsing fails, you need to handle the error.
Then your list is no longer a string, so change the foreach
You are NOT adding the numberInputs to the list:
Very short version, does not add your personal logic but should demonstrate the idea:
try replace
input != ""
with!String.IsNullOrEmpty(input)
andinput==""
withStringIsNullOrEmpty(input)
.Like This: