2014-01-08 3 views
0

Я не понимаю, что происходит в моем случае, чтобы определить, хочу ли я повторить ввод пользователей. Должен ли я сделать еще один цикл вне моего цикла while? Я попытался сделать это, и мое заявление о делах станет недостижимым. Может быть, я не понимаю утверждения case-switch.Case Switch with loop

class Program 
{ 
    static void Main(string[] args) 
    { 


     string _a = ""; 
     constructor con = new constructor(); 
     Console.WriteLine("Enter enter exit to end the program..."); 
     Console.WriteLine("Enter C for constructor, M for method, A for an array..."); 
     Console.WriteLine("Please reference source code to have full details and understanding..."); 
     bool control = true; 
     while (control) 
     { 
      _a = Console.ReadLine(); 
      switch (_a.ToUpper()) 
      { 

       case "EXIT": 
        Console.WriteLine("Thank you for using AJ's program..."); 
        control = false; 
        break; 
       case "C": 
        Console.WriteLine(con.a); 
        Console.WriteLine("Would you like to test another scenario?"); 
        Console.ReadLine(); 
        if (_a.ToUpper() == "Y") 
        { 
         Console.ReadLine(); 
         return; 

        } 
        control = false; 
        break; 
       case "M": 
        control = false; 
        metroid(); 
        break; 
       case "A": 
        control = false; 
        Array(); 
        break; 
       default: Console.WriteLine("No match"); 
        break; 
      } 
     } 
    } 
    public class constructor 
    { 
     public string a = "This is a constructor!"; 
    } 
    static public void metroid() 
    { 
     string b = "This is a method!"; 
     Console.WriteLine(b); 
    } 
    static public void Array() 
    { 
     try 
     { 
      Console.WriteLine("This is a random array. Please enter the size."); 
      string sSize = Console.ReadLine(); 
      int arraySize = Convert.ToInt32(sSize); 
      int[] size = new int[arraySize]; 
      Random rd = new Random(); 
      Console.WriteLine(); 
      for (int i = 0; i < arraySize; i++) 
      { 
       size[i] = rd.Next(arraySize); 
       Console.WriteLine(size[i].ToString()); 
      } 
     } 
     catch (System.FormatException) 
     { 
      Console.WriteLine("Not correct format, restarting array process."); 
      Array(); 
     } 
    } 
} 
} 
+0

Если вы просто хотите, чтобы инструкции были снова видны, переместите операторы 'Console.Write' в цикл' while'. – paqogomez

+0

@paqogomez все они ????? –

+0

@paqogomez Инструкции с аргументами, приведенными в действие, не работают ... –

ответ

1

Вот что я придумал. У вас было слишком много способов выйти из вашей петли, поэтому я удалил все строки control = false, за исключением случаев, когда пользователь набрал «EXIT»

Кроме того, в случае «C» вы возвращаетесь из метода, если они выбирают «Y», Я изменил это на continue, чтобы цикл продолжался.

Наконец, я переместил 3 инструкции инструкций в цикл, поэтому, когда пользователь нажмет «Y», он снова напечатает их.

static void Main(string[] args) 
{ 
    string _a = ""; 
    constructor con = new constructor(); 
    bool control = true; 
    while (control) 
    { 
     Console.WriteLine("Enter enter exit to end the program..."); 
     Console.WriteLine("Enter C for constructor, M for method, A for an array..."); 
     Console.WriteLine("Please reference source code to have full details and understanding..."); 
     _a = Console.ReadLine(); 
     switch (_a.ToUpper()) 
     { 

      case "EXIT": 
       Console.WriteLine("Thank you for using AJ's program..."); 
       control = false; 
       break; 
      case "C": 
       Console.WriteLine(con.a); 
       Console.WriteLine("Would you like to test another scenario?"); 
       _a = Console.ReadLine(); //<==problem #1 you didnt set your var name 
       if (_a.ToUpper() == "Y") 
       { 
        continue; //<==problem #2 return exits the program, continue, just keeps going 
       } 
       control = false; 
       break; 
      case "M": 
       metroid(); 
       break; 
      case "A": 
       Array(); 
       break; 
      default: 
       Console.WriteLine("No match"); 
       break; 
     } 
    } 
} 
0

может быть, вы хотите изменить

   Console.ReadLine(); 
       if (_a.ToUpper() == "Y") 
       { 
        Console.ReadLine(); 
        return; 

       } 

в

   _a = Console.ReadLine(); 
       if (_a.ToUpper() == "Y") 
       { 
        _a = Console.ReadLine(); 
        continue; 

       } 
+0

Без тестирования, что я собираюсь предположить, что он будет циклически проходить и заканчивать программу –

0

Я думаю, вы должны учитывать в этом случае goto. Да, вам нужно приложить дополнительные усилия, но это поможет вам преодолеть цикл While.

Образец ниже:

switch (_a.ToUpper()) 
    { 
    case "EXIT": 
     Console.WriteLine("Thank you for using AJ's program..."); 
     control = false; 
     // execute goto when your all line executes successfully 
     goto case "New"; 

    case "New": 
    // some logic 
    } 

См работает образец здесь Goto-Switch

+0

О, пожалуйста, скажите, что вы не просто рекомендовали goto. – paqogomez

0
   string NewInput= Console.ReadLine(); 
       if (NewInput.ToUpper() == "Y") 
       { 
        //print some thing with console.writeline 

        //if after this you want to restart the loop then instead of return use 
        continue; 
       } 
0

Попробуйте поставить Console.WriteLine внутри цикла в то время как это:

static void Main(string[] args) 
{ 
    bool control = true; 
    while (control) 
    { 
     Console.WriteLine("Enter enter exit to end the program..."); 
     Console.WriteLine("Enter C for constructor, M for method, A for an array..."); 
     Console.WriteLine("Please reference source code to have full details and understanding..."); 
     string _a = Console.ReadLine(); 
     switch (_a.ToUpper()) 
     { 
      case "EXIT": 
       Console.WriteLine("Thank you for using AJ's program..."); 
       control = false; 
       break; 
      case "C": 
       Console.WriteLine("press c"); 
       Console.WriteLine("Would you like to test another scenario?"); 
       Console.ReadLine(); 
       if (_a.ToUpper() == "Y") 
       { 
        Console.ReadLine(); 
        return; 

       } 
       control = false; 
       break; 
      case "M": 
       control = false; 
       metroid(); 
       break; 
      case "A": 
       control = false; 
       Array(); 
       break; 
      default: Console.WriteLine("No match"); 
       break; 
     } 
    } 
} 

Дополнительное чтение о переключатель here и here.

Просто добавьте комментарий для результата, спасибо. Надеюсь, это помогло!

+0

компилируется, но заканчивается после ввода Y –

+0

Вы не должны устанавливать управление в false в случае "C" – jomsk1e