Use for loop with if and else
I have a situation where I have to do some thing like this
for (int i = 0; i < list.size; i++) //Master for loop
{
//I need a control statement here to control list1 i.e. only if statement
if (time == list1.get(someInteger))
{
//do something
}
else
{
//do something else
}
}
But every "if" should be followed by an "else", and I don't seem to understand how to go about it. Ive tried do and while but to no avail. For me it is important to execute both if and else, yet have a control statement for only "if".
Is that possible?
With your current constraints and description and rational assumptions No .
For me it is important to execute both if and else, yet have a control statement for only "if".
This violates the specification of what a if...else...
is. You cannot execute both if and else and keep the if...else...
structure. Logically you could drop the else
and just have the code in the else inside the loop as other answers have pointed out. However, if you actually do need to keep if
and else
you need to clarify why so we have a context to answer your question.
If there is some tricky stuff unstated here you might also have a look at switch
and use a Goto Case
setup. Might be worth saying this probably wouldn't be recommended by many seasoned programmers. Switch statement fallthrough in C#?
...You don't need an else
with every if
. It's as simple as that.
try:
for (int i = 0; i < list.size; i++) //Master for loop
{
//I need a control statement here to control list1 i.e. only if statement
if (time == list1.get(someInteger))
{
//do something
}
//do the other something
}
The if will only be hit if the condition is met, the other part will always be hit.
链接地址: http://www.djcxy.com/p/84496.html上一篇: C#中的开关与下一个非结合的情况是空的
下一篇: 用if和else循环