简体   繁体   中英

Incrementing in Dr.Java

Write a RECURSIVE method 'countToBy' that takes two integer parameters n and m and that produces output indicating how to count to n in increments of m.

For example, to count to 10 by 1 you'd say: countToBy(10, 1); which should produce the following output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

The increment does not have to be 1. For example, the following call indicates that we want to count to 25 in increments of 4: countToBy(25, 4); which produces this output: 1, 5, 9, 13, 17, 21, 25


My Code for this is:

import java.util.*;
import java.io.*;

public class CountBy {

  public static void main(String[] args) { 
    countToBy(34, 5);
    System.out.println(); 
    countToBy(3, 6);
    System.out.println(); 
    countToBy(17, 3);
    System.out.println(); 
  }

  // *** Your printSorted method goes here ***
  public static void countToBy(int max, int var){
    if (max < var)
      System.out.print("Error, max value too low or skip value too high.");
      else{
        for (int x = var-1; x<=max; x = x + var){
          System.out.print(x + ", ");
}
    }
}
}

This works, but I feel like I am missing something... anyhelp would be appreciated.

Just to give you an idea how to write such recursive method:

public static void method(int x, int y){
        if(x<y) return;
        method(x-1, y);
        System.out.print(x + " ");      
}

This method prints sequence of number from y to x . So for method(20,10); it will print out: 10 11 12 13 14 15 16 17 18 19 20 .

public class test {
void counttoby(int n,int m,int aff){
    if(aff==n) System.out.println(n);
    else{
        if(n<aff) System.out.println("error");
        else{
        counttoby(n,m,aff+m);
        System.out.println(aff);
        }
    }
}
public static void main(String[] args) {
    test t= new test();
    t.counttoby(10, 1,1);

}

}

try this code okay

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM