Storing a record set into an array
Hello Again,
Yet another road block in my destination to completing my program. I wanted to create a MultiColumn Combobox and needed to store my Database values into an array so I get get them into the Combobox. I'm having trouble getting this code to work properly. It seems that the the combobox wont accept the variable items maybe because it is outside the scope? I tried to move the code around to get it to work but it don't.
here is the code.
package pms;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class Test3 extends JFrame {
public static void main(String[] args) {
new Test3();
public Test3() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.setBackground(Color.gray);
DBConnection db = new DBConnection();
try {
Connection conn = DriverManager.getConnection(db.connUrl);
Statement sql = conn.createStatement();
ResultSet rs = sql.executeQuery("SELECT * FROM Referrals ORDER BY Referral_Text");
while (rs.next()) {
Item[] items = {
new Item(rs.getString(2), rs.getString(2)),};
JComboBox jcb = new JComboBox(items);
//Close connections.
rs.close();
sql.close();
conn.close();
} catch (SQLException e) {
e.getStackTrace();
jcb.setPreferredSize(new Dimension(24, 24));
jcb.setRenderer(new ItemRenderer());
c.add(jcb, BorderLayout.NORTH);
setSize(200, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// The items to display in the combobox...
class Item {
String itemName = "";
String itemValue = "";
public Item(String name, String value) {
itemName = name;
itemValue = value;
// The combobox's renderer...
class ItemRenderer extends JPanel implements ListCellRenderer {
private JLabel nameLabel = new JLabel(" ");
private JLabel valueLabel = new JLabel(" ");
public ItemRenderer() {
setOpaque(true);
setLayout(new GridLayout(1, 2));
add(nameLabel);
add(valueLabel);
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
nameLabel.setText(((Item) value).itemName);
valueLabel.setText(((Item) value).itemValue);
if (isSelected) {
setBackground(Color.black);
nameLabel.setForeground(Color.white);
valueLabel.setForeground(Color.white);
} else {
setBackground(Color.white);
nameLabel.setForeground(Color.black);
valueLabel.setForeground(Color.black);
return this;
}Thanks!
He is telling you that there are two problems with your code.
The first is that you are declaring the items array inside the while loop, which means its scope is too limited - it can't be accessed by the JComboBox which is declared later.
The second is that you are recreating the items array for every record in your ResultSet. This implies that for every new record, the item(s) already stored will be removed from memory and replaced by the values of the latest record, leading to a single option for your combo box.
Try instead creating an ArrayList object that you initialise right before the loop, and add items to it's collection as you move along. Then pass that ArrayList to the JComboBox in this way:
try {
Connection conn = DriverManager.getConnection(db.connUrl);
Statement sql = conn.createStatement();
ResultSet rs = sql
.executeQuery("SELECT * FROM Referrals ORDER BY ReferItemText");
ArrayList<Item> items = new ArrayList<Item>();
while (rs.next()) {
items.add(new Item(rs.getString(2), rs.getString(2)));
JComboBox jcb = new JComboBox(items.toArray());
// Close connections.
rs.close();
sql.close();
conn.close();
} catch (SQLException e) {
e.getStackTrace();
}
Similar Messages
-
How to get the record set into array?
Hi,
I want to get the record set into array in the procedure and do the processing of the array later in procedure.
below is the stored procedure i am working on:
procedure bulk_delete_group(p_group_id in Array_GroupListID) as
begin
for i in p_group_id.first..p_group_id.last loop
--Here I have to get the list of user id before deleting group
SELECT user_id into *<SOME ARRAY>* FROM group_members WHERE group_id = p_group_id(i);
DELETE group WHERE group_id = p_group_id(i);
--Process the user id array after group deletion..
end loop;
end bulk_delete_group;
Thanks in advance
AdityaSomething like this ->
satyaki>
satyaki>select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
Elapsed: 00:00:00.20
satyaki>
satyaki>
satyaki>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
9999 SATYAKI SLS 7698 02-NOV-08 55000 3455 10
7777 SOURAV SLS 14-SEP-08 45000 3400 10
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 4450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 7000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
13 rows selected.
Elapsed: 00:00:02.37
satyaki>
satyaki>create type np is table of number;
2 /
Type created.
Elapsed: 00:00:03.32
satyaki>
satyaki>Create or Replace Procedure myProc(myArray np)
2 is
3 i number(10);
4 rec emp%rowtype;
5 Begin
6 for i in 1..myArray.count
7 loop
8 select *
9 into rec
10 from emp
11 where empno = myArray(i);
12
13 dbms_output.put_line('Employee No:'||rec.empno||' Name:'||rec.ename);
14 end loop;
15 End myProc;
16 /
Procedure created.
Elapsed: 00:00:00.88
satyaki>
satyaki>
satyaki>declare
2 v np:=np(9999,7777);
3 begin
4 myProc(v);
5 end;
6 /
Employee No:9999 Name:SATYAKI
Employee No:7777 Name:SOURAV
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.30
satyaki>Regards.
Satyaki De. -
SET into string array using toArray()
I have a object java.util.Set collection and I want to convert all the elements
into a string array but i don't know why it is not working in my JSP page...
as i am trying to use toArray() method
i have tried this
String[] arr = collection.toArray();this
String[] arr = (String []) collection.toArray();could you please tell me the right way to aplly it...
thanks in advance....:)I am using session listener which map sessions and it stores sessionid which i hope is a string
when i directly print this set object it shows
[ED0EF456BD1EE956A069340633C8DB87,UT0EF456BD1EE956A069340633C8DB34,RD0EF456BD1EE956A069340633C8DB98]
Message was edited by:
hunterzz -
Inserting a record into an array
I have an applet that pops up different frames when you click on a menu item. On my add a record frame I have a number of textfields and an add button. When the button is clicked it is supposed to insert the record into my array of objects that only can have 3 records. When the button is clicked however I get a null pointer exception. I want to add the record in order based on the employee number, so first I want to check to see if the first spot of the array is null and add the record in the first spot if it is. If it isn't I want to check the employee numbers and insert the the record in the correct place and make sure the array isn't full. Can someone help me out 1. Why the nullpointer exception. 2. I am not sure if my logic is correct. Below is the Code. Thanks!!
public void insertRecord()
if (MyEmpArray[0] == null )
addRec(0);
else
for(int index =0; index <3; index++)
if(intEmpNumber < MyEmpArray[index].intEmpNumber && MyEmpArray[3] != null )
addRec(index);
else
lblErrorMessage.setText("Array is full");
public void addRec(int index)
MyEmpArray[index].setValues(intEmpNumber, strFirstName, strLastName, strHomePhone,
strStreet, strCity, strState, strZip, strCountry, strWorkStreet,
strWorkCity, strWorkState, strWorkZip, strWorkCountry, strWorkPhoneNum,
fltNumHours, fltHourlyWage, intI, intJ, intK);
lblErrorMessage.setText("");
txaReport.setText("");
ClearFields();
}for(int index =0; index <3; index++)
An array with an index from 0 to 3, contains 4 records: you should replace it with
for(int index =0; index <2; index++)
The check-logic is good enough, but there are two minor "bugs":
1) even If the array is full, the for cycle will uselessly check all the records
2) if a the employee number of intEmpNumber is > thanMyEmpArray[index].intEmpNumber the program will show up "Array is full" even if the array isn't full.
So, I suggest to add more code to make distinction between the two cases:
for(int index =0; index <3; index++)
if(MyEmpArray[3] != null ) // check if there is space to add a record
if (intEmpNumber < MyEmpArray[index].intEmpNumber) //check if the position is right
addRec(index);
else
lblErrorMessage.setText("Array is full");
break; // exit the for cicle as the array is full
I don't know what you are programming, but I ask you: "If the new intEmpNumber is < than the intEmpNumber of an already-full-array shouldn't be the new record inserted, discarding the last one?"
I don't know if addRec works, I'm don't know applets, buttons..:)
Sorry for my bad english...I hope this post will help you anyway :) -
Loading COBOL file - blocked variable records and varying size arrays
We would like to use ODI 11g to regularly to parse and load into Oracle DB 11g complex files that originate on the MVS mainframe.
Key file characteristics are:
1. EBCDIC encoding
2. file contains blocked records - each block starts with a 4-byte Block Descriptor Word (BDW). BDW bytes 1-2 specify the block length stored as a 16-bit unsigned integer, i.e. PIC (5) COMP in COBOL.
3. each file block contains multiple variable size records - BDW is followed by 1 or more variable length records. Each record starts with a 4-bytes Record Descriptor Word (RDW). RDW bytes 1-2 specify the record length stored as 16 bit unsigned integer, i.e. PIC (5) COMP in COBOL.
4. each file record contains number of scalar fields and several varying-size arrays - COBOL OCCURS DEPENDING ON. For example:
03 SAMPLE-ARRAY-CNT PIC S9(1) COMP-3.
03 SAMPLE-ARRAY OCCURS 0 TO 5 TIMES DEPENDING ON SAMPLE-ARRAY-CNT.
05 ARRAY-CD1 PIC X(5).
05 ARRAY-CD2 PIC X(7).
05 ARRAY-AMOUNT PIC S9(3)V9999 COMP-3.
5, file contains fields stored as COBOL COMPUTATIONAL and COMPUTATIONAL-3.
6. average record lengh is 1,000 bytes and each file is about 4GB
SQL*Loader/external table functionality can handle most of these requirements on one-off basis, but collectively they present a significant challenge. The file layout can't be reversed engineered as COBOL copybook into ODI.
Does ODI have complex file parsing capabilities that could be used to (pre-)process the file, in as few passes as possible?
Thanks
PetrHi,
there's a couple of options here, and I've included what I think is the simplest below (using TestStand 2.0.1).
It's not exactly elegant though. What I've done is to put in a step that finds out the number of steps to load (based on an earlier decision - in this case a message popup step). I read a number from the limits file, and use this in the looping options of the property loader step that's loading the values into the array. I've done it with a fixed size array target here, big enough to take any incoming data. (Otherwise, knowing how many items you're going to load from the limits file, you could start with an empty array and re-size it prior to loading).
I've cheated slightly by using the pre-expression on the property loader step to specify where th
e data is coming from and where it's going to in the sequence on each iteration of the loop based on the Runstate.Loopindex.
Another option is to go straight into the property loader step, and keep loading properties until the Step.Result.NumPropertiesRead = 0 (remember we're only doing this one at a time)
Another idea would be to load in a value, and check it isn't a "flag" value (i.e. you'd never use say 999 in your array, so set the last element in your limits file to this, and drop out of the loop when this happens.
Further still, you've got the source code for the property loader step, so you could re-write it to make a custom step that loads an array until it fails all on its own (no looping in TestStand).
Hope this gets you going
S.
// it takes almost no time to rate an answer
Attachments:
DynamicPropertyLoader.seq 32 KB -
Return a record set from a procedure
I am building an application for my company.
Before oracle I had used MS SQL Server for a long time.
I build a procedure as following
CREATE OR REPLACE PROCEDURE YBP.ReturnSet
-- Return a record set from a procedure
IS
BEGIN
SELECT * FROM fdbase;
END;
But the complier show me a error message:
<font color="#0000FF">PLS-00428 an INTO clause is expected in this SELECT statement</font>
I read the error details
<font color="#0000FF">"In PL/SQL, only a subquery is written without an INTO clause."</font>
But I know that this procedure can run well in <font color="#0000FF">MS SQL Server .</font>
How I can do this thing in Oracle
Any help will be appreciate!I have a stored proc that is defined as
CREATE or REPLACE
PROCEDURE ABC
(linkid IN CHAR,
Year_in IN DATE,
Method_in IN CHAR,
Date_out OUT DATE,
average_out OUT NUMBER)
is
begin
.. Date_out := ...;
average_out := ...;
end;
another partially completed stored proc that returns a ref
cursor defined as follows:
create or replace package zzz
as
type cursorType is ref cursor;
end;
create or replace function test return zzz.cursortype
as
date_OUT date;
Average_OUT number;
l_cursor zzz.cursorType;
CURSOR temp_cur is
SELECT l.linkid, L.routenumber, ABC(l.linkid,
to_date('01/01/2000', 'mm/dd/yyyy'),
'2',
date_OUT,
average_OUT)
FROM LINK l
WHERE l.LINKID <= '010999';
begin
open temp_cur;
end;
inside test (which I need help completing), how can I refer to
the date_out and the average_out params returned by ABC() so
that these values are in turn passed to the cursortype defined
in package zzz?
Thanks in advance. -
Record directly into iMovie?
I was wondering if I could set up a camera, and record directly into iMovie. I have a long program I need record, and would love to record (import) directly into iMovie.
Yes you can. But there may be occasional short pauses while your Mac "takes a breath" and indexes what it's storing on your hard disc, etc.
Remember that DV video takes up about 13 gigabytes of space per hour, so you'll need that much free space on your disc per hour of recording, and keep about 10% of your total hard disc space free, so that your Mac can still do its internal housekeeping.
You'll need, of course a camcorder with a FireWire/DV/i.Link connection (..all the same thing; just different names for it!..) which generally means a tape-based miniDV camcorder.
(..Although hi-def HDV camcorders have the same FireWire connection, and record onto the same miniDV tape, there's quite an 'overhead' of processing power which your Mac requires in order to convert the incoming hi-def video into the 'Apple Intermediate Codec' format which lets iMovie edit hi-def, so I'd stick with standard-definition DV if I were you!..)*
Depending on the make and model of camera, you may need to put a tape in the camera - or not - and switch it to either Record or VCR mode. (..In a quick test here I've just turned on my Sony camera in 'Camera' mode with a FireWire cable connected, and iMovie is displaying the picture from the camera, and imports it when I click iMovie's "Import" button..)
"..I have a long program I need record.." ..erm, if you're pointing it at a TV screen to record that, you'd want the camera on some sort of support, and - if you have Manual Focus - you may want to de-focus slightly to avoid the moiré pattern which you might get from tightly focused dots (pixels) on the screen. You'd also want to adjust the camera's White Balance so that the screen looks the right colour!
*P.S: hi-def HDV takes up more than 13GB per hour, so if you were to use hi-def HDV you'd need to allow much more (..up to 4x more..) hard disc space per hour of recording! -
Ok, so I completely feel like this is a stupid question for those of you already in the know and recording tracks onto your Computers DAW from instrument apps on the iPad and other i devices. I can not seem to find out exactly what connector or unit I need to be able to connect and use my ipad as a instrument to record tracks onto logic. I have an ipad2 that I want to connect to my apogee duet 2 interface which is obviously connected to my Mac. I know Logic comes with plenty of drum and synth options but I still want to be able to use beatmaker, jam up pro and the sunrizer synth apps on some of my tracks. I do have the camera conversion adaptors. So my question is, do I just run from the camera adapter in the ipad into the midi port on my apogee interface? (I'm new to and still learning about midi) Or is there a special 30 pin cable I need to get that runs from the ipad into the XLR or quarter inch in the break out cables on the apogee? I did find one cord out there that plugged into the ipad and had left and right XLR connectors but my duets break out cable only has two inputs each is their own channel. Also , if the cable I need isn't midi and does connect to the breakout cables, do I set it as an instrument or as a mic in the apogee software? Or am I completely way off base and needing something different all together. Any help would be much appreciated!
I have a fare amount of experience when it comes to recording, set up and the flow of standard instruments, using external hardware and plugins. But the last few weeks I spent a lot of time programming some great beats in beatmaker on my ipad and I want to track them into Logic. It seemed like no matter how I worded the questions when researching what I thought was and should be simple to figure it out, it just took me to answers I wasn't looking for. Thank you ahead of time. Like I said I'm just starting to get out of my comfort zone and learn about midi and the more digital side of things. So sorry about any ignorance concerning that side of things.The new Apogee Duet for iPad and Mac, is compaible with iOS devices and includes a USB Midi input. This sounds like the perfect solution for your workflow.
-
Reading from file into an array
Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
import javax.swing.*; // Imports the Main Swing Package
import javax.swing.event.*;
import javax.swing.text.*; // Used for Text Box Caret Position
import java.awt.*; // Imports the main AWT Package
import java.awt.event.*; // Event handling class are defined here
import java.text.NumberFormat;
import java.text.*; // Imports the Main Text Package
import java.util.*; // Imports the Main Utility Package
public class mortgageCalculator1 extends JFrame implements ActionListener // Creates class mortgageCalculator
JLabel AmountLabel = new JLabel(" Enter Mortgage Amount:$ "); // Declares Mortgage Amount Label
JTextField mortgageAmount = new JTextField(10); // Declares Mortgage Amount Text Field
JButton IntandTerm1B = new JButton("7 years at 5.35%"); // Declares 1st Mortgage Term and Interest Rate
JButton IntandTerm2B = new JButton("15 years at 5.50%"); // Declares 2nd Mortgage Term and Interest Rate
JButton IntandTerm3B = new JButton("30 years at 5.75%"); // Declares 3rd Mortgage Term and Interest Rate
JLabel PaymentLabel = new JLabel(" Monthly Payment: "); // Declares Monthly Payment Label
JTextField monthlyPayment = new JTextField(10); // Declares Monthly Payment Text Field
JButton exitButton = new JButton("Exit"); // Declares Exit Button
JButton newcalcButton = new JButton("New Calculation"); // Declares New Calculation Button
JTextArea mortgageTable = new JTextArea(35,65); // Declares Mortgage Table Area
JScrollPane scroll = new JScrollPane(mortgageTable); // Declares ScrollPane and puts the Mortgage Table inside
public mortgageCalculator1() // Creates Method
super("MORTGAGE CALCULATOR"); // Title of Frame
JMenuBar mb = new JMenuBar(); // Cretes Menu Bar
JMenu fileMenu = new JMenu("File"); // Creates File Menu
fileMenu.setMnemonic('F'); // Enables alt + f to Access File Menu
JMenuItem exitItem = new JMenuItem("Exit"); // Creates Exit in File Menu
fileMenu.add(exitItem); // Adds Exit to File Menu
exitItem.addActionListener(new ActionListener() // Adds Action Listener to the Exit Item
public void actionPerformed(ActionEvent e) // Tests to Verify if File->Exit is Pressed
System.exit(0); // Exits the Programs when File->Exit is Pressed
mb.add(fileMenu); // Adds the File Menu
setJMenuBar(mb);
setSize(600, 400); // Sets Size of Frame
setLocation(200,200); // Sets the Location of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Command on how to close frame
JPanel pane = new JPanel(); // Declares the JPanel
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); // Sets Panel Layout to BoxLayout
Container grid = getContentPane(); // Declares a Container called grid
grid.setLayout(new GridLayout(4,3,5,5)); // Sets grid Layout to GridLayout
pane.add(grid); // Adds the grid to the Panel
pane.add(scroll); // Addes the scrollPane to the Panel
grid.setBackground(Color.yellow); // Set grid color to Yellow
setCursor(new Cursor(Cursor.HAND_CURSOR)); // Makes the cursor look like a hand
mortgageAmount.setBackground(Color.black); // Sets mortgageAmount JPanel JTextField Background Color
mortgageAmount.setForeground(Color.white); // Sets mortgageAmount JPanel JTextField Foreground Color
mortgageAmount.setCaretColor(Color.white); // Sets mortgageAmount JPanel JTextField Caret Color
mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets mortgageAmount JPanel JTextField Font
monthlyPayment.setBackground(Color.black); // Sets monthlyPayment JPanel JTextField Background Color
monthlyPayment.setForeground(Color.white); // Sets monthlyPayment JPanel JTextField Foreground Color
monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets monthlyPayment JPanel JTextField Font
mortgageTable.setBackground(Color.yellow); // Sets mortgageTable JTextArea Background Color
mortgageTable.setForeground(Color.black); // Sets mortgageTable JTextArea Foreground Color
mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18)); // Sets JTextArea Font
grid.add(AmountLabel); // Adds the Mortgage Amount Label
grid.add(mortgageAmount); // Adds the Mortgage Amount Text Field
grid.add(IntandTerm1B); // Adds 1st Loan and Rate Button
grid.add(PaymentLabel); // Adds the Payment Label
grid.add(monthlyPayment); // Adds the Monthly Payment Text Field
monthlyPayment.setEditable(false); // Disables editing in this Text Field
grid.add(IntandTerm2B); // Adds 2nd Loan and Rate Button
grid.add(exitButton);
grid.add(newcalcButton); // Adds the New Calc Button
grid.add(IntandTerm3B); // Adds the Exit Button
setContentPane(pane); // Enables the Content Pane
setVisible(true); // Sets JPanel to be Visable
exitButton.addActionListener(this); // Adds Action Listener to the Exit Button
newcalcButton.addActionListener(this); // Adds Action Listener to the New Calc Button
IntandTerm1B.addActionListener(this); // Adds Action Listener to the 1st loan Button
IntandTerm2B.addActionListener(this); // Adds Action Listener to the 2nd loan Button
IntandTerm3B.addActionListener(this); // Adds Action Listener to the 3rd loan Button
mortgageAmount.addActionListener(this); // Adds Action Listener to the Mortgage Amount Text Field
monthlyPayment.addActionListener(this); // Adds Action Listener to the Monthly payment Text Field
public void actionPerformed(ActionEvent e) // Tests to Verify Which Button is Pressed
Object command = e.getSource(); // Enables command to get data
if (command == exitButton) //sets exitButton // Activates the Exit Button
System.exit(0); // Exits from exit button // Exits from exit button
int loanTerm = 0; // Declares loanTerm
if (command == IntandTerm1B) // Activates the 1st Loan Button
loanTerm = 0; // Sets 1st value of Array
if (command == IntandTerm2B) // Activates the 2nd Loan Button
loanTerm = 1; // Sets 2nd value of Array
if (command == IntandTerm3B) // Activates the 3rd Loan Button
loanTerm = 2; // Sets 3rd value of Array
double mortgage = 0; // Declares and Initializes mortgage
double rate = 0; // Declares and Initializes rate
double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},}; // Array Data for Calculation
try
mortgage = Double.parseDouble(mortgageAmount.getText()); // Gets user input from mortgageAmount Text Field
catch (NumberFormatException nfe) // Checks for correct number fformatting of user input
JOptionPane.showMessageDialog (this, "Error! Invalid input!"); // Outputs error if number is wrong format or nothing is entered
return;
double interestRate = loans [loanTerm][1]; // Sets interestRate amount
double intRate = (interestRate / 100) / 12; // Calculates Interst Rate
double loanTermMonths = loans [loanTerm] [0]; // Calculates Loan Term in Months
int months = (int)loanTermMonths * 12; // Converts Loan Term to Months
double interestRateMonthly = (intRate / 12); // monthly interst rate
double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculation for Monthly payment
double remainingLoanBalance = mortgage; // Sets Reamaining Balance
double monthlyPaymentInterest = 0; // holds current interest payment
double monthlyPaymentPrincipal = 0; // holds current principal payment
NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US); // Number formatter to format output in table
monthlyPayment.setText(myCurrencyFormatter.format(payment));
mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" + // Formats morgageTable Header
"---------\t----------\t------------\t---------------------\n");
for (;months > 0 ; months -- )
monthlyPaymentInterest = (remainingLoanBalance * intRate); // Calculation for Monthly Payment Toward Interest
//Calculate H = R x I
monthlyPaymentPrincipal = (payment - monthlyPaymentInterest); // Calculation for Monthly Payment Toward Principal
//Calculate C = P - H
remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal); // Calculation for Reamining loan Balance
// Calculate R = R - C
// H = monthlyPaymentInterest
// R = remainingLoanBalance
// P = payment
// C = monthlyPaymentPrincipal
// I = interestRateMonthly
mortgageTable.setCaret (new DefaultCaret()); // Sets Scroll position to the top left corner
mortgageTable.append(String.valueOf(months) + "\t" + // Pulls in data and formats MortgageTable
myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
myCurrencyFormatter.format(remainingLoanBalance) + "\n");
if(command == newcalcButton) // Activates the new calculation Button
mortgageAmount.setText(null); //clears mortgage amount fields
monthlyPayment.setText(null); //clears monthly payment fields
mortgageTable.setText(null); //clears mortgage table
public static void main(String[] args) //This is the signature of the entry point of all the desktop apps
new mortgageCalculator1();
}OK, making a little progress but am still very confused.
What I have is a file (int&term.dat) with three lines;
5.75, 30
5.5, 15
5.35 ,7
I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
public static void read()
String line;
StringTokenizer tokenizer;
String rate;
String term;
try
FileReader fr = new FileReader ("int&term.dat");
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer(line);
rate = tokenizer.nextToken();
line = inFile.readLine();
inFile.close();
System.out.println(new String());
catch (FileNotFoundException exception)
System.out.println ("The file was not found.");
catch (IOException exception)
System.out.println (exception);
} -
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
Using a session object to hold the value of a record set?
Hi,
I'm trying to hold the value of a record set (or literally the content of a column in a query in a db) in a session variable so that I can call on this later and insert into another table.
I'm not sure of the correct syntax, I've already made a connection to the DB. I'm trying the following but it doesnt seem to like the code:
<% session.setAttribute("code",rs("column_name")); %>
<%String attrib =
String.valueOf ( session.getAttribute("code")); %>
Hello <%= attrib %>
Any ideas, I dont know how to reference the record set, I declared the recordset previously as rs. Help! Can't find examples anywhere on the net!So just to recap. I appear to be seeing the column name "custorderno" within the Microsoft Access query "lastcust". But I get "no data found" when I run the following code (which I have sectioned off)
<!-- connect to database and lastcust query --!>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Tomcat/jakarta-tomcat-4.1.31/webapps/ROOT/Oatcake.mdb","","");
Statement statement = conn.createStatement();
String sql = "SELECT * FROM lastcust";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
%>
<TR><TD><%= rs.getString("custorderno") %></TD>
</TR>
<% session.setAttribute("code",rs.getString("custorderno")); %>
<% String attrib =
String.valueOf ( session.getAttribute("code") ); %>
Hello <%= attrib %> [B]
<%
%>
</TABLE>
<%
if (statement != null)
statement.close();
if (conn != null)
conn.close();
catch (Exception e) {out.print(e);}
%>
</BODY>
</HTML>
No as mentioned I am (as you can see) declaring everything as a string when in actual fact the contents of the "custorderno" within the query is set to a autonumber within MS Access.
The while loop does work by returning the contents but the session object part is not working correctly with the following result returned:
[B]java.sql.SQLException: No Data Found
Help please! -
How to get values/data stored in the database into a list-item.
how to get values/data stored in the database into a list-item.
i tried to make a list item without any values assigned to it...but i got the below error.
FRM-30191: No list items defined for required poplist.
or
FRM-32082: Invalid value for given item type.
List EMPNO
Item: EMPNO
Block: EMP
Form: MODULE5
FRM-30085: Unable to adjust form for output.
then according to some docs, i tried the the following for the trigger
when-new-form-instance
declare
rg_name varchar2(40) := 'emp_rec';
status number;
groupid recordgroup;
it_id item;
begin
it_id := Find_Item('empno');
groupid := create_group_from_query(rg_name, 'select empno from emp');
status := populate_group(groupid);
populate_list(it_id, groupid);
end;
but yet didnt work... :(
so how the heck do i get values fetched from the database table into the list item?for list items you need to values in the record group, one is the shown value and one is the returned value.
Check out the online help for the populate_list built-in.
You'll need something like select ename,ename from emp as the record group query. -
How do I insert into an array only if the condition is true?
I am buiding an array made up of pairs of data from a file. I am going through line by line putting the values in an array and then taking the pairs of two indexes oring them and putting the number into another array. I do not know if there is more than one set on each line so I have to do a while loop to check.The problem is I have to get the indexes in pairs, so for example I take in the element from index 0 and 1 and or them index 2 and 3 and or them, I do not need the combination of 1 and 2 or 3 and 4 and etc. I am using the "Quotient & Remainder" to check if the index is even or odd, if it is even I take that element and the very next index's element, I or them and put them in another array, but if i
t is odd I do not want to put anything into the array. How can I go about doing that? Any help would be appreciated. I am using version 6.1 Thanks, Molly
Attachments:
labview.bmp 3841 KBMolly,
Rather than running while loop which only executes code every other time you could instead just do a little more math to get your index values. Just multiply the iterator (i) terminal by 2 for the first index and then add 1 to it for the second (you'd need to run the loop half as many times of course). This would be more efficient and easier to read in your code. One other tip is that when you are running a loop a specified number of times it's cleaner to use a for loop rather than a while loop.
Regards,
Ryan K.
NI -
Recording tv into computer somehow....?
hello.
This may be a rediculous, amateur question, but is it possible to record tv into a computer?
Not necessarily live, but even a feed from a VCR while playing a pre-recorded tape.
Basically, what I'm trying to do, is be able to watch a previously recorded show without having to be home.......at my leisure, on my lap top.
I'm an avid sports fan, and I tape many games, and I just never have the time to watch them at home. But away from home, I always find a few hours of down time, and it would be awesome to have the games on my lap top in some kind of format.......
thank you.If you have recorded these in an analogue way (as most older VCRs do) then you'll need a gadget to convert it to a digital format when you want it on your laptop. There are various to choose from, including dedicated bits of harware for the job as well as some digital camcorders.
If you use something like eyeTV then you can record direct to a hard drive anyway and it is all digital - you can view the footage as and when you ahve time by using your laptop.
Finally, if you record on a DVD recorder then the footage can be stored on a DVD and you can watch it whenever you like... ! -
How to insert values into an array of class
Hello everyone,
I need help in inserting values into an array of class, which i have read from a file.
Length of the array is 5. I should insert values one by one into that array.
If the array is full (if count = 5), then I should split the array into 2 arrays
and adjust the values to left and right with median.
I'm getting an ArrayBoundException .. can anybody help me out ?
Thanks in advance
Here is my code..........
import java.util.*;
import java.io.*;
public class Tree
static String second;
static String first;
static int count = 5;
public void insert(int f1,int s1, int c)
if(c!=0)
Record[] rec = new Record[4];
for (int i = 0; i < 5; i++)
rec[i] = new Record();
for(int i = 0; i<=4;i++)
rec.x = f1;
rec[i].y = s1;
else
System.out.println("yes");
public static void main(String[] args)
Tree t = new Tree();
try
FileReader fr = new FileReader("output.txt"); // open file
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null)
StringTokenizer st = new StringTokenizer(s);
while(st.hasMoreTokens())
first = st.nextToken();
second = st.nextToken();
// System.out.println("First-->"+first+" "+"Second-->"+second);
int fir = Integer.parseInt(first);
int sec = Integer.parseInt(second);
t.insert(fir, sec, count);
fr.close(); // close file
catch (IOException e)
System.out.println("Can't read file");
class Record
public int x,y;Hi qwedwe.
Record[] rec = new Record[4];
for (int i = 0; i < 5; i++)
rec[i] = new Record();
}Here is your error: you have an array of 4 Records, but you create and (try to) insert 5 Record-instances.... try:
Record[] rec = new Record[c];
for (int i = 0; i < c; i++)
rec[i] = new Record();
}Regards,
Norman
Maybe you are looking for
-
ios 5 iphone4 Macbook pro- Every time I try to sync my iphone itunes crashes when adding photos. This has happened more than 50 times. Here is the error report I get. Any help would be appreciated. Process: iTunes [4844] Path:
-
Why has my norton 360 tool bar disapeared after installing firefox 6
i used to use norton identity safe with logins and cards etc but since up grading to forefox 6 it has disapeared with no norton tool bar .
-
How to call methods defined in another class ? is it possible?
Hi all, I am new to using JNI, was wondering if this is possible and how I might be able to do this. I'm trying to call some set/get functions defined in a class that is not part of the class where I have my native code defined and called... Let me e
-
External link for documentation in Query
Hi, in a query I have trained the display document link for Date and Masterdata. When I select the link I can visualize the content of the document created in BW. I have the necessity, instead, that when I call the link of the document from the quer
-
I am using a proxy on a web server to send my Portlet requests to the application server so the domain name of the URL through the web server is not the same as the application server domain name. When I use the createActionURL method of the renderRe