以下代码应打印整数值是奇数还是偶数,并且通过switch语句和for语句下降
for(int i=2; i<=10; i+=2)
{
switch(i)
{
case 1:
{System.out.printf("\nNot printing odd numbers");}
case 2:
System.out.printf("\n %d is an even number.", i);
//case 3:
//case 4:
}//end switch
}//end for
将i+=2
更改为i++
和i+=2
将使您将i
的值设置为2,4,6,8,10
,这仅表示偶数。
switch(i%2)
{
case 0:
//even number
break;
case 1:
//Odd Number
break;
}
不需要您的for
循环,
for(int i=2; i<=10; i+=2)
i
不会是奇数。根据您的switch
和问题陈述,我认为您想要,
for(int i=1; i<=10; i++) {
switch(i) {
case 2: case 4: case 6: case 8: case 10:
System.out.printf("\n %d is an even number.", i);
break;
default:
System.out.printf("\nNot printing odd numbers");
}
}
我相信,落入式开关应该看起来像这样。为了简单起见,我省略了您的外部for循环。
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 9:
System.out.printf("\nNot printing odd numbers");
break;
case 2:
case 4:
case 6:
case 8:
System.out.printf("\n %d is an even number.", i);
break;
}
您基本上会遇到某些情况(所有奇数和所有偶数)。因此,这个词。您可以阅读有关fallthrough here的更多信息。
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0: // even number
System.out.printf("\n %d is an even number.", i);
break;
case 1: // odd number
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
尝试此
for (int i = 2; i <= 10; i++) {
switch (i % 2) {
case 0:
System.out.printf("\n%d is an even number.", i);
break;
case 1:
System.out.printf("\nNot printing odd numbers");
break;
}// end switch
}// end for
}
nt num=10;//any number you want
nt last=num%10;
switch(last)
{
case 0:
case 2:
case 4:
case 6:
case 8:
System.out.println("numbet is even" +num) ;
break ;
default :
System.out.println("number is odd" +num)
}
//end of switch block
//odd or even using fall through language java
//GAGAN GANJWAR
[请帮助我完成任务。