我正在尝试在C#中创建一个5,4数组,其中每个单元格都由用户数据组成。我下面的代码有时有效,但不一致。例如,我可以将数据输入到单元格[4,5]或[3,4]中。但是,有时当我运行代码时,它不接受数据并显示一个空单元格。和任何提示?
decimal[,] departments = new decimal[4, 5];
//int count = 0;
Console.WriteLine("If you would like to run the program, type enter");
string exit = Console.ReadLine();
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
Console.WriteLine("Enter sales");
departments[departmentNo, input] = decimal.Parse(Console.ReadLine());
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
示例输出
0 0 0 0
0 0 0 0
0 0 500 0
500 0 0 0
答案 0 :(得分:2)
您可以使用.GetUpperBound(dimension)
来获取特定尺寸的最大界限(在下面的示例中,每个尺寸将返回1)。一旦掌握了这些,您只需要遍历每个位置即可(我假设您只需要在每个位置填充数据即可。)
这里是一个示例:
int[,] items = new int[2, 2];
int width = items.GetUpperBound(0) + 1;
int height = items.GetUpperBound(1) + 1;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
string input;
int inputValue;
do
{
Console.WriteLine($"Please input value for ({x},{y}): ");
}
while (!int.TryParse(input = Console.ReadLine(), out inputValue));
items[x, y] = inputValue;
}
}
或者,如果您确实需要用户能够指定销售价格所在的位置,则可以更新代码以添加一些验证检查:
while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
if (departmentNo > departments.GetUpperBound(0) || departmentNo < 0)
{
Console.WriteLine("Please enter a valid department number.");
continue;
}
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
if (input > departments.GetUpperBound(1) || input < 0)
{
Console.WriteLine("Please enter a valid input.");
continue;
}
Console.WriteLine("Enter sales");
if (!decimal.TryParse(Console.ReadLine(), out decimal value))
{
Console.WriteLine("Please enter a valid sales figure.");
continue;
}
departments[departmentNo, input] = value;
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}
您可能希望将其更改为与上面的示例类似,以便在输入不正确时不必再次重新启动整个循环。
答案 1 :(得分:0)
由于departments
的长度为[4,5]
,这意味着departmentNo
只能在0-3
范围内,而input
只能在0-4
范围内范围decimal
。另外,±1.0 x 10^28 to ±7.9228 x 10^28
关键字表示128位数据类型,这意味着一个单元格的值在if
范围内,这意味着大约28-29个有效数字。您应该设置一些@Test
public void edocument_status() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String body ="";
Map<String, String> map = new HashMap<String,String>();
map.put("locale", locale);
map.put("empKey", empKey);
map.put("applKey", applKey);
map.put("apprStatCd", apprStatCd);
map.put("returnReason", returnReason);
body=mapper.writeValueAsString(map);
testPostMethod("/edocument/status", body);
}
条件,以确保输入值在可用范围内。