передача массива в качестве аргумента; Настройка массива в Java с пользовательским вводом с классом сканера - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь принять пользовательский ввод, поместить его в мой массив, отобразить массив и затем распечатать все значения, превышающие значения "n", которые предоставляет пользователь. Я думаю, что я близко, но я не могу получить пользовательский ввод в go в массив. Я продолжаю получать сообщение об ошибке в затмении, когда я вызываю метод (основной в самом низу), "arrayValues" не может быть преобразована в переменную :

import java.util.Arrays;

import java.util.Scanner;

public class LargerThanN {

 //initialize n
static int n;

static int arraySize;

//setup the array
static int [] integerArray = new int [] {};

public static void printGreaterThanN(int[] integerArray, int n) {

    for (int i = 0; i < integerArray.length; i++) {
            if (integerArray[i]>n) { 
                System.out.println(integerArray[i]);

            }
    } 

}

public static int[] fillArrayWithUserInt() {
    Scanner sc = new Scanner(System.in);

    System.out.println("How big will the array be?");
    int arraySize = sc.nextInt();
    sc.nextLine(); // clears rest of input, including carriage return

    int[] integerArray = new int[arraySize];

    System.out.println("Enter the " + arraySize + " numbers now.");

        for (int i = 0; i < integerArray.length; i++) {
        integerArray[i] = sc.nextInt();
    }

    return integerArray;

    }





/**
 * This method prints the array to the standard output
 * @param array
 */
private static void displayArray( int[] integerArray) {

    for (int i = `0; i < integerArray.length; i++) {
        System.out.print(integerArray[i] + " ");
    }
}   

public static void main(String[] args) {

        int [] array ;

        array = fillArrayWithUserInt();

        Scanner sc = new Scanner(System.in);

        fillArrayWithUserInt();

        displayArray(array);

         System.out.println("To which number would you like to compare the rest? Your n value is: ");

            n = sc.nextInt();

        printGreaterThanN(array, n); 

но теперь мой вывод выглядит так:

Насколько большим будет массив?

4

Введите 4 цифры.

1 2 3 4

Насколько большим будет массив?

3

Введите 3 цифры.

1 2 3

1 2 3 4

С каким числом вы хотите сравнить остальные? Ваше значение n:

2

3

4

Ответы [ 2 ]

1 голос
/ 01 мая 2020

Заголовок, следующий код ничего не делает в java ...

public void set(int n, int value) {
    n = value;
}

Вы, кажется, пишете такой код во многих функциях, где должно быть возвращено значение.

Например, определение функции:

static void fillArrayWithUserInt(int[] integerArray, int arraySize, int arrayValues, int n)

Должно быть действительно записано как:

static int[] fillArrayWithUserInt()

Это может быть реализовано следующим образом

public static int[] fillArrayWithUserInt() {
    Scanner sc = new Scanner(System.in);

    System.out.println("How big will the array be?");
    int arraySize = sc.nextInt();
    sc.nextLine(); // clears rest of input, including carriage return

    int[] integerArray = new int[arraySize];

    System.out.println("Enter the " + arraySize + " numbers now.");

    System.out.println("What are the numbers in your array?");

    for (int i = 0; i < integerArray.length; i++) {
        integerArray[i] = sc.nextInt();
    }

    return integerArray;
}

Приведенная выше функция запросит у пользователя размер массива. Создайте массив с заданным размером. Затем предложите пользователю заполнить массив правильным количеством значений. Затем возвращается массив, созданный в этом процессе.

Теперь все, что вы должны обрабатывать иначе, - это найти значение для сравнения. Это должно быть сделано вне функции fillArrayWithUserInt.

Примерно так:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int[] array = fillArrayWithUserInt();
    displayArray(array);
    System.out.println("To which number would you like to compare the rest? Your n value is: ");
    int n = sc.nextInt();

    printGreaterThanN(array, n);
}

Наконец, вам не нужно объявлять переменные stati c в верхней части вашего класса.

Эти строки могут быть удалены:

 //initialize n
static int n;

static int arraySize;

//setup the array
static int [] integerArray = new int [] {};
0 голосов
/ 01 мая 2020

Вот мое решение проверить.

import java.util.Scanner;

public class LargerThanN {
    static int[] integerArray = null;
    static int n ;

    public static void printGreaterThanN() {

        for (int i = 0; i < integerArray.length; i++) {
            if (integerArray[i] > n) {
                System.out.println(integerArray[i]);
            }
        }

    }

    public static void fillArrayWithUserInt() {

        Scanner sc = new Scanner(System.in);

        System.out.println("How big will the array be?");
        int arraySize = sc.nextInt();
        sc.nextLine(); // clears rest of input, including carriage return

        integerArray = new int[arraySize];

        System.out.println("Enter the " + arraySize + " numbers now.");

        System.out.println("What are the numbers in your array?");

        for (int i = 0; i < integerArray.length; i++) {
            integerArray[i] = sc.nextInt();
        }

        System.out.println("To which number would you like to compare the rest? Your n value is: ");
        n = sc.nextInt();

    }

    /**
     * This method prints the array to the standard output
     * 
     * @param array
     */
    private static void displayArray() {

        for (int i = 0; i < integerArray.length; i++) {
            System.out.print(integerArray[i] + " ");
        }
    }

    public static void main(String[] args) {

        fillArrayWithUserInt();

        displayArray();

        printGreaterThanN();

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...