2016-03-02 2 views
-2

Я новичок в java и изучаю, поскольку я иду, я сейчас работаю над массивами, я, кажется, не понимаю, что я делаю неправильно Вот. Я не думаю, что это правильно потянет данные, this program is suppose to read data from a text file, and ask the user for additional inputs, then display a report. У меня, похоже, проблемы с выходными битами пожертвования, так как я не получил его на работу один раз ... Программная доза компилируется и запускается, netbeans говорит, что все это зеленый, за исключением бит кода с отключенным кодом ниже для метода отображения. Любые предложения, комментарии и баллы в правильном направлении приветствуются =) Также можно использовать некоторые советы о том, как заставить десятичные знаки совмещаться как для вывода текстового файла, так и для вывода на экран программы.Сохранение и получение данных из массива, экспорт в текстовый файл

Основной класс

import java.util.Scanner; 

public class MyEventManager 
{ 
    public static void main(String [] args)   
    { 
     Scanner keyboard = new Scanner(System.in); 
      System.out.printf("\nI will read a text file then add it with user " 
       + "inputs in \norder to display and export a report detailing " 
       + "an event.\n\n"); 
     boolean startOver = false; 

     if (startOver == false) //enter loop 
     { 
      do 
      { 
       //ticket price 
       System.out.printf("What is the single ticket price for " 
         + "the event? "); 
       double singleTicket = keyboard.nextDouble(); 
       //maximum number of donations 
       System.out.printf("What is the maximum number of donations " 
         + "expected for the event? "); 
       int maxDonations = keyboard.nextInt(); 
       //create a new object for event class 
       MyEventClass myEvent = new MyEventClass(singleTicket, 
         maxDonations); 

       if (myEvent.fruityLoops == false) 
        do 
        { 
         myEvent.readAllData(); 
        } 
       while (myEvent.fruityLoops != true); 

       myEvent.displayResults(); 

       System.out.printf("\nWould you like to run program again? " 
         + "[Y/N] - "); 
       String questionAskLoop = keyboard.next(); 

       if ("N".equalsIgnoreCase(questionAskLoop)) 
       { 
        startOver = true; //sets exit condition to end program... 
       } 
      } 
     while(startOver != true);  
     } 
    } 
} 

Второй класс

import java.util.Scanner; 
import java.io.*; 
import java.util.Arrays; 

public class MyEventClass 
{ 
    private final double TICKET_PRICE; 
    private final int []moneyDonated; 
    private double totalTicketsSold; 
    private int DONATION_ARRAY_SIZE; 
    private int storedAmountDonations; 
    private double moneySpent; 
    boolean fruityLoops; 
    private boolean donationSuccess; 
    public static char amountType; 
    public static double amount; 


    public MyEventClass (double singleTicket, int maxDonations) 
    { 
     this.moneyDonated = new int[]{DONATION_ARRAY_SIZE}; 
     this.fruityLoops = false; 
     this.TICKET_PRICE = singleTicket; 
     this.DONATION_ARRAY_SIZE = maxDonations; 
     this.moneySpent = 0; 
    } 

    public boolean myDonation (double donationAmount, int[] moneyDonated) 
    { 
     if (storedAmountDonations == DONATION_ARRAY_SIZE) 
     { 
      return false; 
     } 
     else 
     { 
      moneyDonated[storedAmountDonations] = (int) donationAmount; 
      storedAmountDonations++; 
      return true; 
     } 
    } 

    public void addNewTickets (double addedTickets) 
    { 
     totalTicketsSold += (int) addedTickets; 
    } 

    public double getTicketSales() 
    { 
     return totalTicketsSold; 
    } 

    public double getTicketEnd() 
    { 
     double ticketEnd = totalTicketsSold * TICKET_PRICE; 
     return ticketEnd; 
    } 

    public int [] getMoneyDonated (int[] moneyDonated) 
    { 
     //Calculate and return the total amount of money donated 
     return moneyDonated; 
    } 

    public int storedAmountDonations() 
    { 
     return storedAmountDonations; 
    } 

    public double getMoneySpent() 
    { 
     return moneySpent; 
    } 

    public void sortMethod (char amountType, double amount) 
    { 
     if(amount <= 0)  //positive amount check 
     { 
     throw new IllegalArgumentException("Error Code B-90: Invalid amount " 
       + "(not over 0) -- line: " + amountType + " " + amount 
       + " ignored"); 
     } 
     else if (amountType == 'T' || amountType == 't') //tickets 
     { 
      addNewTickets(amount); 
     } 
     else if (amountType == 'D' || amountType == 'd') //donations 
     { 
      myDonation(amount, moneyDonated); 
      if (donationSuccess == false) //checks if array is full 
      { 
       throw new ArrayIndexOutOfBoundsException ("Error code B-103: " 
         + "The array is full " + amount + " will not be stored" 
         + " in the array"); 
      } 
     } 
     else if (amountType == 'E' || amountType == 'e') //amount spent 
     { 
      moneySpent += amount; 
     } 
     else 
      throw new IllegalArgumentException("Error Code B-113: Invalid item " 
        + "type (not T, D, or E) -- line: " + amountType + " " 
        + amount + " ignored"); 
    } 

