英文:
Comparison between string and serial port input is always false
问题
我正在制作一个游戏,在游戏中我通过串口(Arduino)获取骰子输入。由于输入不仅仅是一个数字,而是 "e" + 我想要的数字,我正在尝试在Visual Studio中获取这个数字。
然而,这并不像你期望的那么简单。我正在使用简单的if语句,看看我的代码:
string RolledNumberCode = Program.form1.DicePort.ReadExisting();
if (RolledNumberCode.Contains("e"))
{
MessageBox.Show(RolledNumberCode);
int RolledNumber = 0;
if (RolledNumberCode.Contains("1")) { RolledNumber = 1; }
else if (RolledNumberCode.Contains("2")) { RolledNumber = 2; }
else if (RolledNumberCode.Contains("3")) { RolledNumber = 3; }
else if (RolledNumberCode.Contains("4")) { RolledNumber = 4; }
else if (RolledNumberCode.Contains("5")) { RolledNumber = 5; }
else if (RolledNumberCode.Contains("6")) { RolledNumber = 6; }
dice.RollAnalog(RolledNumber);
}
在这之后,似乎不起作用,我使用消息框进行了测试,C#确实正确读取了RolledNumberCode,例如,一个消息框弹出显示e4。但是当我将RolledNumber放入MessageBox中时,它总是为0。
有人知道我在这里做错了什么吗?我强烈认为我的代码中只是一个简单的错误,但我找不到它
英文:
I am making a game where I get dice input from the serial port (Arduino). Since the input isn't just simply a number but is "e" + the number I am trying to get the number in Visual Studio.
This, however, doesn't go as simply as you'd expect. I am using simple if statements, see my code:
string RolledNumberCode = Program.form1.DicePort.ReadExisting();
if (RolledNumberCode.Contains("e"))
{
MessageBox.Show(RolledNumberCode);
int RolledNumber = 0;
if (RolledNumberCode.Contains("1")) { RolledNumber = 1; }
else if (RolledNumberCode.Contains("2")) { RolledNumber = 2; }
else if (RolledNumberCode.Contains("3")) { RolledNumber = 3; }
else if (RolledNumberCode.Contains("4")) { RolledNumber = 4; }
else if (RolledNumberCode.Contains("5")) { RolledNumber = 5; }
else if (RolledNumberCode.Contains("6")) { RolledNumber = 6; }
dice.RollAnalog(RolledNumber);
After this didn't seem to work I tested it with messageboxes and the c# does read the RolledNumberCode correctly, for example a messagebox pops up showing e4. But then I put the RolledNumber in a MessageBox, it is always 0.
Does somebody know what I am doing wrong here? I strongly think there is just a simple error in my code but I can't find it
答案1
得分: 1
将代码中的英文部分翻译如下:
"Instead of if else
ladder I would suggest, remove e
from string i.e "e1"
to "1"
and assign it to RolledNumber
"
建议不使用if else
梯形结构,而是从字符串中移除e
,即从"e1"
改为"1"
,然后赋值给RolledNumber
。
string RolledNumberCode = Program.form1.DicePort.ReadExisting();
if (RolledNumberCode.Contains("e"))
{
int RolledNumber = Convert.ToInt32(RolledNumberCode.Replace("e",""));
dice.RollAnalog(RolledNumber);
}
英文:
Instead of if else
ladder I would suggest, remove e
from string i.e "e1"
to "1"
and assign it to RolledNumber
string RolledNumberCode = Program.form1.DicePort.ReadExisting();
if (RolledNumberCode.Contains("e"))
{
int RolledNumber = Convert.ToInt32(RolledNumberCode.Replace("e",""));
dice.RollAnalog(RolledNumber);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论