2015-11-28 2 views
0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

public class Tst001 
{ 
    public static void Main(string[] args) 
    { 
     int[,] showArray = new int[20, 20]; 
     string[,] Walk = new string[20, 20]; 
     int a = 0; 
     int b = 0; 
     int leftCount = 0; 
     int rightCount = 0; 
     double leftOver = 0; 
     double moveCommand; 
     int countLeft = 0; 
     int countRight = 0; 
     int m = 0; 
     int n = 0; 

     for (int x = 0; x < showArray.GetLength(0); x++)//Determine all values to be 0s 
     { 
     for(int y = 0; y < showArray.GetLength(1); y++) 
     { 
      showArray[x, y] = 0; 
     } 
     } 

     DisplayCommand(); 

     do 
     { 
     Console.Write("Enter command: "); 
     moveCommand = Convert.ToDouble(Console.ReadLine()); 

     if (moveCommand == 3 || moveCommand == 4)//Use these values to determine the directions 
     { 
      if (moveCommand == 3) 
      { 
       rightCount++; 
       countRight = rightCount % 4; 
      } 
      else 
      { 
       leftCount++; 
       countLeft = leftCount % 4; 
      } 
     } 
     else if ((int)moveCommand == 5)//Determines the limit of how many passes can be made and eventually passes that walked 
     { 
      leftOver = moveCommand * 100; 
      leftOver = (int)leftOver; 
      leftOver -= 500; 
      leftOver -= 1; 

      if (leftOver >= 20) 
      { 
       Console.WriteLine("Exceed limit of array!"); 
      } 
      else if (leftOver < 20) 
      { 
       if (Directions(countLeft, countRight) == "-V") 
       { 
        if (a - (int)leftOver >= 0) 
        { 
        a -= (int)leftOver; 
        } 
        else 
        { 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", a); 
        } 
       } 
       else if (Directions(countLeft, countRight) == "V") 
       { 
        if (a + (int)leftOver < 20) 
        { 
        a += (int)leftOver; 
        } 
        else 
        { 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - a)); 
        } 
       } 
       else if (Directions(countLeft, countRight) == "-H") 
       { 
        if (b - (int)leftOver >= 0) 
        { 
        b -= (int)leftOver; 
        } 
        else 
        { 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", b); 
        } 
       } 
       else 
       { 
        if (b + (int)leftOver < 20) 
        { 
        b += (int)leftOver; 
        } 
        else 
        { 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - b)); 
        } 
       } 
      }     
     } 
     else if (moveCommand == 6)//command 6 shows the walked 
     { 
      for (int x = 0; x < Walk.GetLength(0); x++) 
      { 
       for (int y = 0; y < Walk.GetLength(1); y++) 
       { 
        if (showArray[x, y] == 0) 
        { 
        Console.Write(" "); 
        } 
        else 
        { 
        Console.Write("*"); 
        } 
       } 
       Console.WriteLine(); 
      } 
     } 
     else if (moveCommand == 2) 
     { 
      continue; 
     } 
     else if (moveCommand == 1)//Determine whether the path is walked or not 
     { 
      do 
      { 
       Console.Write("Enter command: "); 
       moveCommand = Convert.ToDouble(Console.ReadLine()); 

       if (moveCommand == 3 || moveCommand == 4)//Determine the directions 
       { 
        if (moveCommand == 3) 
        { 
        rightCount++; 
        countRight = rightCount % 4; 
        } 
        else 
        { 
        leftCount++; 
        countLeft = leftCount % 4; 
        } 
       } 
       else if ((int)moveCommand == 5)// Determine the limit whether the entered value can be walked 
       { 
        m = a; 
        n = b; 

        leftOver = moveCommand * 100; 
        leftOver = (int)leftOver; 
        leftOver -= 500; 
        leftOver -= 1; 
        if (leftOver>= 20) 
        { 
        Console.WriteLine("Exceed limit of array!"); 
        } 
        else if (leftOver< 20) 
        { 
        if (Directions(countLeft, countRight) == "-V") 
        { 
         if (a - (int)leftOver >= 0) 
         { 
          m = a - (int)leftOver; 
         } 
         else 
         { 
          Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", a); 
         } 
        } 
        else if (Directions(countLeft, countRight) == "V") 
        { 
         if (a + (int)leftOver < 20) 
         { 
          m = a + (int)leftOver; 
         } 
         else 
         { 
          Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - a)); 
         } 
        } 
        else if (Directions(countLeft, countRight) == "-H") 
        { 
         if (b - (int)leftOver >= 0) 
         { 
          n = b - (int)leftOver; 
         } 
         else 
         { 
          Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", b); 
         } 
        } 
        else 
        { 
         if (b + (int)leftOver < 20) 
         { 
          n = b + (int)leftOver; 
         } 
         else 
         { 
          Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - b)); 
         } 
        } 

        //START HERE!! 
        for (int x = 0; x < showArray.GetLength(0); x++) //Determine path, where 1 is walked, 0 not walked 
        { 
         for (int y = 0; y < showArray.GetLength(1); y++) 
         { 
          if (a > m) 
          { 
           if (x >= m && x <= a && y == n) 
           { 
           showArray[x, y] = 1; 
           } 
          } 
          else if (a < m) 
          { 
           if (x >= a && x <= m && y == n) 
           { 
           showArray[x, y] = 1; 
           } 
          } 
          else if (b > n) 
          { 
           if (y >= n && y <= b && x == m) 
           { 
           showArray[x, y] = 1; 
           } 
          } 
          else 
          { 
           if (y >= b && y <= n && x == m) 
           { 
           showArray[x, y] = 1; 
           } 
          } 

         } 
        } 
        //Console.WriteLine("{0}\t{1}\t{2}\t{3}", a, b, m, n); 
        }      

        a = m; 
        b = n; 
       //END HERE!! 
       } 
       else if (moveCommand == 6) //command 6 shows the walked path 
       { 
        for (int x = 0; x < Walk.GetLength(0); x++) 
        { 
        for (int y = 0; y < Walk.GetLength(1); y++) 
        { 
         if (showArray[x, y] == 0) 
         { 
          Console.Write(" "); 
         } 
         else 
         { 
          Console.Write("*"); 
         } 
        } 
        Console.WriteLine(); 
        } 
       } 
      } while (moveCommand != 2) ; 
     } 

     else 
     { 
      Console.WriteLine("Wrong number entered!!!"); 
     } 


     //Console.WriteLine("leftCount {0}\trightCount {1}\ta {2}\tb {3}\ncountLeft {4}\tcountRight {5}\nDirections {6}", leftCount, rightCount, a, b, countLeft, countRight, Directions(countLeft,countRight)); //Just for checking values 
     } while (moveCommand != 9); 

     Console.Read(); 
    } 

    public static string Directions(int x, int y) //Determine directions, V for vertical, H for horizontal 
    { 
     string[,] Direction = { {"-V","H","V","-H" }, 
           {"-H","-V","H","V" }, 
           {"V","-H","-V","H" }, 
           {"H","V","-H","-V" }}; 

     return Direction[x, y]; 
    } 

    public static void DisplayCommand() 
    { 
     Console.WriteLine("Enter 3 to move Right,\n" + 
     "Enter 4 to move Left,\n" + 
     "Enter 5,x to determine amount of passes\n" + 
     "Enter 1 to move pencil down,\n" + 
     "Enter 2 to move pencil up,\n" + 
     "Enter 6 to draw the array,\n" + 
     "Enter 9 to end the program!\n"); 
    } 
} 

