Member 13741832 Ответов: 3

Мне нужно что-то напечатать, если все даты не ошибаются


каждый раз, когда я пытаюсь запустить программу, она говорит, что локальная переменная с именем " wm "не может быть объявлена в этой области, потому что это придаст другое значение "wm", которое уже используется в "родительской или текущей" области для обозначения чего-то другого
ii попытался использовать логические значения, но не смог этого сделать
что я должен изменить?
это и есть код:
using System;

class MainClass {
  public static void Main (string[] args) {
  int wd = 1;
	int wm = 1;
	int wy = 1;
    Console.WriteLine ("enter digit between 0-4");
    int md = int.Parse(Console.ReadLine());
   //md=menu digit
    if (md==0)
{
    Console.WriteLine("Bye Bye");
}
else if (md==1)
{
	Console.Write("enter month number-");
	int month = int.Parse(Console.ReadLine());
	Console.Write("enter a day-");
	int day = int.Parse(Console.ReadLine());
	Console.Write("enter a year-");
	int year = int.Parse(Console.ReadLine());
	if (month<0 || month>12){
	  Console.WriteLine("wrong month");
	  int wm = 0;
	}
	else if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 && day>31 || day<0){
	  Console.WriteLine("wrong day");
	  int wd = 0;
	}
	else if (month==4 || month==6 || month==9 || month==11){
	  if (day>30 || day<0){
	  Console.WriteLine("wrong day");
	  int wd = 0;
	}
}
if(month==2)
{
  if (year%400==0 || year%4==0)
  {
    if (day>29 || day<0){
      Console.WriteLine("wrong day");
      int wd = 0;
    }
  }
    else {
      if (day<0 || day>28){
      Console.WriteLine("wrong day");
      int wd = 0;
    }
  }
  if (year<0 || year>9999){
    Console.WriteLine("wrong year");
    int wy = 0;
  }
  
}
}
}
}                                         


Что я уже пробовал:

я попытался заменить числа логическими и поискать в google

RedDk

Я не уверен, что вижу, на что ссылается pm, потому что он ссылается на "wd", который действительно объявляется, подписывается и все такое ... но что касается "wm", то это то, что вы предлагаете, и есть проблема ... в любом случае он вообще нигде не имеет области действия ... мой компилятор выдаст сообщение о том, что "wm был объявлен, но никогда не использовался". Так в чем же опять проблема?

3 Ответов

Рейтинг:
20

Patrice T

Когда вы ставите int перед именем переменной это объявление, и вы можете объявить переменную только 1 раз в процедуре.
Решение: снимите крышку int перед каждым wd но вот первый. возможно, вам придется сделать то же самое для других переменных.
-----
Научитесь правильно делать отступы в вашем коде, это покажет его структуру, и это поможет чтению и пониманию. Это также помогает выявлять структурные ошибки.

using System;

class MainClass {
  public static void Main (string[] args) {
    int wd = 1;
    int wm = 1;
    int wy = 1;
    Console.WriteLine ("enter digit between 0-4");
    int md = int.Parse(Console.ReadLine());
    //md=menu digit
    if (md==0)
    {
      Console.WriteLine("Bye Bye");
    }
    else if (md==1)
    {
      Console.Write("enter month number-");
      int month = int.Parse(Console.ReadLine());
      Console.Write("enter a day-");
      int day = int.Parse(Console.ReadLine());
      Console.Write("enter a year-");
      int year = int.Parse(Console.ReadLine());
      if (month<0 || month>12){
        Console.WriteLine("wrong month");
        int wm = 0;
      }
      else if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12 && day>31 || day<0){
        Console.WriteLine("wrong day");
        int wd = 0;
      }
      else if (month==4 || month==6 || month==9 || month==11){
        if (day>30 || day<0){
          Console.WriteLine("wrong day");
          int wd = 0;
        }
      }
      if(month==2)
      {
        if (year%400==0 || year%4==0)
        {
          if (day>29 || day<0){
            Console.WriteLine("wrong day");
            int wd = 0;
          }
        }
        else {
          if (day<0 || day>28){
            Console.WriteLine("wrong day");
            int wd = 0;
          }
        }
        if (year<0 || year>9999){
          Console.WriteLine("wrong year");
          int wy = 0;
        }

      }
    }
  }
}

Профессиональные редакторы программистов имеют эту функцию и другие, такие как сопоставление скобок и подсветка синтаксиса.
Блокнот++ Главная Страница[^]
личные[^]


Рейтинг:
0

Maciej Los

Зачем заставлять двери широко распахиваться? Вы должны работать с правильным типом данных - a DateTime. Видеть:

CultureInfo provider = CultureInfo.CreateSpecificCulture("en-US");
string format = "MM/dd/yyyy";
string stringDate;
DateTime myDate;

Console.Write("Enter date in the following format: '{0}'", format);
stringDate = Console.ReadLine();
try
{
	myDate = DateTime.ParseExact(stringDate, format, provider);
	Console.WriteLine("Correct date!");
}
catch (FormatException)
{
	Console.WriteLine();
	Console.WriteLine("'{0}' is NOT in the correct format.", stringDate);
}


Для получения более подробной информации, пожалуйста, смотрите: значение datetime.Метод ParseExact (String, String, IFormatProvider) (System)[^]


Рейтинг:
0

an0ther1

Ваша проблема заключается в том, что вы повторно объявляете свои переменные.

// Declare a new variable named 'myInt'
int myInt;
// Populate the variable
myInt = 22;
// Repopulate the variable
myInt = 33;

Как только вы объявляете переменную, она становится доступной во всей области видимости, которая определяется тем, где вы ее объявляете.
Например, если вы объявите его вне метода, он будет доступен во всем классе.
Если вы объявите его внутри метода, он будет доступен во всем методе
Если вы объявите его внутри оператора if или using, то он будет доступен во всем операторе if или using, но не вне его.
Дополнительные примеры ниже
using System;
// declare a variable that can be accessed throughout any method within this class
private int ClassAccessibleInt = 12;

public static void Main(string[] args)
{
// declare a variable that can be accessed within the Main method
int MethodAccessibleInt = 10;
// declare another variable that can be accessed within the Main by adding 2 others
int AnotherMethodAccessibleInt = ClassAccessibleInt + MethodAccessibleInt;
// create an if statement
if(DateTime.Today.Month > 2)
{
    // declare another variable that can be accessed only within the If Statement
    int IfAccessibleInt = DateTime.Today.Month + ClassAccessibleInt;
    // add value to AnotherAccessibleInt
    AnotherMethodAccessibleInt = AnotherMethodAccessibleInt + IfAccessibleInt;
    // IfAccessibleInt = 3 + 12 = 15
    // ClassAccessibleInt = 12
    // MethodAccessibleInt = 10
    // AnotherMethodAccessibleInt = 10 + 12 + 3 + 12 = 37
    // close if statement
}
// IfAccessibleInt no longer available
// ClassAccessibleInt = 12
// MethodAccessibleInt = 10
// AnotherMethodAccessibleInt = 37
// end Main Method
}
// ClassAccessibleInt = 12
// MethodAccessibleInt no longer available
// AnotherMethodAccessibleInt no longer available


с уважением