Объект не изменяется при отправке в метод в Java? - PullRequest
0 голосов
/ 28 февраля 2019

объект, который я создаю в main и передаю моему методу setValue, не меняет значение объекта в main.я думал, что объекты были переданы по ссылке, и только примитивные типы данных были переданы по значению.это неправильно?или это другая проблема в моем коде

, идея состоит в том, что массив объектов отправляется методу setValue.

a temporaryObject создается и присваивается значения, которые вводит пользователь.

затем временный объект и массив объектов отправляются в другой метод (findPlace), чтобы найти правильное местоположение в массиве, для которого оно должно быть (наибольшее в postion 0 и самое низкое в последнем position).

затем он возвращает местоположение как целое число с именем place для setValueMethod.

затем отправляет массив объектов и temporaryobject в метод add one

addOne метод использует Location для вставки (переменная размещения) и перемещает каждый position вниз на одну position и добавляет временный объект в правильный position.

public static int addOne(Footballer[] theArray, int place, Footballer theObject, int noOfValues)
        {
            int step;

            if (noOfValues == 0)
                {
                    theArray[0] = theObject;
                    noOfValues ++;  
                }
            else
                {                   
                    for (step = noOfValues - 1 ; step >= place; step --)
                        {
                            theArray[step + 1] = theArray[step] ;                       
                        }
                    theArray[place] = theObject;
                }

            return noOfValues;
        } // addOne()

    public static int findPlace(Footballer[] theArray, String theName, int noOfValues)
        {
            int step; 
            int place;

            step = 0 ;
            while ((step < noOfValues) && (theName.compareTo(theArray[step].getName()) > 0))
            {
                step ++;
            }

            place = step ;   // Finds the correct location of place 

            return place;

        } // findPlace()

    // initialises the value of the number of players
    public static int howManyPlayer()
        {
            int NUMOFPLAYERS;
            Scanner num = new Scanner(System.in);

            System.out.print("Enter the number of players\t\t:\t");
            NUMOFPLAYERS = num.nextInt();

            return NUMOFPLAYERS;
        }// howManyPlayer()

    public static void print(Footballer[] allPlayers, int amntOfPlayers)
        {
            // print attributes of all players to screen
            for(int i = 0; i < amntOfPlayers; i++)
                {
                    String printableAttributes;

                    printableAttributes = allPlayers[i].toString();

                    System.out.println(printableAttributes);
                    System.out.println();
                    System.out.println();
                    System.out.println();
                }
        } // print()

        // initialises the values of all of the players int the array
    public static Footballer[] setValue(Footballer[] playerArr, int NUMOFPLAYERS)
        {
            Scanner str = new Scanner(System.in);
            Scanner num = new Scanner(System.in);
            Footballer tempPlayer;
            String curName; // current name
            int curGoals; // current number of goals
            int curPoints; // current number of points
            int noOfElements = NUMOFPLAYERS;
            int place;

            for(int i = 0; i < NUMOFPLAYERS; i++)
                {
                    System.out.println("Player " + (i+1));
                    System.out.print("Enter a name\t\t\t\t:\t");
                    curName = str.nextLine();
                    System.out.print("Enter how many goals they scored\t:\t");
                    curGoals = num.nextInt();
                    System.out.print("Enter how many points they scored\t:\t");
                    curPoints = num.nextInt();

                    tempPlayer = new Footballer(curName, curGoals, curPoints);

                    System.out.println(tempPlayer.getName());
                    System.out.println(tempPlayer.getGoals());
                    System.out.println(tempPlayer.getPoints());

                    place = findPlace(playerArr, curName, noOfElements);
                    noOfElements = addOne(playerArr, place, tempPlayer, noOfElements);

                    System.out.println();
                    System.out.println();
                    System.out.println();
                }// for

            return playerArr;
        } // setValue()

    // the init metod bellow it meant to initalise every postion of to 
    //this initialisation method was only added to stop the Exception-in-thread-main-java-lang-NullPointerException
    public static Footballer[] initArr(Footballer[] theArray, int noOfElements)
        {
            for(int i = 0; i < noOfElements+1; i++)
                {   
                    theArray[i] = new Footballer("", 0, 0);
                }// for
            return theArray;
        }

    public static void main(String[] args)
        {
            // declarations
            Scanner str = new Scanner(System.in);
            Scanner num = new Scanner(System.in);
            final int NUMOFPLAYERS;
            Footballer footballers[]; 
            String curName; // current name
            int curNumOfGoals; // current number of goals
            int curNumOfPoints; // current number of points

            // initialisations
            NUMOFPLAYERS = howManyPlayer();
            footballers = new Footballer[NUMOFPLAYERS+1]; 

            footballers = initArr(footballers, NUMOFPLAYERS);
            setValue(footballers, NUMOFPLAYERS); // sets values of footballers[] in order

            print(footballers, NUMOFPLAYERS); // print all player attributes
        }

, еслиВы хотите, чтобы я добавил Footballer класс, который я сделаю, но, по сути, это так.

Мутаторы:

  1. setName для установки переменной имени объекта
  2. setGoals для установки количества забитых голов
  3. setPoints для установки количества мячейЗабито целых чисел

селекторы:

  1. getName возвращает имя, установленное для объекта
  2. getGoals возвращает количество целей, которые имеет объектscored
  3. getPoints возвращает количество баллов, набранных объектом

другие методы:

  1. toString возвращает строку со всемизначения атрибутов объектов
  2. totalPoints устанавливает totalNumOfPoints = pointsScored + (goalsScored*3) и returns totalNumOfPoints.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...