    public void readAllData() 
    { 
     int lineCount = 0; 
     Scanner keyboard = new Scanner(System.in); 
     System.out.printf("\nPlease input the file location: "); 
     String readFile = keyboard.next(); 

     try 
     { 
      File inputFile = new File (readFile); 
      Scanner scanFile; 
      scanFile = new Scanner(inputFile); 
      System.out.println("Reading data file...."); 

      while (scanFile.hasNext()) 
      { 
       amountType = scanFile.next().charAt(0); 
       amount = scanFile.nextDouble(); 

       lineCount++; 

       try 
       { 
        sortMethod(amountType, amount); 
       } 
       catch (IllegalArgumentException a) 
       { 
        System.out.printf("\nError code B-145: An error occured " 
          + "while attempting to add the data from file"); 
       } 
       catch (ArrayIndexOutOfBoundsException b) 
       { 
        System.out.printf("\nError code B-150: An error occured " 
          + "while attempting to add to the array."); 
       } 
      } 
      scanFile.close(); 
      System.out.printf("\nThe total amount of readable lines where " 
        + lineCount + " lines.\n\n"); 
     } 
     catch (FileNotFoundException c) 
     { 
      System.out.printf("\nError code B-160: The file " + readFile 
       + " was not found!\n"); 
      fruityLoops = false; //restart program 
     } 
     fruityLoops = true; //contuine on with program 
    } 

    public int getLowest (int[] moneyDonated) 
    { 
     int lowValue = moneyDonated[0]; 
     for(int i=1;i < moneyDonated.length;i++) 
     { 
      if(moneyDonated[i] < lowValue) 
      { 
       lowValue = moneyDonated[i]; 
      } 
     } 

     return lowValue; 
    } 

    public double getAverage(int[] moneyDonated) 
    { 
     int sum = moneyDonated[0]; 
     for(int i=1;i < moneyDonated.length;i++) 
     sum = sum + moneyDonated[i]; 

     double advValue = sum/moneyDonated.length; 

     return advValue; 
    } 

    public int getHighest (int[] moneyDonated) 
    { 
     int maxValue = moneyDonated[0]; 
      for(int i=1;i < moneyDonated.length;i++) 
     { 
      if(moneyDonated[i] > maxValue) 
      { 
       maxValue = moneyDonated[i]; 
      } 
     } 

     return maxValue; 
    } 


    public void displayResults() 
    { 
     double income = 0;//moneyDonated + ticketEnd; 
     double profits = income - moneySpent; 

     Scanner keyboard = new Scanner (System.in); 
     System.out.printf("\nWhere is the file for the report export? "); 
     String reportFile = keyboard.next(); 

     try 
     { 
      File outputFile = new File (reportFile); 
      Scanner scanFile = new Scanner (outputFile); 
      System.out.println("Generating output data file...."); 
      try (BufferedWriter writer = 
        new BufferedWriter(new FileWriter(outputFile))) 
      { 
       writer.write("Event Overall Outcome:"); 
       writer.newLine(); 

       writer.write("Ticket Price %15.2f" + TICKET_PRICE); 
       writer.newLine(); 
       writer.newLine(); 

       writer.write("Donation Analysis:"); 
       writer.newLine(); 

       writer.write("Lowest donation " + getLowest (moneyDonated)); 
       writer.newLine(); 

       writer.write("Adverage donation " + getAverage (moneyDonated)); 
       writer.newLine(); 

       writer.write("Highest donation " + getHighest(moneyDonated)); 
       writer.newLine(); 
       writer.newLine(); 

       writer.write("Profit/Loss Results:"); 
       writer.newLine(); 

       writer.write(totalTicketsSold + "Tickets sold" + getTicketEnd()); 
       writer.newLine(); 

       writer.write(storedAmountDonations() + " Donations " 
         + Arrays.toString(moneyDonated) + " +"); 
       writer.newLine(); 

       writer.write("      --------"); 
       writer.newLine(); 

       writer.write("Total Income " + "%14.2f" + income); 
       writer.newLine(); 

       writer.write("Total Expenses " + "%12.2f" + " -" + moneySpent); 
       writer.newLine(); 

       writer.write("      --------"); 
       writer.newLine(); 

       if (profits < 1) 
       { 
        writer.write(" Event Losses " + "%13.2f " + profits); 
       } 
       else 
       { 
        writer.write(" Event Profits " + "%13.2f " + profits); 
       } 

       writer.flush(); 
       writer.close(); 
      } 
      catch (IOException d) 
      { 
       System.out.printf("\nError code B-280: There was an error " 
         + "while attempting to write to " + reportFile 
         + "\nThe file may be damaged!"); 
      } 
      System.out.printf("\nOutput Success!"); 
     } 
     catch (FileNotFoundException d) 
     { 
      System.out.printf("\nError code B-288: The file " + reportFile 
       + " could not be opened! The report cannot be generated.\n"); 
     } 


     System.out.printf("\nEvent Overall Outcome:"); 

     System.out.printf("\n\n Ticket Price %15.2f", TICKET_PRICE); 

     System.out.printf("\n\n Donation Analysis: "); 
     /*System.out.printf("\n Lowest donation " + "%10.2f", 
     getLowest (moneyDonated)); 
     System.out.printf("\n Adverage donation " + "%10.2f", 
     getAverage (moneyDonated)); 
     System.out.printf("\n Highest donation " + "%10.2f", 
     getHighest(moneyDonated));*/ 

     System.out.printf("\n\n Profit/Loss Results: "); 
     System.out.printf("\n " + totalTicketsSold + " Tickets sold " 
       /*+ "%3.2f"*/ + getTicketEnd()); 
     System.out.printf("\n " + storedAmountDonations() + " Donations " 
       /* + "%3.2f"*/ + Arrays.toString(moneyDonated) + " +"); 
     System.out.printf("\n      --------"); 
     System.out.printf("\n Total Income " + "%14.2f", income); 
     System.out.printf("\n Total Expenses " + "%12.2f" + " -", moneySpent); 
     System.out.printf("\n      --------"); 

     if (profits < 1) 
     { 
      System.out.printf("\n Event Losses " + "%13.2f \n\n", profits); 
     } 
     else 
     { 
      System.out.printf("\n Event Profits " + "%13.2f \n\n", profits); 
     } 
    } 
} 

