Stringbuffer to Array....please help.
Is it possible to convert a stringbuffer into a 2d array?? I have a stringbuffer that contains the data for the table, when you look at the stringbuffer it has columns and rows as well as column headers in it. Is it at all possible to turn that into a 2d array? and if not how about just an array?
Here are some starting points. Until I know better what you want to do, it might be hard.
1. StringBuffer is used to combine chars and Strings into one single String. Maybe a Vector is more what you want. If you know the number of columns, but not the number of rows, a Vector of String Arrays would work.
Vector V = new Vector();
String [] S = null;
while( more rows ...)
S = new String[columncount];
for(int i = 0 ; i < columcount ;i++)
S[i] = column i for this row;
V.add(S)
//to show
for(int i = 0 ; i < V.size() ; i++)
String [] S = (String[])(V.get(i));
for(int j = 0 ; j < S.length ; j++)
System.out.print(S[j] + "\t");
System.out.println();
//also look into
String [][] S= new String[V.size()][];
V.copyInto(S);2. If you do want StringBuffer, the you are talking about parsing it. Are these tab separated columns with line breaks between?
Similar Messages
-
How to create an array - Please help
Hello. I have been trying to build a dynamic menu. According to different user role, they would have different access options to use the form. Now, I need to create a dynamic menu to display the menu options according to their user role. Somebody told me I can use an array, but I am not sure how to achieve this, and how to display the menu to user. Please help me. Thank you.
Hi
Arrays in Form are implemented through Record Groups. However you can enable and disable a menu item throught database roles.
For more infor please refer Oracle Documentation.
HTH
Arvind Balaraman
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by scsyim:
Hello. I have been trying to build a dynamic menu. According to different user role, they would have different access options to use the form. Now, I need to create a dynamic menu to display the menu options according to their user role. Somebody told me I can use an array, but I am not sure how to achieve this, and how to display the menu to user. Please help me. Thank you.<HR></BLOCKQUOTE>
null -
Absolute Distinct count in Array -----Please help me out
I'm running out of time and i have no clues to solve it.......can you please help me on it....
The Absolute Distinct Count on Sorted Array is the count of
distinct absolute values of elements of the array.
For example, for the array.
*[-5, -3, -1, 0, 3, 6]*
the absolute distinct count is 5, because there is 5 distinct
absolute values:
*0, 1, 3, 5, 6*
Write a function that computes the absolute distinct count
of a given array.No, above code wouldn't work. Though it will give distinct count, but not absolute distinct count.
Code to get absolute distinct count of elements in an array:
public static void main(String args[]){
int[] values = { -5, -3, -1, 0, 3, 6 };
List<Integer> list=new ArrayList<Integer>();
int tempVal=0;
for(int val : values){
tempVal=Math.abs(val);
if(!list.contains(tempVal)){
list.add(tempVal);
System.out.println("Absolute distinct count: "+list.size());
System.out.println("Absolute distinct elements: "+list.toString());
}Thanks,
Mrityunjoy -
Problems with string array, please help!
I have a String array floor[][], it has 20 rows and columns
After I do some statement to modify it, I print this array
out in JTextArea, why the output be like this?
null* null....
null null...
null null...
How to correct it?a turtle graphics applet:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TG extends JApplet implements ActionListener {
private int x, y;
private int pendown, command, movement;
String direction, output, temp;
JLabel l1;
JTextField tf1;
JTextArea ta1;
String floor[][] = new String[20][20];;
public void init()
x = 0;
y = 0;
pendown = 0;
direction = "r";
Container c = getContentPane();
c.setLayout( new FlowLayout() );
l1 = new JLabel( "Please type a command:" );
c.add( l1 );
tf1 = new JTextField(20);
tf1.addActionListener( this );
c.add( tf1 );
ta1 = new JTextArea(20,20);
ta1.setEditable( false );
c.add( ta1 );
public void actionPerformed( ActionEvent e )
temp = tf1.getText();
if( temp.length() > 1)
command = Integer.parseInt(temp.substring(0,1));
movement = Integer.parseInt(temp.substring(2,temp.length()));
else
command = Integer.parseInt(temp);
switch(command)
case 1:
pendown=0;
break;
case 2:
pendown=1;
break;
case 3:
direct("r");
break;
case 4:
direct("l");
break;
case 5:
move(movement);
break;
case 6:
print();
break;
public void direct(String s)
if(direction == "r" && s =="r")
direction = "d";
else if(direction == "r" && s =="l")
direction = "u";
else if(direction == "l" && s =="r")
direction = "u";
else if(direction == "l" && s =="l")
direction = "d";
else if(direction == "u" && s =="r")
direction = "r";
else if(direction == "u" && s =="l")
direction = "l";
else if(direction == "d" && s =="r")
direction = "l";
else if(direction == "d" && s =="l")
direction = "r";
public void move(int movement)
if(pendown == 1)
if(direction == "u")
for(int b=0;b<movement;b++)
floor[x][y+b] = "*";
else if(direction == "d")
for(int b=0;b<movement;b++)
floor[x][y-b] = "*";
else if(direction == "l")
for(int b=0;b<movement;b++)
floor[x-b][y] = "*";
else if(direction == "r")
for(int b=0;b<movement;b++)
floor[x+b][y] = "*";
else if(pendown == 0)
if(direction == "u")
for(int b=0;b<movement;b++)
floor[x][y+b] = "-";
else if(direction == "d")
for(int b=0;b<movement;b++)
floor[x][y-b] = "-";
else if(direction == "l")
for(int b=0;b<movement;b++)
floor[x-b][y] = "-";
else if(direction == "r")
for(int b=0;b<movement;b++)
floor[x+b][y] = "-";
public void print()
for(int row=0;row<20;row++)
for( int column=0;column<20;column++)
output += floor[row][column];
if(column == 19)
output+="\n";
ta1.setText(output);
} -
Random Numbers in an Array - Please Help!!
I just can't get it right. I have tried everything and it just won't work could you help me. I need to have an 8 element array and assign values excluding values in the range between 20 to 40 and excluding values in the range from 50 to 80. And I need to use the random method. Below is the code that I have created so far. Any suggestion?
import javax.swing.*;
public class MyArray
public static void main (String [ ] args)
JTextArea outputArea = new JTextArea ( );
int myArray [ ]; //array declaration
myArray = new int [ 8 ]; //allocating memory
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for ( int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
for ( int i = 0; i <myArray.length; i++)
myArray [ i ] = 1 + (int) (Math.random() * 19) ? (10*Math.random() + 39) : (1*Math.random() + 81);
output += "\n" + i + "\t" + myArray [ i ];
outputArea.setText (output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
System.exit ( 0 );How about:
Random rnd = new Random();
int[] numbers = new int[8];
for (int index=0; index<numbers.length; index++) {
int rNum;
while(((rNum = rnd.nextInt(Integer.MAX_VALUE))>=20 && rNum<=40) || (rNum>=50 && rNum<=80));
numbers[index] = rNum;
System.out.println(rNum);
} -
Displaying stringbuffer not working, please help
I have the following code in the jsp file,
s1 is a StringBuffer containing multiple lines of text.
<TEXTAREA NAME="DESCRIPTION" ROWS=8 COLS=100 value =
<%
out.println(s1);
System.out.println("\nJust Printed line(s)\n" + s1);
%>
>
</TEXTAREA>
Output from "just printed lines .. is fine.
But, out.println(s1) does not print anything in the textarea.
thanks
babuI think your text is not displaying on Browser.
if you want to display text of TextArea control it should be like this:
<TEXTAREA><%out.println(s1)%></TEXTAREA>
not the value tag as in TextBox for display.
zakir -
Having major problems with arrays, please help
Hi,
I'm writing a program to simulate a juke box using an array of strings to hold each track that is input. when the program starts, the user is asked the maximum number of songs to store, and this is passed to the constructor of the PlayList method, which sets up on array of Strings called queue with the total given.]
I have four options, one to add a song, one to play the first song in the queue and then remove it from the queue. One to display all the songs in playlist, and one to quit. NB it doesn't "play" the song it just displays a message saying "now playing - song name".
It all works UNTIL i choose option 2 (play first song and then remove it from the queue). This seems to work, but then when I choose to display all the songs, its not removed the right one, and now there's two of the same. I've been trying for hours with this, and it's really annoying me. Here's the PlayList class
public class PlayList
//declare attributes
private String [] queue;
private int total;
//declare constructor
public PlayList(int numsongs)
queue = new String [numsongs];
total = 0;
public boolean addToQueue(String track)
if (!isFull())
queue[total] = track;
total++;
return true;
else
return false;
public boolean removeFromQueue()
if (isEmpty())
return false;
else
int i;
//remove first item off queue -- queue[0]
for (i=1; i <= total-1; i++)
//rename the others
queue[i] = queue[i-1];
total--;
return true;
public boolean isEmpty()
if (total == 0) return true;
else return false;
public boolean isFull()
if (total == queue.length)
return true;
else
return false;
public String getItem(int item)
return queue[item-1];
public int getTotal()
return (total);
And here's the code from the main class which is executed.
public class JukeBox
public static void main(String[] args)
//delcare variables
int choice;
PlayList playlist;
int maxnum;
String song;
System.out.println("*** Jukebox simulator ***" + "\n");
System.out.print("Maximum number of songs in playlist: ");
maxnum = EasyIn.getInt();
playlist = new PlayList(maxnum);
do
System.out.println("\n" + "[1] Add song to playlist");
System.out.println("[2] Play first song in playlist");
System.out.println("[3] Display list of songs in playlist");
System.out.println("[4] Quit" + "\n");
System.out.print("Enter choice [1-4]: ");
choice = EasyIn.getInt();
//if statements for each case
if (choice == 1)
if (playlist.isFull())
System.out.println("*** Cannot add song, playlist is full ***");
else
System.out.print("Enter artist and song name - ");
song = new String(EasyIn.getString());
playlist.addToQueue(song);
System.out.println("\n" + "*** Song added to playlist ***");
System.out.println(song + "\n");
if (choice == 2) //display first song in queue, and then remove it from the queue
if (playlist.isEmpty())
System.out.println("*** No songs in playlist ***");
else
System.out.println("*** Now playing: ***");
System.out.println(playlist.getItem(1));
playlist.removeFromQueue();
if (choice ==3)
if (playlist.isEmpty())
System.out.println("*** No songs in playlist ***" + "\n");
return;
System.out.println("*** Songs currently in playlist ***");
for (int i = 1; i <= playlist.getTotal(); i++)
System.out.println(playlist.getItem(i));
if (choice == 4)
System.out.println("*** Thank you for using the juke box simulator ***");
while (choice != 4);
}Any ideas?Hi,
I just realised that before u posyed (honest, I did hehe), and now my code its like this
public boolean removeFromQueue()
int i;
if (isEmpty())
return false;
else
for (i=1; i <= total; i++)
queue[i-1] = queue[i-];
total--;
return true;
}But now I get IndexOutOfBoundsException :s -
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 -
Please help, 2D Array of Vectors and Incompatible types :(
I have a 2D array of vectors called nodeLocations but when I try and access the vector inside I get a compile error.
My code is something like this:
nodeLocations[j].addElement(noArc)
My editor picks up that its a Vector and shows me addElement as an acceptable entry to put after the "." yet the compiler says:
"addElement(java.lang.Object) in java.util.Vector cannot be applied to (int)"
Can someone please help?
Thank you in advance.
also a related problem:
I get inconvertible types (says int required) when I try and get an element from a vector stored in a 2D Array. I know that it comes out as an object and so should be cast but it does not seem to work. My code is as follows:
else if (((int)(nodeLocations[nodeNumber][adjNodeNumber].elementAt(0))) != distance)
I would appreciate any help anyone can give.
Similar errors to the above two happen when
I try a push with a Stack in a vector.
I try to get something out of the stack inside the vector.The Vector class's addElement() method requires an Object parameter. It appears that you're trying to add an int to the Vector. You'll need to create an Integer object and place that into the vector (see sample below) or use the pre-release version of JDK 1.5 which provides autoboxing capabilities.
int z = 5;
Integer x = new Integer(z);
nodeLocations[j].addElement(x); -
Simple array comparison not working. Please HELP!
I have been struggling to solve this problem for a few days now, and I'm slowly losing my mind.
I am in Adobe Acrobat 10.
I have a group of button fields called: btn0, btn1, btn2, etc.
I have a group of text fields called: txt0, txt1, txt2, etc.
I have a script that takes the value of txt0 and makes it the caption for btn0, and so on.
I have a script that sets the MouseUp action of btn0 to setFocus to txt0, and so on.
These scripts work fine.
I have a script that takes the values of all the txt fields and puts them in an array, and sorts it.
I have a script that takes the array[0] item and makes it the caption for btn0, and so on (alphabetizing my list of buttons).
Those scripts work fine.
I am trying to compare the value of the array[0] item to each of the txt fields to find the match, and then set the MouseUp action of btn0 to setFocus to the matching txt field, and so on (so my alphabetized list points to the correct locations).
This is where I'm at a loss.
Here is what I have:
//specified the txt fields
var txt0 = this.getField("Z name");
var txt1 = this.getField("A name");
//etc.
//put their values into an array called rxArray
var rxArray = [txt0.value, txt1.value]; //etc.
//sorted the array
rxArray.sort();
//set the captions equal to the sorted array items
for (var i = 0; i < 5; i++) {
var b = ("btn" + i);
this.getField(b).buttonSetCaption(rxArray[i]); //works fine; alphabetizes the list of buttons
//below is what goes wrong
for(var x = 0; x < 5; x++) {
var r = ("txt" + x);
if(rxArray[i] == r.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
Here is what I know:
The alphabetizing and labeling works fine, but the buttons' MouseUp scripts don't work at all. Nothing happens.
If I change the following piece of the above script:
if(rxArray[i] == r.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
To this:
if(rxArray[i] == txt1.value){
var s = (r + ".setFocus();");
this.getField(b).setAction("MouseUp", s);
Because rxArray[0] does equal the value of txt1 ("A name"), then the MouseUp script for btn0 gets set to:
txt4.setFocus();
So I know that, each time the nested loop runs, the if statement is true, and the setFocus script updates. Until the end of the loop, leaving the setFocus as the last item run. So why doesn't my script work? It should only update the setFocus script IF the array item matches the txt field, and should set it to THAT txt field.
Please please help. I know I'm missing something simple in there somewhere.@Try67:
That's a good question. I was running into some other issues and have revamped my code. Here is what I have in my test file:
A list of five buttons and a list of five text fields. One additional button that sets the focus to the next empty text field to add a new item, and two additional buttons, one that sorts my list alphabetically, and one that unsorts it.
with the following field names
The sort button calls function sortName and the unsort calls function sortNumber (the order of entry).
Here are those scripts in final form:
function sortName() {
//first reset the captions for the buttons to blank
for (var a = 0; a < 5; a++) {
var b = ("btn" + a);
this.getField(b).buttonSetCaption("");
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var rxArray = [txt0.value, txt1.value, txt2.value, txt3.value, txt4.value];
for(var m = rxArray.length - 1; m > -1; m--){
if(rxArray[m] == ""){
rxArray.splice(m, 1);
rxArray.sort();
var newArray = [txt0, txt1, txt2, txt3, txt4];
for(var n = newArray.length - 1; n > -1; n--){
if(newArray[n].value == ""){
newArray.splice(n, 1);
for (var i = 0; i < rxArray.length; i++) {
var b = ("btn" + i);
this.getField(b).buttonSetCaption(rxArray[i]);
for (var x = 0; x < newArray.length; x++) {
if(rxArray[i] == newArray[x].value){
var s = ("this.getField('" + newArray[x].name + "').setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
function sortNumber() {
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var newArray = [txt0, txt1, txt2, txt3, txt4];
for (var x = 0; x < newArray.length; x++) {
var b = ("btn" + x);
this.getField(b).buttonSetCaption(newArray[x].value);
var s = ("this.getField('" + newArray[x].name + "').setFocus();");
this.getField(b).setAction("MouseUp", s);
//end
As you can see, I've used the array lengths rather than fixed numbers, except when clearing the button values. I use a number there because there is no array to reference and didn't feel like making an array just for that. The number of buttons won't change.
I've also added in a splice() method to remove the blank entries from my arrays when appropriate (making using the array length even more important).
The result of the sort is:
The only quirk I've found in all this is with the Add New button, which calls function addNew, which is:
function addNew() {
var txt0 = this.getField("t0");
var txt1 = this.getField("t1");
var txt2 = this.getField("t2");
var txt3 = this.getField("t3");
var txt4 = this.getField("t4");
var newArray = [txt0, txt1, txt2, txt3, txt4];
for (var i = newArray.length - 1; i > -1 ; i--) {
if (newArray[i].value == "") {
newArray[i].setFocus();
//end
For this, I would have though that running through the array from start to finish looking for the first empty text field and setting the focus to it would have been correct. But that resulted in the last empty text field being focused. So I reversed the for loop to run finish to start, and the result was that the first empty field was focused. Not sure why that is... -
ARRAY and records at multiple level ? please help
Hi experts!!
I am struck up with a problem. If u can please help me.
I need a structure of this type.
create type GRADE as object(
grade varchar2(30)
/ -- works fine , creates
create type GRADE_ARRAY as VARRAY(10) of GRADE;
/ -- works fine and creates
create type SPECIES as object
Species_number number,
array_of_grade GRADE_ARRAY
/ works fine
create type SPECIES_ARRAY as VARRAY(20) of SPECIES;
-- error comes here.. Can not have multiple level..type error
and so can not go ahead. In fect I wanted to use next level also. like this.
The next command remains my dream only then because I could not create the SPECIES ARRAY it self..
create type TIMBER as object
timber_mark varchar2(6),
no_species number,
array_of_species(20) SPECIES_ARRAY
the problem is for multiple level ARRAY AND RECORD/object combination..
I tried with OBJECT AND VARRAY it does only for one level.. not even two level.
my Mail ID:
[email protected]
Thanks and Regards..
Virendra chauhanI think multi-level collections was first implemented in 9.2. You failed to mention what version of the DB you are using.
-
Creating an Array of external JPGs, please help.
So what I want to do is load up external JPGs into an Array of MovieClips, and then go to the main onEnterFrame function. My code is below:
var imageLoader:Loader = new Loader();
var imageArray:Array = new Array();
function loadImage():void {
for (i = 0; i < 9; i++) {
imageLoader.load(new URLRequest("image" + String(i) + ".jpg"));
imageArray[i] = new MovieClip();
imageArray[i].addChild(imageLoader);
addEventListener(Event.ENTER_FRAME,onEnterFrame);
I tried adding an Event.COMPLETE function I found:
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
function imageLoaded(e:Event):void {
var image:Bitmap = (Bitmap)(e.target.content);
imageArray[i] = new MovieClip();
imageArray[i].addChild(image);
Unfortunately, I usually only ended up with 1 or 0 images, and errors. I can't seem to properly pass the i
value, so that's a big problem because the order the images go is key to my program.
Please help me get this working so my image gallery can work, thanks!So the problem is that you want them in the array in the same sequence am I right on this?
See the updated code:
var imageArray:Array = new Array();
var imageLoader:Array = new Array();
function loadImage():void {
for (i = 0; i < 9; i++) {
var imageLoader[i] = new Loader();
imageArray[i] = new MovieClip();
imageLoader.load(new URLRequest("image" + String(i) + ".jpg"));
imageArray[i].addChild(imageLoader[i]);
//imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
addEventListener(Event.ENTER_FRAME,onEnterFrame);
/* function imageLoaded(e:Event):void {
var image:Bitmap = (Bitmap)(e.target.content);
imageArray[index].addChild(image);
In this case you can not track whether an image is loaded or not. It is the most simplest way of doing this. If your images are not coming from dynamic sources and are fixed in number and position you can use this method also. -
Parse into array using JDOM! please help
hey,
i've managed to parse an xml document using JDOM
i[b] need to be able to parse it and store the text (the value of each node) into an array, and then insert into db etc.
the problem is with the recursive function listChildren which calls itself... can someone tell me where do i insert the block of code such that i can store it into an array of string.
here's the code:
public static void parse(String stock) throws SQLException
SAXBuilder builder = new SAXBuilder();
Reader r = new StringReader(stock);
Document doc = builder.build(r);
Element root = doc.getRootElement();
listChildren(root, 0);
public static void listChildren(Element current, int depth) throws Exception
String nodes = current.getName();
System.out.println(nodes + " : " + current.getText());
List children = current.getChildren();
Iterator iterator = children.iterator();
while(iterator.hasNext())
Element child = (Element) iterator.next();
listChildren(child, depth+1);
i'm looking for something like:
a=current.getText();
but i donno where to include this line of code, please help
cheers,
Shivek Sachdevhi, I suggest you make an array of byte arrays
--> Byte[][] and use one row for each number
you can do 2 things,
take each cipher of one number and put one by one in each column of the row correspondent to that number. of course it may take too much room if the int[] is too big, but that is the easiest way I think
the other way is dividing your number into bitsets(class BitSet) with sizes of 8 bits and then you can save each bit into each column of your array. and you still have one number in each row. To put your numbers back use the same class.
Maybe someone has an easier way, I couldnt think of any. -
Problem with array size...PLEASE HELP
hi...
I want to keep putting the Strings that user inputs, in an array. I don't know how many of them there are, and I don't want to define a big array like :
String myArray[]= String [1000];
what am I suppose to do?
PLEASE HELP...!
ThanksUse a Vector or an ArrayList instead of a straight array.
-
Array of CreditCard objects - PLEASE HELP!
My situation is this: I need to create an array of CreditCard objects. The problem is that when I try to invoke the methods getName, getNumber, or getLimit, the compiler recognizes the array (cardholders) as a variable.
My coding is this.
for(int i=0;fileInput.hasNext();i++)
CreditCard[] cardholders = new CreditCard[records];
int cardNum = Integer.parseInt(fileInput.next());
String cardName = fileInput.nextLine();
double cardLimit = Double.parseDouble(fileInput.nextLine());
cardholders[i] = new CreditCard(cardNum, cardName, cardLimit);
But when I try to access a CreditCard object, through cardholders[4] (for example), the error cannot find symbol appears. PLEASE HELP ITS DRIVING ME CRAZY.
THANKSYou are lacking basic Java knowledge, micksabox. The following tutorial is on Arrays in Java. The one after on the Java Collections Framework, you might want to learn about as the better solution for working with sets and lists of objects in Java.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
http://java.sun.com/docs/books/tutorial/collections/index.html -
The file just won't load into array...Please Help!
hi i need some help in loading a binary file into an array so that i can edit the data that was saved from previous run..
i could save the file but after that when i try to load it back to memory...i can't...ie. all the information keyed in were lost...please help
this is the Code for the loading process...
public static void loadAircraft (ArrayList aircraft) {
try {
FileInputStream filein = new FileInputStream(".\\Data\\Aircraft.bin");
ObjectInputStream objectin = new ObjectInputStream(filein);
Aircraft craft = (Aircraft) objectin.readObject();
aircraft.add(craft);
objectin.close();
filein.close();
catch (Exception e) {}
}the above code won't load anything into memory...is there a way for overcoming this?
inside the Aircraft class there are four different data of which they contain two differen data types.
one of which is String and the other three are in int.
Awaiting for reply...thanksyes...its some objects of an array that i am trying to load back...
erm...i'll show you the whole code maybe...
//to reference the swing library
import javax.swing.*;
import java.util.*;
import java.io.*;
public class SetupAircraft {
static ArrayList aircraft;
public static void init () {
aircraft = new ArrayList(5);
loadAircraft(aircraft);
//opens up another sub group while the user
//entered 1 as his/her option in the SetupSystem
//menu
public static void Setup () {
//this will create a string that is going to be displayed
//in the input dialog box
String menu = " Please select an option: \n"
+"----------------------------\n"
+"1) Add New Aircraft\n"
+"2) Edit Existing Aircraft\n"
+"3) List Aircraft\n"
+"4) Delete Existing Aircraft\n"
+"5) Save\n"
+"6) Return to Main Menu\n\n"
+" Enter a number between 1-6\n";
//declare a field named option for selection through menu
int option = 0;
//continue the loop until the user inputs the number 6
do {
//error handling for the input from the menu
//if the input is not integer the error is caught and
//reassigning option to be 0
try {
option = Integer.parseInt(JOptionPane.showInputDialog(null, menu,
"Setup Aircraft", JOptionPane.QUESTION_MESSAGE));
catch (NumberFormatException e) {
option = 0;
//determine which option the user has chosen
//and enters the respective section
switch (option) {
case 1: add(aircraft);
break;
case 2: edit(aircraft);
break;
case 3: list(aircraft);
break;
case 4: //delete(aircraft);
break;
case 5: save(aircraft);
break;
case 6: return;
default: JOptionPane.showMessageDialog(null, "Please enter a number between 1-6",
"Alert", JOptionPane.ERROR_MESSAGE);
option = 0;
while (true);
public static void add (ArrayList aircraft) {
String type = "";
int first = 0;
int business = 0;
int economy = 0;
do {
try {
type = JOptionPane.showInputDialog(null,"Enter Aircraft Type", "Prompt for Type",
JOptionPane.QUESTION_MESSAGE);
try {
if(aircraft.contains(type)) {
JOptionPane.showMessageDialog(null, type + " already exist!",
"Error", JOptionPane.ERROR_MESSAGE);
type = "-100";
catch (Exception e) {}
if (type=="-100");
else if (type.length()==0) {
JOptionPane.showMessageDialog(null, "Please enter an aircraft type",
"Error", JOptionPane.ERROR_MESSAGE);
else if (!(type.startsWith("-",3))) {
JOptionPane.showMessageDialog(null, "Please enter the aircraft type with XXX-XXX format where X is integer.",
"Error", JOptionPane.ERROR_MESSAGE);
type = "0";
//catch the input error that the user has produces.
catch (Exception e) {
return;
while (!(type.startsWith("-",3)));
//try to ask the user for the passenger's name and if the name field contains
//no characters at all repeat the prompt for name field until the user presses
//Cancel.
try {
first = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter First Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
try {
business = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Business Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
try {
economy = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Economy Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
Aircraft newAircraft = new Aircraft (type, first, business, economy);
aircraft.add(newAircraft);
JOptionPane.showMessageDialog(null, "Aircraft Sucessfully Added",
"Successful", JOptionPane.INFORMATION_MESSAGE);
public static void edit (ArrayList aircraft) {
String type = "";
int first = 0;
int business = 0;
int economy = 0;
do {
try {
type = JOptionPane.showInputDialog(null, "Enter Aircraft Type to Edit",
"Prompt for Type", JOptionPane.QUESTION_MESSAGE);
if (type.length()==0) {
JOptionPane.showMessageDialog(null,"Please enter an aircraft type",
"Error",JOptionPane.ERROR_MESSAGE);
else if (!(type.startsWith("-",3))) {
JOptionPane.showMessageDialog(null, "Please enter the aircraft type with XXX-XXX format where X is integer.",
"Error", JOptionPane.ERROR_MESSAGE);
type = "0";
catch (Exception e) {
return;
while (!(type.startsWith("-",3)));
try {
int edited = aircraft.indexOf(new UniqueAircraft(type));
Aircraft craft = (Aircraft)aircraft.get(edited);
try {
first = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter First Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
try {
business = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Business Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
try {
economy = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Economy Class Capacity",
"Prompt for Capacity", JOptionPane.QUESTION_MESSAGE));
catch (Exception e) {
String error = "For input string:";
if (e.getMessage() == "null") {
return;
else if (e.getMessage().startsWith(error)) {
JOptionPane.showMessageDialog(null, "Please enter only numbers",
"Error", JOptionPane.ERROR_MESSAGE);
Aircraft newAircraft = new Aircraft (type, first, business, economy);
aircraft.add(newAircraft);
aircraft.add(newAircraft);
JOptionPane.showMessageDialog(null, "Successfully edited aircraft\n"+type+" to capacities\n"
+"First: "+first+"\n"+"Business: "+business+"\n"+"Economy: "+economy,
"Successful", JOptionPane.INFORMATION_MESSAGE);
catch (Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
public static void list (ArrayList aircraft) {
JOptionPane.showMessageDialog(null, aircraft.size()+" aircraft found", "Found",JOptionPane.INFORMATION_MESSAGE);
Object[] aircrafts;
aircrafts = aircraft.toArray();
for (int i=0;i<aircraft.size();i++) {
Aircraft a = (Aircraft) aircrafts;
JOptionPane.showMessageDialog(null, a, "Aircrafts" + (i+1), JOptionPane.INFORMATION_MESSAGE);
public static void save (ArrayList aircraft) {
try {
FileOutputStream fileout = new FileOutputStream(".\\Data\\Aircraft.bin");
ObjectOutputStream objectout = new ObjectOutputStream(fileout);
Object[] aircrafts;
aircrafts = aircraft.toArray();
objectout.writeObject(aircrafts);
objectout.close();
fileout.close();
JOptionPane.showMessageDialog(null,aircraft.size()+" aircrafts saved", "Sucessful", JOptionPane.INFORMATION_MESSAGE);
catch (IOException e) {
JOptionPane.showMessageDialog(null,e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
public static void loadAircraft (ArrayList aircraft) {
try {
FileInputStream filein = new FileInputStream(".\\Data\\Aircraft.bin");
ObjectInputStream objectin = new ObjectInputStream(filein);
Aircraft craft = null;
while ((craft=(Aircraft)objectin.readObject())!=null) {
aircraft.add(craft);
objectin.close();
filein.close();
catch (Exception e) {
JOptionPane.showMessageDialog(null,e.toString());
e.printStackTrace();
i think thats a bit too long..but it would explain what i am trying to save...its linking to the class Aircraft tho...
thanks...i appreciate your help...
Maybe you are looking for
-
When I have typed an email and press spell check it sayed that browser will check it for me. When I tested it the spelling mistake was left uncheck by MSN Hotmail and or Firefox. Which? How do I get the spell check to work? Rgds Chris
-
Presentation variable problem in PDF generation
Hi, I have created the custom field using the following code *case when (V_balance.yr<=@{var_year}{2009} and V_balance.yr>=@{var_year-3}{2006}) then 1 else 0 end* Use this field I have created the filter and remove the field from report. When I run t
-
I am doing a JMS to IDOC scenario... i am getting an error: com.sap.aii.utilxi.misc.api.BaseRuntimeException thrown during application mapping com/sap/xi/tf/_ECC_TTG_CREATE_: RuntimeException in Message-Mapping transformatio~ Before it was working fi
-
SAP Business One DI Proxy service terminated unexpectedly
Hi All, DI Proxy service doesn't work correctly and it generate an entry in event viewer: SAP Business One DI Proxy service terminated unexpectedly. Does anyone know what can be the reason? I checked diproxyserver.properties file and everything is ok
-
SQLException : Result Set is IDLE
Hi, Am accessing a DB stored procedure, executing it using executeQuery() & then fetching the resultset. There are 2 resultset objects returned. Am getting this exception when fetching the result set objects. It says soemthing like: "Result Set is ID