В настоящее время я изучаю код на C#. Это упражнение из книги. Мне удалось закончить это упражнение. Тем не менее, мне нравится знать, могут ли некоторые из «команд» вводиться в методы (не из книги, просто любопытные с моей стороны). Как вы можете видеть, существует много дублированных кодов. Моя основная проблема для решения этой проблемы заключается в том, что эти «команды» используют несколько значений (a, b, leftCount и т. Д.). Я не знаю, как принимать эти значения, когда команды помещаются в методы.Поместите дублированный код в метод C#

редактировать: команда 2 должна быть «карандаш вверх» вместо «карандаш» команда 1 должна быть «карандаш вниз» вместо «карандаш вверх»

+0

вы можете объявить свои поля в классе, а не в способ затем использовать его из ваших методов (в качестве параметра) – FKutsche

+0

Вы можете двигаться логика в другой класс, где вы можете создать переменные как переменная-член и каждый метод для каждого условия команды. После этого попытайтесь определить, может ли код быть реорганизован для удаления дубликата кода. – user1672994

+0

В настоящее время это пятая глава кодирования, я не совсем понимаю, какие поля. Я буду смотреть в него. Спасибо за ваш ответ. – Edward79

ответ

0

Попробуйте что-то вроде этого. Не изменял весь код. Похоже, вы дважды проверяете movecommand == 6.

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

 
public class Tst001 
 
{ 
 
    static int[,] showArray = new int[20, 20]; 
 
    static int countLeft = 0; 
 
    static int countRight = 0; 
 
    static int leftCount = 0; 
 
    static int rightCount = 0; 
 
    static int leftOver = 0; 
 
    static int a = 0; 
 
    static int b = 0; 
 

 
    static string[,] Walk = new string[20, 20]; 
 
    public static void Main(string[] args) 
 
