Array static int help
static int[] insert(int x, int i, int[] a)
insert takes an item x, an index i, and an array a, and returns a new array containing all the elements of a with one additional element, namely x, at position i.
ok im trying to add 2 ints to the array?
and i dont understand what im doing wrong this is what i tried and it says error bc it needs an int in the return.
its suppose to do this
a = new int[3]; a[0] = 5; a[1] = 2; a[2] = 7;
a.length3
b = insert(-42, 1, a); // -42 is passed into x and 1 is passed into i
b.length4
b[1]-42
b[2]2
this is what i have written that is wrong...
public static int[] insert(int newZ, int newX, int[] a){
int totals = 1;
int z = newZ;
int x = newX;
for (int i = 0; i < a.length; i++){
totals = (a[i]+ z + x);
return totals;
}
Hi,
This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at :
http://forum.java.sun.com/forum.jspa?forumID=54
Thanks,
RK.
Similar Messages
-
FINDING MEDIAN FOR AN ARRAY OF INTS WITH EVEN NUMBER OF VALUES
okie dokie fellas i know this has got to be easy but i hjave been sittin at my comp forever workin on projects that are due and my head isn't all there anymore...could someone please clue me in on how im supposed to write the logic to find the median of an array of integers if the array contains an even number of values...I know I have to average the 2 values on either side but i cant figure it out at all...sorry i know its dumb but thnaks to anyone who helps
package pgm3deClercqMatt;
* @author Owner
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class ExamStatistics
public static void main(String[] args)
DbConnection db = new DbConnection("pgm3");
boolean moreRecords;
String query = "SELECT * FROM pgm3Data ORDER BY ExamGrade";
ResultSet rs = db.processQuery(query);
int nbrGrades = 0;
ResultSetMetaData rsmd = null;
try
rsmd = rs.getMetaData();
catch(SQLException sqlex)
JOptionPane.showMessageDialog(null, "SQLException getting ResultSet data or metadata");
System.exit(0);
int s[] = new int[200];
DecimalFormat decimal = new DecimalFormat("#,##0.00");
int n = 0, aboveNinety = 0, numberAboveNinety = 0;
double sum = 0, avgGrade = 0, medianGrade = 0;
try
moreRecords = rs.next();
if(!moreRecords)
JOptionPane.showMessageDialog(null, "pgm3Data Result Set is Empty.");
System.exit(0);
while(moreRecords)
s[n] = rs.getInt(1);
n++;
moreRecords = rs.next();
}// end of while loop
System.out.println("n = " + n);
System.out.println("s[0]= " + s[0]);
System.out.println("s[n-1]= " + s[n-1]);
//FIND AVERAGE OF ARRAY
for(int j=0; j<n; ++j)
sum += s[j];
avgGrade = sum/n;
//FIND NUMBER OF GRADES ABOVE OR EQUAL TO 90
for(int j=0; j<n; ++j)
if(s[j]>=90)
numberAboveNinety++;
//FIND MEDIAN EXAM GRADE
for(int j=0; j<n ; ++j)
if(Math.abs(medianGrade - Math.floor(medianGrade))<1.e-10)
medianGrade = s[(j+1)/2];
else
medianGrade = <HERE IS WHERE THE PROB IS
}// end of try block
catch(SQLException sqlex)
JOptionPane.showMessageDialog(null, " SQLException getting ResultSet data or metadata");
System.exit(0);
String output = "";
output = "Number of Exam Grades: " + n;
output += "\nHighest Exam Grade: " + maxOfArray(s, n) + "\nLowest Exam Grade: " + minOfArray(s, n)
+ "\nAverage Grade: " + decimal.format(avgGrade) + "\nNumber of exam grades above 90: "
+ numberAboveNinety + "\nMedian Exam Grade: " + medianGrade;
JOptionPane.showMessageDialog(null, output);
System.exit(0);
}// end of main
static int maxOfArray(int z[], int n)
int j, max = z[0];
for(j=1; j<n; ++j)
if(z[j]>max)
max = z[j];
return max;
static int minOfArray(int z[], int n)
int j, min = z[0];
for(j=1; j<n; ++j)
if(z[j]<min)
min = z[j];
return min;
}// end of ExamStatistics
class DbConnection
// class DbConnection creates and manages the db connection,
// processes queries, and returns result sets for processing
private Connection connection = null;
private String url="jdbc:odbc:";
private Statement statement;
private String username = "";
private String password = "";
private ResultSet rs;
private int nbrResultSets = 0;
// Constructor Argument is the registered name of the database
DbConnection(String dbName)
try
{// load driver to allow connection to database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection ((url+dbName), username, password );
catch (ClassNotFoundException cnfex)
fatalError("ClassNotFoundException on connection attempt");
System.exit(0);
catch (SQLException sqlex )
fatalError("SQLException -- Unable to Connect to db");
System.exit(0);
} // end of constructor
ResultSet processQuery(String query)
// process a single SQL query and return the resulting data set
rs = null;
try
statement = connection.createStatement();
rs = statement.executeQuery(query);
catch (SQLException sqlex)
fatalError("SQLException on query or processing");
return rs;
void endConnection()
try
connection.close();
catch (SQLException e)
fatalError("SQLException on attempt to close connection");
// simple local fatal error handler
private void fatalError(String msg)
JOptionPane.showMessageDialog(null,msg);
System.exit(0);
} // end of class DbConnectionsorry to anyone who thinks what i'm doing is a joke
first of all i'm a student and secondly i'm taking
java in a summer session so things don't get
explained as well as they should. And how is this our problem?
I'm doing the best
i can. The for loop was because the array that I
defined to hold 200 values was being filled by a
database with a supposed unknown number of values but
less than 200 so i waslooping through to get each
value and put it in order and the conditional
statement was supposed to test to see if the incoming
median was an integer and was in the final write-up
put into it's own boolean method returning false if
there was no median and you needed to take the
average of the next lowest and highest values. BThere's always a median. The definition I sent you tells you what it is.
But
thnak you very much to the people that actually help
on here and don't try to bash people who have put
effort into writing their code, however shitty it may
look to them. You can't control what people say about your stuff. Everyone who criticizes your work isn't making a personal attack. They're telling you something that you should be learning from. Your problem is that you can't separate yourself from your work.
No one knows absolutely everything and
people who decide to talk down on others when they
are using this forum as a last resort need to grow
up.Grow up? That's what you need to do. If you think for a moment that you'll never be criticized once you leave that ivory tower you're sadly mistaken. You need to figure out how to separate yourself from your code.
% -
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 -
Problem in array output, pls help!
i made an array:
public class Estudyante
String studentNo;
String studentName;
String address;
String phone;
String email;
public void displayDetails()
System.out.println(studentNo);
System.out.println(studentName);
System.out.println(address);
System.out.println(phone);
System.out.println(email);
public class StudentFinder
//define the variables of the class
Estudyante estObjects[];
//initialize the variables
public StudentFinder()
//creating an array of 3 estudyantes
estObjects = new Estudyante[3];
//creating objects of all the three elements in an array
for(int ctr = 0; ctr !=estObjects.length;ctr++)
estObjects[ctr] = new Estudyante();
//assigning test values
//estudyante 1 details
estObjects[0].studentNo = "0001";
estObjects[0].studentName = "Rez";
estObjects[0].address = "Pasig";
estObjects[0].phone = "111-1111";
estObjects[0].email = "[email protected]";
//estudyante 2 details
estObjects[1].studentNo = "0002";
estObjects[1].studentName = "Reza";
estObjects[1].address = "Manila";
estObjects[1].phone = "222-2222";
estObjects[1].email = "[email protected]";
//estudyante 3 details
estObjects[2].studentNo = "0003";
estObjects[2].studentName = "Reza Ric";
estObjects[2].address = "Malate";
estObjects[2].phone = "333-3333";
estObjects[2].email = "[email protected]";
//declare the method of the class
public void displayFinder()
//add the code for displaying estudyante details
for (int ctr = 0;ctr != estObjects.length;ctr++)
estObjects[ctr].displayDetails();
//the displayDetails() method is present in the Estudyante class
//code the main() method
public static void main(String args[])
StudentFinder finderObject;
finderObject = new StudentFinder();
finderObject.displayFinder();
problem:
when i run this in command prompt, it displays all the 3 sets of details
question:
how will i display the set of details i want and not all of them?
eg: i only want the details of studentNo = "0001"
so in command prompt i execute
java StudentFinder 0001
how will i be able to get the details for studentNo = "0001" only and how will i display "No such student" if the studentNo asked for is not in any of the details.Hi KikiMon,
In your displayFinder() method you'll have to take an argument, specifying which Student to display. Like this:
public void displayFinder(String target)
for (int ctr = 0;ctr != estObjects.length;ctr++)
if(estObjects[ctr].studentNo.equals(target)) {
estObjects[ctr].displayDetails();
An in your main you'll have to forward a commandline argument like this:
public static void main(String args[])
StudentFinder finderObject;
finderObject = new StudentFinder();
finderObject.displayFinder(args[0]);
Later,
Klaus -
is it only one chance i can initialize array with int [] a={3,2,1}
===============================
class InitializeArrayTest
int [] a; //i need keep a[] global
public static void main(String args[])throws IOException
//a=new int[] { 3, 2, 1};//can not complie<========why here is wrong
a=new int[3];//also can not
a={3,2,1}; //I want to use {3,2,1} as data for simple test purpose here for other method
}so if static means only one instance allowed
for what reason there is no compiler error in the
coding below
static int [] preSort;
public B(int i)
int []preSort=new int; //<======why no syntax
You are declaring a new local variable called preSort, which has scope to the end of the constructor. -
What's the simplest way to pass an array of ints to a class
Did I word that right when I called it a "class"? Anyway, doing the obvious doesn't work i.e. from the (String[] args) that occurs in every java program, I thought that using (int[] arg), where arg is an array of ints would work, but it doesn't appear to be as simple as that.
Here's my code:
// Construct a shape from user input
class Shape {
int sides;
void Shape(int[] specs) {
sides = specs[0];
class CreateShape {
public static void main(String[] args) {
if(args.length < 3) {
System.out.println("usage: CreateShape [number of sides], [side1], [side2], ...");
return;
int arg[] = new int[args.length];
int i = 0;
for(String s : args) {
System.out.println("is is: "+i);
arg[i] = Integer.parseInt(s);
i++;
if(arg[0] != args.length + 1) {
System.out.println("You did not specify the correct number of sides");
System.out.println("usage: Shape [number of sides], [side1], [side2], ...");
return;
Shape shape = new Shape(arg);
}I'm just getting one error now:
Shape.java:33: cannot find symbol
symbol : constructor Shape(int[])
location: class Shape
Shape shape = new Shape(arg);
^
1 error
Edited by: psvm on Mar 31, 2008 11:43 AM -
I would like to use arrays to minimize code.
I am trying to generate an array of int base on an array of boolean randomly selected.You can try using 'Boolean to 0,1.vi', found in the Boolean palette: this vi converts a scalar, array or cluster of booleans to a scalar, array or cluster of word (I16 integers).
To use it, simply wire an array of booleans (indicator) to its left, and an array of integers (control) to its right et voilà.
Roberto
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos? -
How to display an Array of ints in an Array of TextFields
I'm trying to create an array of textfield's, and then create an array of ints and display one of those ints in each textfield. Can anyone please help me?
Yea after you create the array of textfields and ints, do a for loop with textfield.length limit.
for(int i = 0; i < textfield.length; i++){
look in the JTextField API for how to put int into
a text. I know, but if this is for a class, you have
figure it out. (You might have to use the Integer object to convert it to a string
I hope this helps. If you still can't get it, post some code and I'm sure someone will help you through it.
gl
kimoS -
Swing Arrays! Please help!!
how do you assign the values of an array to another array?
example:
String A[] = {"a","b","c"};
String B = {};//initial as an empty array
String text;
if text == null
how do you assign the values of array A to array B;
Please help
Thanks in advanceThis should work
String[] A = {"a","b","c"};
String[] B = null;
boolean condition = true;
if (condition)
int size = A.length;
B = new String[size];
for (int i = 0; i < size; i++)
B[i] = A;
note that the B array size is not dynamic, you have to allocate memory when you come to know what size it should be. If you don t want to worry about these array problems, you can use a Vector or an ArrayList. -
How to javadoc "public final static int"?
How can we create "Field Summary" HTML document for "public final static int" variables?
This question is probably same as the below question.
http://forums.java.sun.com/thread.jsp?forum=41&thread=72832
p.s.
The below document indicates CENTER, NORTH, ...
How an we achieve it to document "public final static" variables?
http://java.sun.com/products/jdk/1.2/docs/api/index.htmlNo, 1.3 does not have the static constant values exposed to the Doclet API,
and so that information is not available to any doclets to place in the
generated documentation.
BTW, based on feedback from a developer, we changed the format from:
public static final int NORTH = 0
to
public static final int NORTH
See: Constant values
where the "Constant values" link takes them to a summary page that
lists all of the values. This helps discourage users from mistakenly
seeing and using the value instead of the constant.
-Doug Kramer
Javadoc team -
How to convert String array into int.
void getSoldSms(Vector vecSoldSms)
String str[]=new String[vecSoldSms.size()];
String words[]=new String[str.length]; // String array
for(int i=0;i< vecSoldSms.size();i++)
str=(String)vecSoldSms.get(i);
} //End for
for(int i=0;i<str.length;i++)
words = str[i].split("\\|\\|");
System.out.println();
for(int j=0;j<1;j++)
int count[str.length]=Integer.parseInt(words[i]);
System.out.print(count[j]*advance_count);
} // end inner for loop
} //End for
} //End function getSoldSms
how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
And if you want { "1", "2", "3" } to be 123:
StringBuffer b = new StringBuffer();
for (int i = 0; i < array.length; i++) {
b.append(array);
int result = Integer.parseIn(b.toString()); -
Make Array of int's from a String
Hi,
Trying to transform a String into an array of ints. The following works, but seems a little longwinded for what must be quite a common function - specifically line 9 in the code (turning a char into an int). Can anyone suggest an easier way?
public class IntArray {
public static void main( String[] args ) {
if ( args.length == 1 ) {
String s = args[ 0 ] ;
int sLength = s.length() ;
int[] argIntArray = new int[ sLength ] ;
for ( int j = 0 ; j < s.length() ; j++ ) {
// This line ...
argIntArray [ j ] = Integer.parseInt( s.charAt( j ) + "" );
for ( int j = 0 ; j < argIntArray.length ; j++ ) {
System.out.println( argIntArray[ j ] );
} else {
System.out.print( "Please enter an int" );
}Thanks,
RichI'm not sure how common it is, but since you are assuming that the input is a String that represents an int...
public class IntArray {
public static void main( String[] args ) {
if ( args.length == 1 ) {
String s = args[ 0 ] ;
int sLength = s.length() ;
int[] argIntArray = new int[ sLength ] ;
for ( int j = 0 ; j < s.length() ; j++ ) {
// This line ...
argIntArray [ j ] = s.charAt( j ) - '0' ;
//I suggest checking for <0 or >9
for ( int j = 0 ; j < argIntArray.length ; j++ ) {
System.out.println( argIntArray[ j ] );
} else {
System.out.print( "Please enter an int" ); -
Exception creating Array of int
Hi,
I was trying to create an Array of int. I wrote the following code:
int[] a = {1,2};
Class componentClass = (a.getClass()).getComponentType();
Array a1 = (Array) Array.newInstance(componentClass,5);
When running it, I got the following exception:
java.lang.ClassCastException: [I
at com.ingeneo.seizer.testsuite.AAA.cache.TestCache.main(TestCache.java:24)
Exception in thread "main"Here it is:
package com.ingeneo.seizer.testsuite.ABC.cache;
import java.lang.reflect.Array;
public class TestCache
public static void main(String[] args)
int[] a = {1,2};
Class componentClass = (a.getClass()).getComponentType();
Array a1 = (Array) Array.newInstance(componentClass,5); -
Stuck with array's NEED HELP!!!
I have been working at this for two hours now and I need a someone else's opinion other than my own. I need to create a method that finds the row index of the row which contains the largest number divisible evenly by 6. and the column index of the column with the smallest sum. all in one method.
This is what I have so far.
public static int sum(int[][]arr, int numRow)
int[][] s;
s = new int[0][10];
int u = 0, largestevenindex = 0, largesteven = -99999, product = 0, sum = 0, i, j;
for(i=0;i<numRow;i++)
for(j=0;j<arr.length;j++)
if(arr[i][j]%6==0 && arr[i][j]>largesteven) //To find the the row index of the largest number divisible by 6.
largesteven = arr[i][j];
largestevenindex = i;
System.out.println(largesteven);
System.out.println(largestevenindex);
for(u=0;u<arr[i].length;u++) //I think I have to create another table and place the sums of the colums and then compare. Is there an easier way?
s[0] = s[0][u]+arr[i][j];
System.out.println(s[0][u]);
return largestevenindex;
This is the test file23 45 10 77 19 13 16
52 34 71 19 88 65 3
12 1 57 16 4 36 17
9 22 31 27 8 25 12
56 77 88 22 33 44 99
6 21 16 89 4 37 48
25 17 8 9 64 72 81
95 26 5 73 18 92 66
99 12 45 72 19 77 43
11 71 26 34 81 7 45
16 2 34 68 67 7 51
19 52 4 56 51 95 12
57 4 7 9 2 1 3
Anyone have any tips for my code, or another way to do this. Thanks.Your right flounder, I forget to add we are suppose to just find the product of the two index(smallest sum cloum index and largest row index divisible by 6)
public static int sum(int[][]arr, int numRow)
int[][] s;
s = new int[0][10];
int u = 0, largestevenindex = 0, largesteven = -99999, product = 0, sum = 0, i, j;
for(i=0;i<numRow;i++)
for(j=0;j<arr.length;j++)
if(arr[i][j]%6==0 && arr[i][j]>largesteven)
largesteven = arr[i][j];
largestevenindex = i;
return largestevenindex;
This gets the row index of the highest number divisible by 6. How do I go about finding the colum index that has the smallest sum. any hints or clues. It has to be apart of this method, though. -
Static input help for DATS type
Hello,
I'd like to link static input help for screen field of DATS type. If I click on help linked to this screen field I get CONVT_NO_NUMBER error: 'Unable to interpret "=2" as a number.'
My steps:
- In Screen Painter I selected desired screen field and selected DATS type and "1 Show at selection" in its details.
- I defined global variable with same name as desired screen field
What's the problem?
Best regards,
Josef MotlHi,
do this way.....
first declare the variable in program as
1. data: date type sy-datum.
2. now go to your screen,(click on F6) use get from Program
now choose date form it , and say ok, now save it and activate it.
delete the old one..
now you will be able to get all the things which you want.
automatical validation also possible, and F4 also possible.
Regards
vijay
Maybe you are looking for
-
WHILE DELETING A SALE ORDER GETTING A RUNTIME ERROR
hi to all experts, whenever i try to delete a particular sale order im getting a runtime error stating that Short text Screen: Illegal message What happened? The current screen processing action was terminated since a situat occurred wher
-
Alert with a pop up is saying to call
On Safari, 2 pop up screens saying Alert Apple System partially damaged and to immediately call 1-855-724-9651. Small pop up also indicates to contact the same number and also http//techsupportnumber.us. Obviously fake malware but screens are froz
-
Exporting movies with nested animations
Hi! I'm hoping someone out there can be of some assistants, I'm currently working on a animation, and I've pretty much finished now and am trying to export the full animation so I can use this within Director MX 2004. Only, now I've discovered that i
-
Creating dynamic caches from static config
Hi, we normally create our caches using static config, using the std xml config. Example, in our cache-mapping, we'll have a cache like the below: <cache-name>account</cache-name> <scheme-name>distributed-persistent-write-thru</scheme-nam
-
Hi, I'm new to the SAP and Netweaver. I'm trying to logon to the MI WebConsole with the login and password I had given during installation but it returns the error "Username or password incorrect". In the "System" I have given the hostname of th