1

以下代码应通过 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
4

6 回答 6

8

更改i+=2i++andi+=2会给你ias的值,2,4,6,8,10这意味着只有偶数。

switch(i%2)
  {
  case 0:
     //even number
     break;
  case 1:
     //Odd Number
     break;
  }
于 2014-10-10T05:06:49.110 回答
2

没有必要给你的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");
  }
}
于 2014-10-10T05:06:21.547 回答
2

我相信直通开关应该是这样的。为简单起见,我省略了您的外部 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 的更多信息。

于 2014-10-10T05:12:12.803 回答
1
     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
于 2014-10-10T05:06:15.527 回答
1

尝试这个

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
    }
于 2014-10-10T05:15:07.477 回答
0
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
于 2019-02-12T11:02:58.950 回答