如何使用开关捕捉奇数

问题描述 投票:1回答:7

以下代码应打印整数值是奇数还是偶数,并且通过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
java switch-statement fall-through
7个回答
8
投票

i+=2更改为i++i+=2将使您将i的值设置为2,4,6,8,10,这仅表示偶数。

switch(i%2)
  {
  case 0:
     //even number
     break;
  case 1:
     //Odd Number
     break;
  }

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");
  }
}

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 here的更多信息。


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

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
    }

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

-1
投票

[请帮助我完成任务。

© www.soinside.com 2019 - 2024. All rights reserved.