2012-01-15 2 views
1

Я новичок в C# и не могу понять, как проверить в коде, который я уже написал. У меня код работает отлично, но хочу продолжать добавлять функции. Я ищу советы или все, что вы хотели бы упомянуть. Спасибо заранее. Вот код, который у меня есть до сих пор, и вам нужно пройти проверку на 3 getInputs рядом с зелеными комментариями.Проверка чисел и букв с помощью C# для новичков

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace BasicUserInterface 
{ 
    class Program 
    { 
     static void DisplayApplicationInformation() 
     { 
      Console.WriteLine("Welcome to the Basic User Interface Program"); 
      Console.WriteLine("CIS247, Week 2 Lab"); 
      Console.WriteLine("Name: Fred Ziyad"); 
      Console.WriteLine(); 
      Console.WriteLine("This program accepts user input as a string, then makes the"); 
      Console.WriteLine("approppriate data conversion and display the results."); 
      Console.WriteLine(); 
     } 

     static void DisplayDivider(String outputTitle) 
     { 
      Console.WriteLine("************* " + outputTitle + " **************"); 
     } 

     static string GetInput(string inputType) 
     { 
      string strInput; 

      Console.Write("Enter " + inputType + ": "); 
      strInput = Console.ReadLine(); 

      return strInput; 
     } 

     static void TerminateApplication() 
     { 
      Console.WriteLine(); 
      Console.WriteLine("Thank you for using the Basic User Interface program"); 
      Console.Read(); 
     } 

     static void Main(string[] args) 
     { 
      int age; 
      double mileage; 
      string strInput, name; 

      DisplayApplicationInformation(); 

      DisplayDivider("Start Program"); 
      Console.WriteLine(); 

      DisplayDivider("Get Name"); 
      name = GetInput("your name"); 
      Console.WriteLine("Your name is " + name); 
      Console.WriteLine(); 
      //Validate name to be a string of letters. 

      DisplayDivider("Get Age"); 
      strInput = GetInput("your age"); 
      age = int.Parse(strInput); 
      Console.WriteLine("Your age is: " + age); 
      Console.WriteLine(); 
      //Validate age to be a number. 

      DisplayDivider("Get Mileage"); 
      strInput = GetInput("gas mileage"); 
      mileage = double.Parse(strInput); 
      Console.WriteLine("Your car MPT is: " + mileage); 
      //Validate mileage to be a number. 

      TerminateApplication(); 
     } 
    } 
} 

ответ

1
//Validate age to be a number. 

Вот как проверить строку, является ли номер:

string str = "123"; 
int result; 
if (!Int32.TryParse(str, out result)) 
    ; //not a whole number 

TryParse вернет ложь, если строка не успешно разобрать, как действительное число, и, если он делает синтаксический анализ успешно, вернет преобразованный int в параметр out.

Или, если вы хотите, чтобы десятичные:

string str = "123.5"; 
double result; 
if (!Double.TryParse(str, out result)) 
    ; //not a number 

Та же самая идея


//Validate name to be a string of letters. 

Вот как подсчитать количество символов в строке, которые не буквы:

string str = "AB3C"; 
int numberOfNonLetters = str.Count(c => !Char.IsLetter(c)); 

Чтобы убедиться, что строка имеет только буквы, просто убедитесь, что numberOfNonLetters равен нулю

+0

Не значит TryParse? (Возможно, вы смотрите игру Бронкос). –

+0

@SteveWellens - Я полностью наблюдаю за игрой в АФК, и думаю после 2-летнего, так что да, опечатки следует ожидать. TOUCHDOWN –

+0

Спасибо вам большое! –

3

Числовые типы имеют метод TryParse, который вы можете использовать, чтобы поймать недопустимого ввода.

Пример:

DisplayDivider("Get Age"); 
strInput = GetInput("your age"); 
if (int.TryParse(strInput, out age)) { 
    Console.WriteLine("Your age is: " + age); 
    Console.WriteLine(); 
} else { 
    Console.WriteLine("Age input was not a valid number."); 
} 
+0

Надеюсь, что вы не возражаете :) –

+0

Спасибо за помощь, я думал об этом в течение 3 часов. Спасибо! –

Смежные вопросы