如何使用 switch 语句?
我试图更好地理解 switch 语句。我不需要代码,但需要一个关于如何完成它的演练。
如果有人输入 7 位数字的电话号码 EG。 555-3333 但将其输入为“jkl-deff”,因为它将对应于拨号盘上的字母,我如何将输出更改回数字?
这行得通吗:
switch (Digit[num1])
case 'j,k,l':
num1 = 5;
break;
case 'd,e,f':
num1 = 3;
break;
I am trying to understand the switch statement better. I don't need the code but kinda a walkthrough on how it would be done.
If someone enters a 7 digit phone number EG. 555-3333 but enters it as "jkl-deff" as it would correspodnd to the letters on the dial pad, how would I change the output back to numbers?
Would this work:
switch (Digit[num1])
case 'j,k,l':
num1 = 5;
break;
case 'd,e,f':
num1 = 3;
break;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要使用 switch 语句执行此操作,您必须遍历 char 数组,切换每个字符。将所有具有相同编号的字符分组在一起。
就像
那句话一样,我不确定 switch case 是最好的方法。我不知道什么是最好的,但感觉有些不对劲:)
编辑
i 是当前考虑的字符的索引。您的电话号码将包含 7 个(或 8 个、10 个或 12 个字符的字符串,具体取决于格式)。您必须一次获取每个字符......因此在上面的示例中,phone[0] = 'j'。
To do that with a switch statement, you'd have to walk through the char array, switching on each character. Group all the chars that have the same number together.
Something like
That said, I'm not sure that switch case is the best way to do that. I don't know what would be the best off the top of my head, but something feels wrong about this :)
Edit
The i would be the index of the current character under consideration. You'll have a 7 (or 8 or 10 or 12 character string depending on formatting) for a phone number. You'd have to take each character at a time.. so phone[0] = 'j' in the above example.
我不会使用开关!
I would not use a switch!
您可能可以这样做:
将字符转换为电话键盘数字。最后的 num==8 部分处理 9 键上的额外数字。
总而言之,它看起来像这样:
另外,关于 switch 语句的注释:“case”和“:”之间的项目必须与“switch()”部分指定的项目具有相同的类型。该类型必须是标量,不包括字符串之类的东西。
You could probably do it like this:
to convert a character to a phone pad digit. The num==8 part at the end handles the exra digit on the 9 key.
Altogether it would look like this:
Also, a note about the switch statement: The item that comes between the "case" and the ":" has to have the same type as the thing specified by the "switch()" portion. And that type must be a scalar, which excludes things like strings.