Leggere l'input della console
Console.ReadLine aspetta che l'utente scriva una riga e prema Invio, poi la restituisce come stringa.
Come funziona
Leggere ciò che l'utente digita con Console.ReadLine e convertirlo in sicurezza con int.TryParse.
ReadLine può restituire null quando l'input finisce, quindi ?? fornisce un valore predefinito. int.TryParse restituisce false invece di lanciare un'eccezione se il testo non è un numero. Nel compilatore online, scrivi le risposte quando compaiono le richieste.
Esempio C# eseguibile
Program.cs
using System;
class Program
{
static void Main()
{
// Console.ReadLine returns the typed line, or null when input ends.
Console.Write("What is your name? ");
string name = Console.ReadLine() ?? "friend";
// int.TryParse converts text safely instead of throwing on bad input.
Console.Write("How old are you? ");
string text = Console.ReadLine() ?? "";
if (int.TryParse(text, out int age))
{
Console.WriteLine($"Hello, {name}!");
Console.WriteLine($"In 10 years you will be {age + 10}.");
}
else
{
Console.WriteLine($"\"{text}\" is not a whole number.");
}
}
}
What is your name? Ada
How old are you? 29
Hello, Ada!
In 10 years you will be 39.Esercitati con il debugger
Metti un breakpoint su un'assegnazione o una condizione importante, fai clic su Debug ed esamina i valori locali prima di passare alla riga successiva.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Average of Three Average three whole numbers. Facile
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. Facile