Почему все параметры моего объекта "Сервисы" работают, кроме этого? - PullRequest
0 голосов
/ 05 мая 2020

Я создаю массив List differentServices, состоящий из объектов Services, которые я создаю.

Когда я пытаюсь получить данные из файла, который будет служить в качестве служб с параметрами имя службы, имя файла службы и плата за обслуживание, и при печати значений моего списка массивов differentService я отмечаю, что имя все службы в моем Arraylist различны, и в зависимости от файла, сборы за обслуживание различных объектов в Arraylist все разные и в соответствии с файлом, но имя файла каждого объекта в differentServices одинаково, хотя способ, которым я объявить новые Услуги () - это то же самое, что и для названия услуги и платы за услугу.

Я пытаюсь понять, почему мне нужно, чтобы данные каждого сервиса были разными.

import java.util.*; 
import java.io.*;

public class Assignment2_main {

Services[] a; //a is a Template object
int size;
static String name;
static String fileName;
static double usageFee;
static String toRemoveString = "service=";

 public void ArrayList() {
        a = (Services[]) new Object[10]; //a defined as a list of 10 Objects T
        size = 0;
 }

 public void add(Services item) { //Add item to the end
        if(size == a.length) { //If the size is equal to the length of a
            doubleArray(); //Double the array
        }
        a[size++] = item; //The last object of the array takes the value of item
 }

 public void add(int pos, Services item) { //Add item to specific position
        if(size == a.length) {//Double the array if the size is equal to the length of a
            doubleArray();
        }
        for(int i=size-1; i>pos; i--) { //Every element after the position specified is changing index by one
            a[i+1] = a[i];
        }
        a[pos] = item; //The element at position pos takes the value of item
        size++; //Increment the size
 }

 public Services get(int pos) { //Get value at position pos
        if(pos >= size || pos < 0) { //If the specified position is out of bound, display error
            throw new IndexOutOfBoundsException();
        }
        return a[pos]; //Return the object at position pos
 }

 public Services remove(int pos) { //Remove element at position pos
        if(pos >= size || pos < 0) { //If the specified position is out of bound, display error
            throw new IndexOutOfBoundsException();
        }
        Services temp = a[pos]; //temp object T takes value of the element to remove
        for(int i=pos; i<size-1; i++) { //Every element after the position specified is changing index by one
            a[i] = a[i+1];
        }
        size--; //size of the array decrements by one
        return temp; //Return the removed value
 }

 public int size() { //Return the size of the list
        return size;
 }

 void doubleArray() {
        Services[] newArray = (Services[])new Object[a.length*2]; //Doubles the length of the array a
        for(int i = 0; i < size; i++) { //places all the elements of the array a into array newArray
            newArray[i] = a[i];
        }
        a = newArray; //places all the elements back into a
 }

 public static void main(String[] args) {

     ArrayList<Services> differentServices = new ArrayList<Services>();

     try {
          File configFile = new File("/Users/Yohan/Desktop/CS245Assignment2/config.txt");
          Scanner scanConfigFile = new Scanner(configFile);
          while (scanConfigFile.hasNextLine()) {
            String data = scanConfigFile.nextLine();
            String[] token = data.split(",");
            for(int i=0;i<token.length;i++) {
                if(i==0) {
                    name = token[i].replaceAll("service=", "");
                }
                else if(i==1) {
                    fileName = token[i];
                }
                else if(i==2) {
                    usageFee = Double.parseDouble(token[i]);
                }
                else {
                    System.out.println("Logical Error");
                }
            }
            Services newService = new Services(name, fileName, usageFee);
            //Problem before this
            differentServices.add(newService);
            System.out.println(differentServices.get(0).fileName);
          }

          scanConfigFile.close();
        } catch (FileNotFoundException e) {
          System.out.println("An error occurred.");
          e.printStackTrace();
        }

     System.out.println(differentServices.get(0).fileName);

     String userItemInput = "", userSizeInput = "", userQuantityInput = "";
     Scanner input = new Scanner(System.in);
     while(!(userItemInput.contentEquals("done"))) {
         System.out.println("Enter your next item or 'done':");
         userItemInput = input.nextLine();
            if (userItemInput.contentEquals("done")) {
                continue;
            }
         System.out.println("Size:");
         userSizeInput = input.nextLine();
         System.out.println("Quantity:");
         userQuantityInput = input.nextLine();
     }
 }
}

Вот файл конфигурации:

 service=Instacart,instacart.csv,5.99
 service=Prime,amazon.csv,4.00
 service=Safeway,safeway.csv,3.99
 service=GoogleDelivery,google.csv,6.99
 service=Basket,basket.csv,2.50

А вот и мой Сервис. java файл:

public class Services {

   public String name = "";
   public static String fileName = "";
   public double usageFee = 0;

   //constructor
   public Services(String name, String fileName, double usageFee) {
        this.name = name;
        this.fileName = fileName;
        this.usageFee = usageFee;
    }   
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...