سؤال

I'm asking "how many rows" and hoping it prints out the pascal triangle. But I'm getting an error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method nthPascalRow(int) in the type Pascal is not applicable for the arguments (Scanner) at Pascal.main(Pascal.java:39)

Here's my code

public class Pascal {
    public static int[] nthPascalRow(int row) {
        if (row == 0) {
            int[] result = { 1 };
            return result;

        }
        if (row == 1) {
            int[] result = { 1, 1 };
            return result;
        }
        int[] previous = { 1, 1 };
        for (int r = 2; r <= row; r++) {
            int[] next = new int[r + 1];
            next[0] = 1;
            for (int i = 1; i < r; i++) {
                next[i] = previous[i - 1] + previous[i];
            }
            next[r] = 1;
            previous = next;
        }
        return previous;

    }

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        System.out.println("How many rows?");
        input.nextInt();
        int[] result = nthPascalRow(input);
        for (int r : result) {
            System.out.print(r + " ");
        }   

    }

}
هل كانت مفيدة؟

المحلول

You should to add the import

import java.util.Scanner;

and to use one variable to put the integer entered by user

    int index = input.nextInt();
    int[] result = nthPascalRow(index);

نصائح أخرى

You're getting that error because you're passing in input, which is a Scanner object, whereas the method you're calling expects an int row.

Re-consider what you want to pass to the method.

All you have to do is set

input.nextInt() 

to a variable and then pass that variable to the method example:

int a = input.nextInt();
int[] result = nthPascalRow(a);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top