    { 
 
     int moveCommand; 
 

 
     for (int x = 0; x < showArray.GetLength(0); x++)//Determine all values to be 0s 
 
     { 
 
      for (int y = 0; y < showArray.GetLength(1); y++) 
 
      { 
 
       showArray[x, y] = 0; 
 
      } 
 
     } 
 

 
     DisplayCommand(); 
 
     do 
 
     { 
 
      Console.Write("Enter command: "); 
 
      string cmd = Console.ReadLine(); 
 
      string[] cmdArray = cmd.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
 
      moveCommand = Convert.ToInt16(cmdArray[0]); 
 
      if (cmdArray.Count() == 2) 
 
      { 
 
       leftOver = Convert.ToInt16(cmdArray[1]); 
 
      } 
 

 
      switch (moveCommand) 
 
      { 
 
       case 2: 
 
        break; 
 
       case 3: 
 
        MoveLeftRight(moveCommand, leftOver); 
 
        break; 
 
       case 4: 
 
        MoveLeftRight(moveCommand, leftOver); 
 
        break; 
 
       case 5: 
 
        Pass(moveCommand, leftOver); 
 
        break; 
 
       case 6: 
 
        DrawArrow(); 
 
        break; 
 
       case 9: 
 
        break; 
 
       default: 
 
        Console.WriteLine("Wrong number entered!!!"); 
 
        break; 
 
      } 
 

 
      //Console.WriteLine("leftCount {0}\trightCount {1}\ta {2}\tb {3}\ncountLeft {4}\tcountRight {5}\nDirections {6}", leftCount, rightCount, a, b, countLeft, countRight, Directions(countLeft,countRight)); //Just for checking values 
 
     } while (moveCommand != 9); 
 

 
     Console.Read(); 
 
    } 
 

 
    public static string Directions(int x, int y) //Determine directions, V for vertical, H for horizontal 
 
    { 
 
     string[,] Direction = { {"-V","H","V","-H" }, 
 
           {"-H","-V","H","V" }, 
 
           {"V","-H","-V","H" }, 
 
           {"H","V","-H","-V" }}; 
 

 
     return Direction[x, y]; 
 
    } 
 
    public static void MoveLeftRight(int moveCommand, int count) 
 
    { 
 
     if (moveCommand == 3 || moveCommand == 4)//Determine the directions 
 
     { 
 
      if (moveCommand == 3) 
 
      { 
 
       rightCount++; 
 
       countRight = count; 
 
      } 
 
      else 
 
      { 
 
       leftCount++; 
 
       countLeft = count; 
 
      } 
 
     } 
 

 
    } 
 
    public static void Pass(int moveCommand, int leftOver) 
 
    { 
 

 
     if (leftOver >= 20) 
 
     { 
 
      Console.WriteLine("Exceed limit of array!"); 
 
     } 
 
     else if (leftOver < 20) 
 
     { 
 
      if (Directions(countLeft, countRight) == "-V") 
 
      { 
 
       if (a - (int)leftOver >= 0) 
 
       { 
 
        a -= (int)leftOver; 
 
       } 
 
       else 
 
       { 
 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", a); 
 
       } 
 
      } 
 
      else if (Directions(countLeft, countRight) == "V") 
 
      { 
 
       if (a + (int)leftOver < 20) 
 
       { 
 
        a += (int)leftOver; 
 
       } 
 
       else 
 
       { 
 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - a)); 
 
       } 
 
      } 
 
      else if (Directions(countLeft, countRight) == "-H") 
 
      { 
 
       if (b - (int)leftOver >= 0) 
 
       { 
 
        b -= (int)leftOver; 
 
       } 
 
       else 
 
       { 
 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", b); 
 
       } 
 
      } 
 
      else 
 
      { 
 
       if (b + (int)leftOver < 20) 
 
       { 
 
        b += (int)leftOver; 
 
       } 
 
       else 
 
       { 
 
        Console.WriteLine("Exceed limit of array! Do not enter more than {0} passes!", (19 - b)); 
 
       } 
 
      } 
 
     } 
 

 
    } 
 
    public static void DrawArrow() 
 
    { 
 
     for (int x = 0; x < Walk.GetLength(0); x++) 
 
     { 
 
      for (int y = 0; y < Walk.GetLength(1); y++) 
 
      { 
 
       if (showArray[x, y] == 0) 
 
       { 
 
        Console.Write(" "); 
 
       } 
 
       else 
 
       { 
 
        Console.Write("*"); 
 
       } 
 
      } 
 
      Console.WriteLine(); 
 
     } 
 

 
    } 
 
    public static void DisplayCommand() 
 
    { 
 
     Console.WriteLine("Enter 3 to move Right,\n" + 
 
      "Enter 4 to move Left,\n" + 
 
      "Enter 5,x to determine amount of passes\n" + 
 
      "Enter 2 to move pencil down,\n" + 
 
      "Enter 1 to move pencil up,\n" + 
 
      "Enter 6 to draw the array,\n" + 
 
      "Enter 9 to end the program!\n"); 
 
    } 
 
}​

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