อ่านข้อมูลจากคอนโซล
Console.ReadLine รอให้ผู้ใช้พิมพ์หนึ่งบรรทัดแล้วกด Enter จากนั้นคืนบรรทัดนั้นเป็นสตริง
ทำงานอย่างไร
อ่านสิ่งที่ผู้ใช้พิมพ์ด้วย Console.ReadLine และแปลงอย่างปลอดภัยด้วย int.TryParse
ReadLine อาจคืน null เมื่ออินพุตหมด จึงใช้ ?? กำหนดค่าเริ่มต้น int.TryParse คืน false แทนการโยน exception เมื่อข้อความไม่ใช่ตัวเลข ในคอมไพเลอร์ออนไลน์ให้พิมพ์คำตอบเมื่อข้อความถามปรากฏ
ตัวอย่าง C# ที่รันได้
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.ฝึกกับดีบักเกอร์
ตั้ง breakpoint ที่การกำหนดค่าหรือเงื่อนไขสำคัญ กด Debug แล้วดูค่าตัวแปรภายในก่อนไปยังบรรทัดถัดไป
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Average of Three Average three whole numbers. ง่าย
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. ง่าย