【问题标题】:Queue with array given user input给定用户输入的数组队列
【发布时间】:2019-12-01 23:21:10
【问题描述】:

看了一些在线教程后,我一直在尝试使用数组编写队列算法,数组中的数字来自用户输入。当我运行程序时,删除选项似乎无法正常工作,因为我第一次运行删除选项时它总是说值为 0,但是当继续删除选项时它总是删除最后输入的值,而不是第一个。

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

  namespace queue_test
 {
  class Program
{
    static void Main(string[] args)
    {
        int max = 10;
        int []a;//array
        a = new int[max + 1];
        int b; //user input
        int front = 0;
        int rear = 0;

        int j = 0;

        do
        {
            Console.WriteLine
                 ("What do you want to do?");

            Console.WriteLine();

            Console.WriteLine("Add = 1");
            Console.WriteLine("Delete = 2");
            Console.WriteLine("Exit = 3");

            Console.WriteLine();

            b = int.Parse(Console.ReadLine());

            Console.WriteLine();

            if (b == 1)
            {
                Console.WriteLine("You selected to Add");

                if (rear == max)
                { 
                    Console.WriteLine("The Queue is full");

            }

            else
                Console.WriteLine("What value do you want to add?");

            int v; //value
            v = int.Parse(Console.ReadLine());
            j++;
                a[j] = v;
            rear++;
        }

           else if (b == 2)

        {
            Console.WriteLine();
            Console.WriteLine("You selected to Delete");


                if (front == rear)
                {
                    Console.WriteLine(" Queue is empty");
                }

                else

                    Console.WriteLine("The deleted value is:" + a[front++]);

            }

         else if (b == 3)
            {
                Console.WriteLine("Exit program");
                Console.WriteLine();
                Console.WriteLine("Press Enter to exit");
                Console.ReadLine();
                Environment.Exit(0);

            }
            else

            {
                Console.WriteLine("Enter a matching option");
                Console.WriteLine();
            }

        } while (b != 'X') ;
    }
}
}

【问题讨论】:

标签: c# arrays queue


【解决方案1】:

Add块中的语句需要重新排列,如下图(j++操作需要移到a[j] = v操作旁边):

int v; //value
v = int.Parse(Console.ReadLine());
a[j] = v;
j++;
rear++;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多