我正在使用Powershell来解析CSV文件。 CSV文件是游戏的广告资源,包括其名称,流派和价格。该脚本的目的是对文件输入输出运行基本查询;这是我用来练习新语言文件输入/输出的典型练习。我的一个问题是返回意外的输出。
输入文件:
Name,Genre,Price
Age_of_Empires,RTS,19.99
Europa_Universalis_IV,GS,129.99
Skyrim,RPG,60.00
Oblivion,RPG,30.00
Morrowind,RPG,10.00
Call_of_Duty,FPS,60.00
Knights_and_Merchants,RTS,5.00
Halo,FPS,60.00
Empire_Earth,RTS,10.00
Civilization,GS,59.99
Empires_Apart,RTS,10.00
Battlefield,FPS,59.99
Paper_Mario,RPG,2.99
Victoria_II,GS,9.99
Cultures,RPG,7.99
PUBG,FPS,79.99
Crusader_Kings,GS,9.99
这是我的剧本:
#Parses data file
#Format: [Name],[Genre],[Price]
$file = Import-Csv .\inventory
echo ""
echo "Welcome to `"GameGO`"! here is our current inventory..."
echo $file #Print out the inventory
Read-Host "Press Enter to continue" #This is only here because it keeps the program from running out of order
do #Use a loop to ask if the user wants to inquire many items
{
$choice = Read-Host "What would you like to inquiry?"
#The following blocks of if statements will be used to determine what output to give. Note that the user
#will have to know verbatim what commands to give
if ($choice -eq "average")
{
#Removed for simplicity on Stack Overflow
}
elseif ($choice -eq "highest")
{
$high = 0 #To be safe?
$highGame = "null" #Do I have to initalize this to a value?
ForEach ($line In $file)
{
if ($line.Price -gt $high)
{
$highGame = $line.Name
$high = $line.Price
echo "The new most expensive game is $highGame and it costs $high." #Debug statement!
}
}
echo "The final most expensive game is $highGame and it costs $high."
}
$loop = Read-Host "Would you like to inquire something else? Y\N"
} while ($loop = "Y")
我检查最高价值游戏的if语句给出的值不正确。返回的错误值是一致的,但没有任何我能识别的模式。
正如该计划现在所说:
What would you like to inquiry?: highest
The new most expensive game is Age_of_Empires and it costs 19.99.
The new most expensive game is Skyrim and it costs 60.00.
The new most expensive game is Victoria_II and it costs 9.99.
The final most expensive game is Victoria_II and it costs 9.99.
我已经尝试过更改价格,删除标题,添加新标题,重新排序等等。但是,没有调试测试可以在我能够真正看到我的错误位置的地方产生结果。似乎没有任何理由。我需要另外一双眼睛。
此外,我遇到一个奇怪的错误,其中Read-Host命令导致脚本行无序运行。奇怪的是,它通过添加"按Enter继续"读主机。我现在并不担心,我只包括这个解释,以帮助您理解为什么包含该行。
答案 0 :(得分:1)
在这种情况下,价格将作为字符串存储在csv对象中。只需将其转换为整数或双精度,您的代码就可以正常工作!
if ([double]$line.Price -gt $high)
基本上它按字母顺序工作,这就是为什么你从1开始,然后是6开始,然后是9开始。例如,它跳过Oblivion,因为6是"进一步向下"按字母顺序排列的列表不是3。
希望这有助于解释问题 - 一旦看到问题,它就会非常直观。顺便说一下,鲁本是最好的三明治。