[英]Incrementing in Dr.Java
編寫一個遞歸方法“countToBy”,它接受兩個整數參數 n 和 m,並產生指示如何以 m 為增量計數到 n 的輸出。
例如,要從 1 數到 10,您可以說: countToBy(10, 1); 這應該產生以下輸出:1, 2, 3, 4, 5, 6, 7, 8, 9, 10
增量不一定是 1。例如,下面的調用表明我們要以 4 的增量計數到 25: countToBy(25, 4); 產生這個輸出: 1, 5, 9, 13, 17, 21, 25
我的代碼是:
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 + ", ");
}
}
}
}
這有效,但我覺得我錯過了一些東西......任何幫助將不勝感激。
只是為了讓您了解如何編寫這種遞歸方法:
public static void method(int x, int y){
if(x<y) return;
method(x-1, y);
System.out.print(x + " ");
}
此方法打印從y
到x
的數字序列。 所以對於method(20,10);
它將打印出: 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);
}
}
試試這個代碼好嗎
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.