I need help for reading from a .txt file.
My goal in this program is to display the data from the text file to the command prompt. Everything compiles, but its doesnt display the data.
It probably has to do with my constructer. So help with revising the constructing would be appreciated. I am new to programming by the way.
import java.util.*;
import java.io.*;
class Inventory
public static void main(String[] args)
final int MAX = 50;
InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line;
String name;
String file = " inventory.txt ";
int units = 0;
int count = 0;
float price;
try
FileReader fr = new FileReader ("inventory.txt");
BufferedReader inFile = new BufferedReader(fr);
line = inFile.readLine();
while (line !=null)
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try
units = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
items[count++] = new InventoryItem(name, units, price);
catch (NumberFormatException exception)
System.out.println("error in input.Line ignored:");
System.out.println(line);
line = inFile.readLine();
inFile.close();
for (int i = 0; i<count; i++)
System.out.println (items);
catch (IOException exception)
System.out.println("The file " + file + "was not found.");
} //end of main method
}// end of Inventory class
public class InventoryItem
private String name;
private int units;
private float price;
public InventoryItem (String nameOfItem, int numOfUnits, float priceOfItem)
name = nameOfItem;
units = numOfUnits;
price = priceOfItem;
Use CODE tags
What's not printing?
try
units =
its = Integer.parseInt(tokenizer.nextToken());
price =
ice = Float.parseFloat(tokenizer.nextToken());
items[count++] = new InventoryItem(name, units,
nits, price);
catch (NumberFormatException exception)
System.out.println("error in input.Line <========= THIS ???????
.Line ignored:");
System.out.println(line); <============= AND THIS???
line = inFile.readLine();
inFile.close();
for (int i = 0; i<count; i++)
System.out.println (items); <========== THIS IS OK, right?
If I have correctly indentified your problem, then the reason it's not printing is that your print statements are within a catch block, and evidently your code is not throwing any NumberFormatExceptions
Similar Messages
-
Help in reading a csv txt file!
hey i have a problem with this code, Im trying to read a txt file, containing users and scores, and list scores separate, but I get the fist 3 scores empty(0) can any one help plz?
String uname;
int theScore;
int noScores = 0;
int [] scores;
public highScores()
try
FileReader gamers = new FileReader( "Gamers.txt" );
BufferedReader br = new BufferedReader( gamers );
String stringRead = br.readLine( );
while( stringRead != null )
StringTokenizer st = new
StringTokenizer( stringRead, "," );
String uname = st.nextToken( );
theScore = Integer.parseInt( st.nextToken( ) );
noScores = noScores + 1;
scores = new int[noScores];
for(int i = (noScores - 1);i < noScores;i++)
scores[i] = theScore;
System.out.println("" + uname + "," + theScore);
stringRead = br.readLine( );
br.close( );
for(int i = 0;i < noScores;i++)
System.out.println("" + scores);
catch( IOException ioe )
ioe.printStackTrace( );
//file im reading from (Gamers.txt)
Usename,1234
Me,678
you,456
them,698
//output
Usename,1234
Me,678
you,456
them,698
0
0
0
698
Press any key to continue . . .Why are you creating the score array inside he while loop? What's that for? It looks like it's for all the scores, but if you have 3 lines, then you're creating 3 different scores arrays--one with 1 element, 1 with 2 elements, and 1 with 3 elements.
For all but the last one, you're creating it, populating the last element, then throwing it away.
For the last one, you create it, populate the last element (leaving the first three with their default value of 0) and then that's what gets printed.
When you have this kind of problem, print out a bunch of relevant stuff (and even some stuff that you think is not relevant) at each step of the way, so ou can see what your code is doing. Yout THINK you know what it's doing, but obviously you're mistaken. If you can't figure it out from staring at it, then you'll have to let the code itself tell you what's really going on.
You'll have to create the array before you start the while loop, which means you'll have to know ahead of time how many scores you have, or know some maximum that you could possibly have and make it big enough to hold that many.
Or,instead of an array, you couse use a List, such as java.util.ArrayList.
http://java.sun.com/docs/books/tutorial/collections/ -
Need help pulling data from an outside file into my array. Please help =)
Hi,
I need help adapting my array to read the interest rates from an outside file. Here is my code and the outside file I wrote. Please help. Oh, the array in question is on line 259, inside of my calculation() method.
Thanks...
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add(selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener(this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont(new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.addActionListener(this);
tableLabel.setText("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled(false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = {5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append(" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end
My data file is called: "InterestData.dat" and only contains the following text:
5.35, 5.5, 5.75Ok, now I am getting this error message:
cannot resolve symbol method lenght()
Please help me out here, this is due tomorrow and I've been killing myself on it...
attaching program with revised code included, see beginning of calculation method line 250:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.* ;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add (selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener (this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.setBackground(new Color(202,255,112));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont (new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.setBackground(new Color(202,255,112));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.setBackground(new Color(202,255,112));
quitButton.addActionListener(this);
//define label for amortization table
tableLabel.setText ("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText ("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText ("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled (false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText ("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
//declare input stream object
InputStream istream;
//create a file object to refer to the outside file
File interestData = new File("InterestFile.dat");
//assign instream to the new file object
istream = new FileInputStream(interestData);
try
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(interestData));
String line = "";
while((line = in.readLine()) != null)
sb.append(line);
in.close();
String fileData = sb.toString();
String[] splitData = fileData.split(", ");
double [] yearlyInterestArray = new double[splitData.length()];
for(int j = 0; j < splitData.length(); j++)
yearlyInterestArray[j] = new Double(splitData[j]).doubleValue();
catch (IOException e)
JOptionPane.showMessageDialog(null, "File does not exist." + e.getMessage());
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = { 5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow ();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex ();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText ());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow ((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append (" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end -
Reading from a txt file and storing into a list
i want to read a list of counters(String) which are there in a flat txt file and store them into a List.
Any suggestion will be helpful
sanjeevTry this
try {
FileReader fr = new FileReader("C:/abc.txt");
BufferedReader br = new BufferedReader(fr);
String record = null;
while ((record = br.readLine()) != null)
System.out.println(record );
-
Need help for capturing from handycam
Can anyone help me with a question about capturing?
I have a Sony Handycam and a firewire cable. I'm trying to capture mini dv footage from the camera to my G4 Powerbook in Final Cut Pro. I don't have access to a deck right now, that's why I need it to work with the camera.
The computer is not reading that the camera is attached.
Is there some setting or something that I need to change?
When I try and capture, the window is black because the media isn't coming through.
I can't capture in iMovie either.
Any suggestions would be greatly appreciated. Thanks for the help!Hi Warren,
If you are using FC Pro, you should probably post your question in that forum. That said, which model Handycam do you have and is it MicroMV format? If so, even though it may have a FW connection you probably need Sony MovieShaker software, Pinnacle 8 or Ulead Videostudio. FCE and iMovie won't work with MicroMV and I don't believe FCP does, either. -
Need help loading data from Excel data file to oracle tables
i need to load an Excel spreadsheet to Oracle table.
The spreadsheet contains 20 columns, the first 8 columns contains basic info, but the rest 12 columns contains info like
1stQtr_08, 2ndQtr_08, 3rdQtr_08, 4thQtr_08
1stQtr_09, 2ndQtr_09, 3rdQtr_09, 4thQtr_09
1stQtr_10, 2ndQtr_10, 3rdQtr_10, 4thQtr_10
So what i need to accomplish is:
break that one record(with 20 fields) in Excel to 3 records for each fiscal year in the Oracle table, so each record in the database table will look like
8 basic field + fiscal_year + 1stQtr_08, 2ndQtr_08, 3rdQtr_08, 4thQtr_08
8 basic field + fiscal_year + 1stQtr_09, 2ndQtr_09, 3rdQtr_09, 4thQtr_09
8 basic field + fiscal_year + 1stQtr_10, 2ndQtr_10, 3rdQtr_10, 4thQtr_10
There are about 10000 rows in the data file, so how can i use sqlldr to perform such task? beside sqlldr, any other good suggestions?
thxExternal Tables is just an Oracle API for sqlloader. If you going to load this data over and over again, External tables would be a good idea, but if it's a one time thing, sqlldir is simpler, unless you just want to learn how to use External Tables.
I used to run a data warehouse, so I have done, at least similar, to what you are doing in the past. -
Read numbers from a .txt file and display them in a graph
How can I get Labview 7 to read from a txt. file containing a lot of
coloumns with different datas? There`s only two of the coloumns that are
interesting to me, the first, that contains the time of the measuring, and
one in the middle, that contains the measured temperatures. I want Labview
to read this datas and display them graphicly.
Thanks from StaleHere's one way.
You can also use the help-> find examples and search for "text".
2006 Ultimate LabVIEW G-eek.
Attachments:
Graph.vi 21 KB -
Read from a text file line by line
Hi,
I am new to Labview and I am trying to output a text file line by line. For example if my text file is
START
SETRPM 1000
WAIT 10s
RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
WAIT 5s
RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
END
I want it to output
START
SETRPM 1000
SETMAF 5 ...and so on
I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
Thank you!
Your program does exactly what you asked it to do. In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register. This data will consist of the first line of the (assumed-)multi-line file you specified.
I suppose your question is "Why is it only showing me one line?" This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
Bob Schor
P.S. -- I pointed your code at a text file of 7 lines on my PC. When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text. -
I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
Attachments:
try2.txt 2 KB
read_array.vi 21 KBThe problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
Here are some of your choices to fix your problem.
1. Change the source file to a tab delimited file. Your VI will then run as is.
2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does. -
by i need help for my photoshop connective..if you ceck problem please.
Does your Cloud subscription properly show on your account page?
If you have more than one email, are you sure you are using the correct Adobe ID?
https://www.adobe.com/account.html for subscriptions on your Adobe page
If yes
Some general information for a Cloud subscription
Cloud programs do not use serial numbers... you log in to your paid Cloud account to download & install & activate... you MAY need to log out of the Cloud and restart your computer and log back in to the Cloud for things to work
Log out of your Cloud account... Restart your computer... Log in to your paid Cloud account
-Sign in help http://helpx.adobe.com/x-productkb/policy-pricing/account-password-sign-faq.html
-http://helpx.adobe.com/creative-cloud/kb/sign-in-out-creative-cloud-desktop-app.html
-http://helpx.adobe.com/x-productkb/policy-pricing/activation-network-issues.html
-http://helpx.adobe.com/creative-suite/kb/trial--1-launch.html
-ID help https://helpx.adobe.com/contact.html?step=ZNA_id-signing_stillNeedHelp
If no
This is an open forum, not Adobe support... you need Adobe staff to help
Adobe contact information - http://helpx.adobe.com/contact.html
-Select your product and what you need help with
-Click on the blue box "Still need help? Contact us" -
I need autocomplete for search for words in a txt. file
i am not so good in java.
I have a running code for search in text with a txt. file (from user bluefox815).
But I need a solution with autocomplete for search for words in a txt. file.
test_file.txt (Teil des Inhaltes):
Roboter robots
Mechatronik mechatronics
and so on
Can you help me please.
Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
* this program searches for a string in a text file and
* says which line it found the string on
public class SearchText implements ActionListener {
private String filename = "test_file.txt";
private JFrame frame;
private JTextField searchField;
private JButton searchButton;
private JLabel lineLabel;
private String searchFor;
private BufferedReader in;
public SearchText() {
frame = new JFrame("SearchText");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
searchField = new JTextField(80);
searchButton = new JButton("Search");
// this is used later in our actionPerformed method
searchButton.setActionCommand("search");
// this sets the action listener for searchButton, which is the current class
// because this class implements ActionListener
searchButton.addActionListener(this);
lineLabel = new JLabel("nach dem Fachbegriff suchen");
public void createGUI() {
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
JPanel bottomPanel = new JPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
topPanel.add(searchField);
topPanel.add(searchButton);
bottomPanel.add(lineLabel);
mainPanel.add(topPanel);
mainPanel.add(bottomPanel);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
public void actionPerformed(ActionEvent e) {
// now we get the action command and if it is search, then it is the button
if ("search".equals(e.getActionCommand())) {
searchFor = searchField.getText();
searchTheText();
private void searchTheText() {
// I initialize the buffered reader here so that every time the user searches
// then the reader will start at the beginning, instead of where it left off last time
try {
in = new BufferedReader(new FileReader(new File(filename)));
} catch (IOException e) {
String lineContent = null;
int currentLine = 0;
// this will be set to true if the string was found
boolean foundString = false;
while (true) {
currentLine++;
// get a line of text from the file
try {
lineContent = in.readLine();
} catch (IOException e) {
break;
// checks to see if the file ended (in.readLine() returns null if the end is reached)
if (lineContent == null) {
break;
if (lineContent.indexOf(searchFor) == -1) {
continue;
} else {
lineLabel.setText(String.valueOf(lineContent));
foundString = true;
break;
if (!foundString)
lineLabel.setText("Es kann kein Fachbegriff gefunden werden.");
try {
in.close();
} catch (IOException ioe) {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SearchText().createGUI();
}Markus1 wrote:
But I need a solution with autocomplete for search for words in a txt. file.What is your question? What have you tried so far? What are you having difficulty with?
Mel -
Problem on reading and writing from from a *.txt file
I get Problem on reading and writing from from a *.txt file. The following is the read() method...
The software said the DataInputStream is depreciated. Can anyone help me please?
public void read()
File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
FileInputStream in = null;
String str = "";
try
in = new BufferedReader(file);
//in = new FileInputStream(file);
for(;;)
str = new BufferedReader(in).readLine();
//str = new DataInputStream(in).readLine();
if(str == null)
break;
System.out.print(str);
in.close();
catch(IOException e)
System.err.println("execution error: " +e);
}Thank you for your reply. I have made some change. However, there is an incompetable type found error.
in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
public void read()
File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
FileInputStream in = null;
//BufferedReader in = null;
String str = "";
try
in = new BufferedReader(new InputStreamReader(in));
//in = new FileInputStream(file);
for(;;)
BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
//str = new BufferedReader(in).readLine();
//str = new DataInputStream(in).readLine();
if(str == null)
break;
System.out.print(str);
in.close();
catch(IOException e)
System.err.println("execution error: " +e); -
Need Help for Nokia 6500 slide
Hi all I'm A new Guy here ,
But I do really need help for hard reset my phone
I already try *#7073# But It doesn't work ,
If Anybody know to make a hard reset please helprwss wrote:
I'v got te same problem with my 6500 Slide, is there a button combination that we have to press
to hard reset the 6500 Slide?!
How does the 6500 slide hard reset?
That's simple.
All you have to do is:
From MENU goto SETTINGS, When there scroll down and select 'Restore Factory Setting'.
There are two options in there:
"Restore Settings only"
and
"Restore all"
Select "Restore All"
When done the phone will delete every thing on the Phone memory(C:\)(contacts,picture,messages etc)
and also restore phone to its original settings and will restart.
This proceedure is mostly common on S40 phone.
Hope this explain and solve the problem. -
Need help for access list problem
Cisco 2901 ISR
I need help for my configuration.... although it is working fine but it is not secured cause everybody can access the internet
I want to deny this IP range and permit only TMG server to have internet connection. My DHCP server is the 4500 switch.
Anybody can help?
DENY 10.25.0.1 – 10.25.0.255
10.25.1.1 – 10.25.1.255
Permit only 1 host for Internet
10.25.7.136 255.255.255.192 ------ TMG Server
Using access-list.
( Current configuration )
object-group network IP
description Block_IP
range 10.25.0.2 10.25.0.255
range 10.25.1.2 10.25.1.255
interface GigabitEthernet0/0
ip address 192.168.2.3 255.255.255.0
ip nat inside
ip virtual-reassembly in max-fragments 64 max-reassemblies 256
duplex auto
speed auto
interface GigabitEthernet0/1
description ### ADSL WAN Interface ###
no ip address
pppoe enable group global
pppoe-client dial-pool-number 1
interface ATM0/0/0
no ip address
no atm ilmi-keepalive
interface Dialer1
description ### ADSL WAN Dialer ###
ip address negotiated
ip mtu 1492
ip nat outside
no ip virtual-reassembly in
encapsulation ppp
dialer pool 1
dialer-group 1
ppp authentication pap callin
ppp pap sent-username xxxxxxx password 7 xxxxxxxxx
ip nat inside source list 101 interface Dialer1 overload
ip route 0.0.0.0 0.0.0.0 Dialer1
ip route 10.25.0.0 255.255.0.0 192.168.2.1
access-list 101 permit ip 10.25.0.0 0.0.255.255 any
access-list 105 deny ip object-group IP any
From the 4500 Catalyst switch
( Current Configuration )
interface GigabitEthernet0/48
no switchport
ip address 192.168.2.1 255.255.255.0 interface GigabitEthernet2/42
ip route 0.0.0.0 0.0.0.0 192.168.2.3Hello,
Host will can't get internet connection
I remove this configuration...... access-list 101 permit ip 10.25.0.0 0.0.255.255 any
and change the configuration .... ip access-list extended 101
5 permit ip host 10.25.7.136 any
In this case I will allow only host 10.25.7.136 but it isn't work.
No internet connection from the TMG Server. -
Need help for writing extract program
hi
i need help for writing extract program to retriew data from legacy system.
i already developed bdc programs for me31k and me21.
my requirement is to write extract program s for those t.codes.
to retriew data from legacy system and stored in flat file.i need help with a java program. it is a program that allows the user to enter a student's GPA, number of extracurricular activities, and number of service activities. The user can not enter a gpa above 4.0 or below 0. The user can not enter a negative number for the number of both activities. If the student meets the following criteria: 1) GPA of 3.8 or above and at least one extracurricular activity and one service activity, 2) GPA below 3.8 but at least 3.4 and a total of at least three extracurricular and service activities, 3) GPA below 3.4 but at least 3.0 and at least two extracurricular activities and three service activities, the message "Scholarship candidate" should display. If the student does not meet the criteria above, then the message"not a candidate" should display. Can you help me, please?
You haven't posted ANY 'java program' for us to help with.
The forum is NOT a coding service. It is to help you with YOUR code.
Post the code you have written and SHOW us (don't just tell us) how you compile it and execute it and the results you get. Then we can help you with any problems you are are having.
If you need help understanding just what the program should be doing you need to ask your instructor to clarify the assignment.
Maybe you are looking for
-
Powerbook G4 can't connect to network
I have a Powerbook G4 (800 Mhz) running Tiger. I'm trying to get it to connect to my WPA-protected home wireless network. When I turn Airport on, the computer "sees" the network, but when I select it and enter the password (and choose WPA for the con
-
I need help for repair dmg file in illustrator 5.0!
Hi everyone, I just un-pluged my hard drive with out select eject that dmg all the my homework AI files. I tried open new file> place. I tried open with Acrobat X. I tried open and place with photoshop. I tried Recovery Toolbox for Illustrator. all o
-
What is the use of COL_SELECT_MASK IN fm gui_download?
Hi i Just want to know what is the use of col_select_mask in GUI_DOWNLOAD. currently i need to work on one report where they are passing this parameter to gui_download. result is it is taking only 255 char column length in the downloaded excel... i n
-
Flex 4.5.1 AIR 2.6 android mobile application
I am trying my first Flex(4.5.1)/AIR(2.6) mobile application for android. I am using Flash Builder 4.5.1. I am able to run the application on desktop selecting the Target platform as Google Android and Google Nexus One as device to simulate. But I am
-
i download adobe flash player for my macbook pro, but nothing that requires adobe flash player works. i haven"t tried much, but only because i have no idea what to do.