Это входного текстового файла

T 25 
E 210.99 
T 1 
D 500.00 
E 134.67 
D 1 

Это вывод текстовый файл

Event Overall Outcome: 
Ticket Price %15.2f60.0 

Donation Analysis: 
Lowest donation 500 
Adverage donation 500.0 
Highest donation 500 

Profit/Loss Results: 
26.0Tickets sold1560.0 
1 Donations [500] + 
         -------- 
Total Income %14.2f0.0 
Total Expenses %12.2f -345.65999999999997 
         -------- 
    Event Losses %13.2f -345.65999999999997 

И, наконец, это то, что программа выводит на экран ...

run: 

I will read a text file then add it with user inputs in 
order to display and export a report detailing an event. 

What is the single ticket price for the event? 25 
What is the maximum number of donations expected for the event? 2 

Please input the file location: event.txt 
Reading data file.... 

Error code B-150: An error occured while attempting to add to the array. 
Error code B-150: An error occured while attempting to add to the array. 
The total amount of readable lines where 6 lines. 


Where is the file for the report export? export.txt 

Error code B-288: The file texport.txt could not be opened! The report 
cannot be generated. 

Event Overall Outcome: 

    Ticket Price   25.00 

    Donation Analysis: 

    Profit/Loss Results: 
    26.0 Tickets sold 650.0 
    1 Donations [500] + 
         -------- 
    Total Income   0.00 
    Total Expenses  345.66 - 
         -------- 
    Event Losses  -345.66 


Would you like to run program again? [Y/N] - 

Подобно тому, как FYI, для меня исключение кодов ошибок А является основным классом и B является вторым классом, число следует за это строка кода, из которой пришло сообщение. Просто то, что я пытался помочь мне быстрее найти свое место ...

Моя цель - заставить дисплей выглядеть так.

need to look like this.

+2

У вас слишком много кода и слишком мало информации о реальной проблеме, с которой мы сталкиваемся. – tnw

+0

Моя проблема заключается в том, что мой массив пожертвований не хранит суммы пожертвований из текстового файла в массив и правильно их отображает – Newb2Java

+0

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

ответ

1

Ваша главная проблема в вашем втором классе:

this.moneyDonated = new int[]{DONATION_ARRAY_SIZE}; 

Это не создает массив размера DONATION_ARRAY_SIZE. Правильный синтаксис:

this.moneyDonated = new int[DONATION_ARRAY_SIZE]; 
1

Есть 2 важных вопроса, указанных выше. Во-первых, размер массива. Вы должны иметь что-то вроде этого:

this.DONATION_ARRAY_SIZE = maxDonations; 
    this.moneyDonated = new int[DONATION_ARRAY_SIZE]; 

Во-вторых, логическое donationSuccess будет инициализируется ложь. И у вас есть этот блок кода:

 if (donationSuccess == false) //checks if array is full 
     { 
      throw new ArrayIndexOutOfBoundsException ("Error code B-103: " 
        + "The array is full " + amount + " will not be stored" 
        + " in the array"); 
     } 

Вы никогда не изменить это значение donationSuccess, следовательно, блок кода всегда будет бросать эту ошибку, даже если это не так. Вы должны переосмыслить способ инициализации и установить значение donationSuccess.

+0

Спасибо. Я дам эту мысль и попробую. Я не обязательно ищу ответы на свои проблемы, просто нажал в правильном направлении, это дает мне отправную точку, спасибо =) – Newb2Java

Смежные вопросы