C# 具有给定用户输入的数组的队列
在看过一些在线教程之后,我一直在尝试使用数组编写一个队列算法,数组中的数字来自用户输入。当我运行程序时,删除选项似乎不能正常工作,因为我第一次运行删除选项时,它总是说值为0,但当继续删除选项时,它总是删除最后输入的值,而不是第一个值C# 具有给定用户输入的数组的队列,c#,arrays,queue,C#,Arrays,Queue,在看过一些在线教程之后,我一直在尝试使用数组编写一个队列算法,数组中的数字来自用户输入。当我运行程序时,删除选项似乎不能正常工作,因为我第一次运行删除选项时,它总是说值为0,但当继续删除选项时,它总是删除最后输入的值,而不是第一个值 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; name
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') ;
}
}
}
语句需要在Add块中重新排列,如下所示(j++操作需要移到[j]=v操作旁边): 调试代码比您想象的要容易。它还将帮助您更多地了解代码执行时会发生什么,并帮助您编写更好的代码。
int v; //value
v = int.Parse(Console.ReadLine());
a[j] = v;
j++;
rear++;