如何根据用户输入打印所有3的整数的奇数整数?

时间:2018-06-26 04:53:59

标签: java

import java.util.Scanner;
public class multOfThree
{


   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);


      int num1 = 0;

      while ( num1 % 2 == 0 )
      {

         System.out.print( " Enter an odd integer: " );
         num1 = input.nextInt();

         if ( num1 % 2 != 0 && num1 % 3 == 0 )


         // need to print all user input that are odd and multiple of 3
         // this now only prints one line if user input odd number and is a multiple of 3


         System.out.println( num1+ " Is a multiple of 3" );
      }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下

List<Integer> oddNumsDivisibleByThree = new ArrayList<>();
try (Scanner input = new Scanner(System.in)) {
    int number = 0;

    do {
        System.out.print(" Enter an odd integer or -1 to quit: ");
        number = input.nextInt();
        if (number % 2 != 0 && number % 3 == 0)
            oddNumsDivisibleByThree.add(number);
    } while (number != -1);
}

System.out.println(oddNumsDivisibleByThree);

确保关闭正常打开的I / O资源,否则可能会导致系统内存泄漏。您也可以使用try-finally