Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

public class Main1
{
    public static void main(String[] args)
    {
        printNumbers(7, 3);
    }

    public static int printNumbers(int numValue, int rows) {
        for (int i = 0; i < rows; i++) {
            int x = (int)(Math.random() * 10);
            System.out.print(x);
            if (numValue == x && i < rows) {
                System.out.println(" ");
            } else if (i < rows) {
                System.out.print(x);
            }
        }
        return printNumbers(7, 3);
    }
}    

It's supposed to print random numbers until you reach the numValue, then it creates a new row, and there is a specified amount of rows. Although I put 3 rows, this code keeps running infinite rows. I must be missing something. I'm new to making methods and this is my first crack at it all by myself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

This method would recourse endlessly, as it unconditionally calls printNumbers(7,3) when it returns. From the looks of it, it doesn't seem you even need a return value there - change the return type to void, drop the return statement and you should be OK:

public static void printNumbers(int numValue, int rows){
    for (int i = 0; i < rows; i++) {
         int x = (int)(Math.random() * 10);
         System.out.print(x);
         if (numValue == x && i < rows) {
             System.out.println(" ");
         } else if (i < rows) {
           System.out.print(x);
         }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...