java - 使用do .. while循环以降序打印因数

标签 java loops do-loops

这是我目前坚持的一项任务。
问题是“使用do..while循环以相反顺序打印因子“ n””

此操作的序言允许用户输入任何int值,并首先通过标准if语句查找非因数,然后使用DO循环按降序查找和打印因数。我坚持的事实是,如果不使用数组或其他IF循环,就无法决定如何在DO循环中求值。任何帮助表示赞赏。我将在底部标记代码。 (这不是很漂亮,因为它只是程序的草稿,并且尚未清除。)



import java.util.Scanner;
public class NestedFactorLoop
{
   public static void main(String [] args) //entry point
   {
   
   Scanner keyboard = new Scanner(System.in);
   
   int choice = 0, i = 1, average = 0, nonFactorCounter = 0;
   
      System.out.print("Enter a positive integer: ");
      choice = keyboard.nextInt();
      
      System.out.println("\na. Use a for loop to print non-factors of 26: \n");
      while(choice > i){
         
         if( choice % i != 0){
            System.out.print( i + " ");
            nonFactorCounter++;
            average += i;
         }
         i++;
      }
      
       System.out.println("\n\nNumber of non-factors: " + nonFactorCounter);
       System.out.printf("Average value of non-factors: %-4.2f", (double)(average / nonFactorCounter), " ");
       
       System.out.println("\n\nb. Use a do..while loop to print factors of 26 in reverse order:\n");
      
         ######################################DO loop section   
      i = choice;
         do {
         System.out.print(i + " ");
         i--;
         }while( i > 0 );
       ####################################  
      System.out.println("\n\nNumber of factors: ");
      System.out.println("Average value of factors: ");
            
   } 
   
} 

最佳答案

do...while在每种方式上均与while循环相同,不同之处在于它保证内部的代码块至少执行一次。因此,可以使用do...while循环来实现它,就像使用while循环一样。

choice = i;
average = 0;
int factorCounter = 0;
do {
    if (choice % i == 0) {
        System.out.print(i + " ");
        factorCounter++;
        average += i;
    }
    i--;
} while (i >= 1);

System.out.println("\n\nNumber of factors: " + factorCounter);
System.out.printf("Average value of factors: %-4.2f", (double) (average / factorCounter), " ");

关于java - 使用do .. while循环以降序打印因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61670077/

相关文章:

java - Apache httpclient HTTPGET 解码

java - 从文件中读取不同类型的数据

arrays - 数据步内的 SAS 阵列 DO 循环计算

java - 并发修改异常 : Why does removing the null in List throw this Exception if it´s not the first variable

VBA DO 循环问题

if-statement - 将 Go-to 语句从 FORTRAN 77 转换为 Fortran 90

java - 如果应用程序有多个登录(例如 Facebook、Google 和 Web 服务登录),如何在 Android 中管理 session

java - 如何编写 jSTL 而不是 scriptlet?

java - Spring Java Web服务,异步

r - 打破 R 中的嵌套循环