Link to home
Avatar of Thanatoo
Thanatoo

asked on

Problem with my Array

The txt file is
10
5.15
15
5.875
30
6.25                        

The code for my array is wrong.

for (int i = 0; i < array.size(); i++)
                         {
                    String[] line = ((String) array.get(i)).split("\n"); //I do not think this is the right split
                    YearlyInterestArrayNew[i] = line[1].trim(); // This is on the first line
                    TermArrayNew[i] = line[2].trim(); //This is on the second line
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can read it using a Scanner or BufferedReader. split would be done if it were a String
Try

for (int i = 0; i < array.size(); i++)
    arrayX[i] = line(i + 1);
Avatar of Thanatoo
Thanatoo

ASKER

I need to do it this way though. It was working but I needed to use this txt file insted.
This is more like it i think

int ixTerm, ixRate;
ixTerm = ixRate = 0;
for (int i = 0; i < array.size(); i++) {
      if (i % 2 == 0) {
            TermArrayNew[ixTerm++] = line[i + 1].trim();
      }
      else {
            YearlyInterestArrayNew[ixRate++] = line[i + 1].trim();      
      }
}      
I was using a txt file

5.35, 7
5.50, 15
5.75, 30

and code was

 FileReader InputFile;
          try {
               InputFile = new FileReader("data2.txt");
               BufferedReader data = new BufferedReader(InputFile);
               String aline = null;
               java.util.ArrayList array = new java.util.ArrayList();
               while ((aline = data.readLine()) != null) array.add(aline);
               YearlyInterestArrayNew = new String[array.size()];
               TermArrayNew = new String[array.size()];
               

               for (int i = 0; i < array.size(); i++)
               {
                    String[] line = ((String) array.get(i)).split(",");
                    YearlyInterestArrayNew[i] = line[0].trim();
                    TermArrayNew[i] = line[1].trim();
               }

               InputFile.close();
          } catch (Exception e1) {
               e1.printStackTrace();
          }
that worked great

but now the txt file is
10
5.15
15
5.875
30
6.25
This

>>for (int i = 0; i < array.size(); i++) {

should be

for (int i = 0; i < line.length; i++) {
That gave me a lot of errors
My current code with correction should work for you
you don't need that loop try something like this:


               InputFile = new FileReader("data2.txt");
               BufferedReader data = new BufferedReader(InputFile);
               String aline = null;
               java.util.ArrayList array = new java.util.ArrayList();
               while ((aline = data.readLine()) != null) array.add(aline);
               YearlyInterestArrayNew = new String[] { (String)array.get(1), (String)array.get(3), (String)array.get(5)};
               TermArrayNew = new String[] { (String)array.get(0), (String)array.get(2), (String)array.get(4)};
               
OK. You can actually read the values from 'array'

int ixTerm, ixRate;
ixTerm = ixRate = 0;
for (int i = 0; i < array.size(); i++) {
     if (i % 2 == 0) {
          TermArrayNew[ixTerm++] = ((String)array.get(i)).trim();
     }
     else {
          YearlyInterestArrayNew[ixRate++] = ((String)array.get(i)).trim();
     }
}    
And that code, btw will work irrespective of the number of entries in your text file, as, unlike the previous example code, the values are not hard-coded
int ixTerm, ixRate;
ixTerm = ixRate = 0;
for (int i = 0; i < line.length; i++) {
     if (i % 2 == 0) {
          TermArrayNew[ixTerm++] = line[i + 1].trim();
     }
     else {
          YearlyInterestArrayNew[ixRate++] = line[i + 1].trim();    
     }
}

gives me a lot of errors
did u try the code I posted?
That worked but I was using the wrong txt file.

the old file was split by , this one is on different lines

I was using a txt file

5.35, 7
5.50, 15
5.75, 30

New txt file
10
5.15
15
5.875
30
6.25


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DecimalFormat;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Week4KennethIA extends JFrame implements ActionListener {

     
     //Declareing Variables  
     int totalYears;
     double loanAmount;
     double interest;
     double monthlyPayment;
       
     //Declaring an Array
     String YearlyInterestArrayNew[] = null;
     String TermArrayNew[] = null;
     String InputFile = ".\\Data.dat";
             
     //Creating Row one and its Intro Label
     JPanel row1 = new JPanel();
     JLabel Intro_label = new JLabel("Enter Information to Calculate Payment", JLabel.CENTER);

     //Creating Row two for loanAmount with label and text field    
     JPanel row2 = new JPanel(new GridLayout(1, 2));// 1 row, 2 columns
     JLabel loanAmount_label = new JLabel("Principal Amount $",JLabel.LEFT);
     JTextField loanAmount_txt = new JTextField(10);
     
     //Creating Row two for payment with label and text field
     JPanel row5 = new JPanel(new GridLayout(1, 2));// 1 row, 2 columns
     JLabel payment_label = new JLabel("Monthly Payment", JLabel.LEFT);      
     JTextField payment_txt = new JTextField(10);

     // Creating buttons with a CENTER Layout horizontal and vertical gap of 10    
     JPanel button = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
     JButton clearButton = new JButton("Clear");
     JButton exitButton = new JButton("Exit");
     JButton calculateButton = new JButton("Calculate");
     JButton helpButton = new JButton("Help");
       
     JPanel row6 = new JPanel(new GridLayout(1, 4));
     JLabel columns_label = new JLabel("Month Number                       Amount Principal                             Amount Interest            Principal Left");
     //Set Text Area
     JTextArea displayArea = new JTextArea(10, 35);
     JScrollPane scroll = new JScrollPane(displayArea);
       
     Menu LoanOptions = new Menu("LoanOptions", true);  

     public Week4KennethIA() {
       
          // create an instance of the menu  
          MenuBar mnuBar = new MenuBar();
          setMenuBar(mnuBar);
         
          // construct and populate the File menu
          mnuBar.add(LoanOptions);                      
                         
           
          //Sets the size to 600 pixels by 400 pixels      
          setSize(600, 400);
          // Program will exit when exit button on window is clicked
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          // Creates container called pane
          Container pane = getContentPane();

          //Adding rows
          pane.add(row1);
          pane.add(row2);
          pane.add(row5);

          //Labels and text fields for each row added
          row1.add(Intro_label);
          row2.add(loanAmount_label);
          row2.add(loanAmount_txt);
          row5.add(payment_label);
          row5.add(payment_txt);

          //sets payment amount window so it cannot be changed by user
          payment_txt.setEnabled(false);

          //Adding Buttons
          button.add(calculateButton);
          button.add(clearButton);
          button.add(exitButton);
          button.add(helpButton);
          pane.add(button);
               
          pane.add(row6);
          row6.add(columns_label);
                pane.add(scroll);

         
          //Setting the Layout, Components are laid out vertically from top to bottom.
          pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
          //Makes window visible          
          setVisible(true);
          //Sets the contents to pane          
          setContentPane(pane);

          //adding Listeners
          calculateButton.addActionListener(this);
          clearButton.addActionListener(this);
          exitButton.addActionListener(this);
          helpButton.addActionListener(this);

   
            FileReader InputFile;
          try {
               InputFile = new FileReader("data2.txt");
               BufferedReader data = new BufferedReader(InputFile);
               String aline = null;
               java.util.ArrayList array = new java.util.ArrayList();
               while ((aline = data.readLine()) != null) array.add(aline);
               YearlyInterestArrayNew = new String[array.size()];
               TermArrayNew = new String[array.size()];
             

               for (int i = 0; i < array.size(); i++)
               {
                    String[] line = ((String) array.get(i)).split(",");
                    YearlyInterestArrayNew[i] = line[0].trim();
                    TermArrayNew[i] = line[1].trim();
               }

               InputFile.close();
          } catch (Exception e1) {
               e1.printStackTrace();
          }

          MyMenu();
     }

 
       public void MyMenu()
       
       {
     
     for (int i = 0; i < TermArrayNew.length; i++)
       {
            LoanOptions.add(TermArrayNew[i] + " years @ " + YearlyInterestArrayNew[i]+ "%");
     }
     }
       


       //If statement for buttons
     public void actionPerformed(ActionEvent event){
         
                //creates event where if exit on menu is pressed then program will exit
          String arg = event.getActionCommand();
          if (arg == "Exit")
          {
                     System.exit(0);
          }
               
               
          Object command = event.getSource();
         
                //If entries are not correct when the Calculate button is pressed
                //an Error message will appear
          if(command == calculateButton)
          {
               try
               {
                              displayArea.setText(null);
                                Payment();
               }
               catch(NumberFormatException e)
               {
                    JOptionPane.showMessageDialog(null, "Use only numbers and decimals",
                                                             "Invaild Entry", JOptionPane.ERROR_MESSAGE);
               }
          }
          //
                if(command == helpButton)
          {
               {
                    JOptionPane.showMessageDialog(null, "Use only numbers and decimals\nDo not use any special characters.",
                                                             "Help", JOptionPane.INFORMATION_MESSAGE);
               }
          }
                //Makes the cLear Button clear out all entries
          if(command == clearButton)
          {
               loanAmount_txt.setText(null);
               payment_txt.setText(null);
                         displayArea.setText(null);
          }
         
                //Makes the Exit button exit program when pressed
          if(command == exitButton)
          {
               System.exit(0);
          }
     }

     public void Payment()
       {

        /**Declare variables, gets Text, converts Strings*/
        int i = 0;
        totalYears = Integer.parseInt(TermArrayNew[i]);
        double interest1 = Double.parseDouble(YearlyInterestArrayNew[i]);    
        double loanAmount = Double.parseDouble(loanAmount_txt.getText());            
        double interest = interest1 / 100;
        double perMonthRate = interest / 12;                                      
        double termMonths = totalYears * 12;
                                     


        /**
        Monthly Payment Calculation

        Formula M = P * ( J / (1 - (1 + J) ** -N))
        Where:
        P = principal, the initial amount of the loan
        I = the annual interest rate (from 1 to 100 percent)
        L = length, the length (in years) of the loan
        J = monthly interest in decimal form = I / (12 x 100)
        N = number of months over which loan is amortized = L x 12
        */      

        double monthlyPayment = loanAmount * (perMonthRate/(1 - Math.pow((1 + perMonthRate),(-termMonths))));

        //formats numbers to display dolar sign and only two decimal places
        DecimalFormat dec = new DecimalFormat("\u00A4#,##0.00");      
        //Changes format of Payment to $#,###.##            
        payment_txt.setText("" + dec.format(monthlyPayment));

       
        double interestPaid = 0;                                
        double monthlyPrincipal = 0;                          
        double principalBalance = loanAmount;                    
        int paymentNumber = 1;                                  

       
       for(int y = 1; y <= totalYears; y++)
          {                                                      
            displayArea.append("");                                


           for (int m = 0; m<12; m++)
            {    
                interestPaid = principalBalance * perMonthRate;
                monthlyPrincipal = monthlyPayment - interestPaid;
                principalBalance = principalBalance - monthlyPrincipal;

                displayArea.append("Month "+paymentNumber+"\t\t"
                                       +dec.format(monthlyPrincipal)+"\t\t"
                                       +dec.format(interestPaid)+"\t         "
                                       +dec.format(principalBalance)+"\n");
                        paymentNumber++;
                        displayArea.setCaretPosition(0);
            }
          }
     }
     public static void main(String[] arguments) {
          Week4KennethIA fin = new Week4KennethIA();
          fin.setVisible(true);
     }
}
Your code need to be changed:

>>
           while ((aline = data.readLine()) != null) array.add(aline);
               YearlyInterestArrayNew = new String[array.size()];
               TermArrayNew = new String[array.size()];
             

               for (int i = 0; i < array.size(); i++)
               {
                    String[] line = ((String) array.get(i)).split(",");
                    YearlyInterestArrayNew[i] = line[0].trim();
                    TermArrayNew[i] = line[1].trim();
               }
>>

Your string arrays should be half the size, and actually they'd be better to hold int and double

YearlyInterestArrayNew = new String[array.size()/2];

Replace the rest by what i gave you earlier

that still splits the txt by commas doesn't it
Sorry CEHJ but I am a bit confused
code I posted will work fine with your new text fiule
That code is great but I split it with , the new file is on different lines. It didn't work when I tried it. String[] line = ((String) array.get(i)).split(","); //I can not get it to work. Sorry I am new at this

I was using a txt file

5.35, 7
5.50, 15
5.75, 30

New txt file
10
5.15
15
5.875
30
6.25
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
that code looks suspiciously the same as what I already suggested, just put into a loop :)
Your Awesome Thanks you so much you have no idea how this has stressed me out.
You are both Great
can you explain why you didn't split the points after I originally suggested how to correctly get the values?
Sorry if I missed understood you before. I'm now going to work on the menu buttons.
ASKER CERTIFIED SOLUTION
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Sorry I'll do that I am new at this
thanks :)
The code posted by objects suffers from the flaw i mentioned earlier. You won't be able to add or remove entries from your text file
O posted to the community Board and as soon as it is open I'll split the points
thanks kindly , much appreciated :)
I'll work on that after I figure out how to make the menu come with radio buttons. Thanks CEHJ