Need Help with a getText method
Gday all,
I need help with a getText method, i need to extract text from a JTextField. Although this text then needs to converted to a double so that i can multiply a number that i have already specified. As you may of guessed that the text i need to extract already will be in a double format.e.g 0.1 or 0.0000004 etc
Thanks for your help
ps heres what i have already done its not very good though
ToBeConverted.getText();
( need help here)
double amount = (and here)
total = (amount*.621371192);
Converted.setText("= " + total);
Double.parseDouble( textField.getText() );
Similar Messages
-
I need help with this recursion method
public boolean findTheExit(int row, int col) {
char[][] array = this.getArray();
boolean escaped = false;
System.out.println("row" + " " + row + " " + "col" + " " + col);
System.out.println(array[row][col]);
System.out.println("escaped" + " " + escaped);
if (possible(row, col)){
System.out.println("possible:" + " " + possible(row,col));
array[row][col] = '.';
if (checkBorder(row, col)){
System.out.println("check border:" + " " + checkBorder(row,col));
escaped = true;
else {
System.out.println();
escaped = findTheExit(row+1, col);
if (escaped == false)
escaped = findTheExit(row, col+1);
else if (escaped == false)
escaped = findTheExit(row-1, col);
else if (escaped == false)
escaped = findTheExit(row, col-1);
if (escaped == true)
array[row][col] = 'O';
return escaped;
}I am having difficulties with this recursion method. What I wanted here is that when :
if escaped = findTheExit(row+1, col); I am having trouble with the following statement:
A base case has been reached, escaped(false) is returned to RP1. The algorithm backtracks to the call where row = 2 and col = 1 and assigns false to escaped.
How do I fix this code?
I know what's wrong with my code now, even though that if
if (possible(row, col))
[/code[
returns false then it will go to if (escaped == false)
escaped = findTheExit(row, col+1);
how do I do this?Okay I think I got the problem here because I already consult with the instructor, he said that by my code now I am not updating my current array if I change one of the values in a specific row and column into '.' . How do I change this so that I can get an update array. He said to me to erase char[][] array = getArray and replace it with the array instance variable in my class. But I don't have an array instance variable in my class. Below is my full code:
public class ObstacleCourse implements ObstacleCourseInterface {
private String file = "";
public ObstacleCourse(String filename) {
file = filename;
public boolean findTheExit(int row, int col) {
boolean escaped = false;
//System.out.println("row" + " " + row + " " + "col" + " " + col);
//System.out.println(array[row][col]);
//System.out.println("escaped" + " " + escaped);
if (possible(row, col)){
//System.out.println("possible:" + " " + possible(row,col) + "\n");
array[row][col] = '.';
if (checkBorder(row, col)){
escaped = true;
else {
escaped = findTheExit(row+1, col);
if (escaped == false)
escaped = findTheExit(row, col+1);
else if (escaped == false)
escaped = findTheExit(row-1, col);
else if (escaped == false)
escaped = findTheExit(row, col-1);
if (escaped == true)
array[row][col] = 'O';
return escaped;
public char[][] getArray() {
char[][] result = null;
try {
Scanner s = new Scanner(new File(file));
int row = 0;
int col = 0;
row = s.nextInt();
col = s.nextInt();
String x = "";
result = new char[row][col];
s.nextLine();
for (int i = 0; i < result.length; i++) {
x = s.nextLine();
for (int j = 0; j < result.length; j++) {
result[i][j] = x.charAt(j);
} catch (Exception e) {
return result;
public int getStartColumn() {
char[][] result = this.getArray();
int columns = -1;
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
if (result[i][j] == 'S')
columns = j;
return columns;
public int getStartRow() {
char[][] result = this.getArray();
int row = -1;
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
if (result[i][j] == 'S')
row = i;
return row;
public boolean possible(int row, int col) {
boolean result = false;
char[][] array = this.getArray();
if (array[row][col] != '+' && array[row][col] != '.')
result = true;
return result;
public String toString() {
String result = "";
try {
Scanner s = new Scanner(new File(file));
s.nextLine();
while (s.hasNextLine())
result += s.nextLine() + "\n";
} catch (Exception e) {
return result;
public boolean checkBorder(int row, int col) {
char[][] array = this.getArray();
boolean result = false;
int checkRow = 0;
int checkColumns = 0;
try {
Scanner s = new Scanner(new File(file));
checkRow = s.nextInt();
checkColumns = s.nextInt();
} catch (Exception e) {
if ((row + 1 == checkRow || col + 1 == checkColumns) && array[row][col] != '+')
result = true;
return result;
I thought that my problem would be not to read the file using the try and catch everytime in the method. How do I do this?? Do I have to create an array instance variable in my class? -
I need help with my remove method on a BST!
Guys I need some help here, I have to create a remove method for a BST and below is my code:
public boolean remove(OrderedMap map, K keyOfelementToRemove) {
boolean result = false;
if (root == null)
result = false;
else {
MapNode curr = root;
MapNode prev = root;
while (curr.key.equals(keyOfelementToRemove) == false) {
prev = curr;
if (keyOfelementToRemove.compareTo(curr.key) < 0)
curr = curr.left;
else if (keyOfelementToRemove.compareTo(curr.key) > 0)
curr = curr.right;
if (curr == null)
break;
if (curr == null)
return result;
else if (curr == root && curr.left == null)
root = root.right;
else if (curr.left == null) {
if (curr.right == null)
curr = null;
else if (curr == prev.left)
prev = curr.right;
else if (curr == prev.right){
prev = curr.right;
else if (curr.left != null) {
MapNode temp = curr.left;
while (temp.right != null)
temp = temp.right;
K change = temp.key;
temp = null;
curr.key = change;
size--;
return result;
}the algorithm that my instructor provides is:
private boolean remove( BinaryTreeNode t, Comparable elementToRemove )
Set result to false
Traverse the tree t until elementToRemove is found. Use curr and prev to find the element
leaving curr referring the node you want to remove. It may be the case that curr is null indicating
that elementToRemove was not found. Now there are four cases to consider :
Case 1: Not found
return result (false)
Case 2: The root is to be removed, but it has no left child.
root = root's right subtree (assuming root refers the the root node in your BST)
Case 3: The node is further down tree with no left child. Now must adjust one of the parent's links
if curr is on the left side of prev,
move parent's left link down to down to curr's right child
else
curr is on the right side of prev, so move parent's right down to down to curr's right child
Case 4: curr has a left child.
We can no longer ignore the left subtree. So find the maximum in the left subtree and
move that object to the node referenced by curr . Then eliminate the maximum in the
left subtree, which is now being reference from the original node to remove.
however for case 3 and 4 it doesn't work, can someone please tell me why? I don't know where I made a mistake and I tried finding it but I still dont knowI am sorry about the double post. I'll try not to do this again. My problem here seems to be that prev and curr aren't updating the BST outside this method, which means that it only changes locally but not permanently. I will post the code of the other headings:
public class OrderedMap<K extends Comparable<K>, V> {
private class MapNode {
// Links to other BSTs
private MapNode left;
private MapNode right;
ArrayList<V> temp1 = new ArrayList<V>();
// The references to the key/value pair of the mapping
private K key;
@SuppressWarnings("unused")
private V value;
public MapNode(K theKey, V theValue) {
key = theKey;
value = theValue;
left = null;
right = null;
} // end class MapNode
private MapNode root;
private int size;
public OrderedMap() { // Create an empty tree
root = null;
size = 0;
public int size() {
return size;
} -
Need Help with new Classes / methods
Hi, I need to create a class called Proposition. It include a Proposition object with 3 variables
Name, Description, Value
This is the constructor I wrote:
private String name;
private String description;
private boolean value;
public Proposition(){
name = "name";
description = "description";
value = false;
}Now I need a method that give values to the 3 variables in the proposition object:
public Proposition setProp(String line){
StringTokenizer ST1 = new StringTokenizer(line, ".");
String ValidLine = ST1.nextToken()+".";
StringTokenizer ST2 = new StringTokenizer(ValidLine, "=");
name = CutSpace(ST2.nextToken());
description = (ST2.nextToken()).trim();
value = false;
return name;
return description;
return value;
}An example of String line is: v = we are in Vancouver.
When I run the program, I got error message with the 3 return statements saying found String/Boolean while Proposition is needed. I'm not quite sure how to write the return statements. Can any1 help?
Thx!Your setProp() method should not be returning anything. After all it is setting not getting. So just declare it as
public void setProp(String line){and remove the return statements. -
NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!
I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
Please reply soon!!! Thanks in advance.class a
private static String aa = "";
public static setVar (String var)
aa = var;
class b
public void init()
a.aa = "try";
public static void main(String b[])
b myB = new b ();
b.init();
hope this help;
bye _drag -
Need help with a remove method..
Hello. I'm getting started on a project here to implement a recursive remove method that will remove any number from a list. I was given a test that the method must pass, but I'm having some trouble getting started. This is my second interaction with the idea of recursion and it's a bit difficult for me.
Here is the test I'm writing the method for:
public void testRemove() {
int element=0;
boolean inList = false;
for (int i = -10; i < 11; i++)list.insert(i);
int numElements = list.length();
list.remove(element);
for (int e : list) {
if ( e == element ) inList = true;
assertTrue(!inList && (list.length()==(numElements-1)));
element = -10;
inList = false;
list.remove(element);
for (int e : list) {
if ( e == element ) inList = true;
assertTrue(!inList && (list.length()==(numElements-2)));
element = 10;
inList = false;
list.remove(element);
for (int e : list) {
if ( e == element ) inList = true;
assertTrue(!inList && (list.length()==(numElements-3)));
//does remove work when element's value greater than value of last item in list
element = 20;
inList = false;
list.remove(element);
for (int e : list) {
if ( e == element ) inList = true;
assertTrue(!inList && (list.length()==(numElements-3)));
//does remove work when element's value less than value of first item in list
element = -20;
inList = false;
list.remove(element);
for (int e : list) {
if ( e == element ) inList = true;
assertTrue(!inList && (list.length()==(numElements-3)));
System.out.printf("%s\n", "testRemove " + list.toString());
}Now, clearly I need to test whether or not the number being removed is in the list (too low/too high), but I'm stuck trying to implement this.
If anyone can give me any ideas or direction it would be greatly appreciated.Thanks for the quick reply, from what I had gathered and what you posted I'm starting to see where I need to go from here. I had gotten as far as if list is null return null, and the cod that you posted makes sense, but implementing it into the source code I already have will be troubling for me. The code as you presented it I have no trouble understanding, for example:
if (list.data == data) return list.next;
list.next=remove(list.next, data);Is clear to me, however I don't know how to implement that into my code. This is the code for the insert method:
private Node<ElementType> insertp(Node<ElementType> list, ElementType element) {
if ( (list == null) || ( element.compareTo(list.getElement() ) < 0 ) ) {
// test for insert at head or before current node
Node<ElementType> newNode = new Node<ElementType>(element, null);
newNode.setNext(list);
return newNode;
else if (list.getNext() == null) { // list with one element
Node<ElementType> newNode = new Node<ElementType>(element, null);
list.setNext(newNode); // element goes at end
else if ( element.compareTo(list.getNext().getElement()) < 0 ) { // insert after list
Node<ElementType> newNode = new Node<ElementType>(element, list.getNext());
//newNode.setNext(list.getNext());
list.setNext(newNode);
else {
insertp(list.getNext(), element); // find insertion point
return list;
}I'm still struggling to understand all of the code there. the element.compareTo() and everything. If you (or some one else) can explain to me what is going on with those methods, I may be able to implement it myself. Also, this may be of some use, these are the methods I have available to me:
public class Node<E> {
// Instance variables:
private E element;
private Node<E> next;
/** Creates a node with null references to its element and next node. */
public Node() {
this(null, null);
/** Creates a node with the given element and next node. */
public Node(E e, Node<E> n) {
element = e;
next = n;
// Accessor methods:
public E getElement() {
return element;
public Node<E> getNext() {
return next;
// Modifier methods:
public void setElement(E newElem) {
element = newElem;
public void setNext(Node<E> newNext) {
next = newNext;
public String toString() {
return element.toString();
} -
Need help with project (calling methods) please!!
Hi there i have a project for uni requiring me to create a java program that creates a random No. and lets the user have three guesses to find the No. When the users guesses correct he gets a message telling him hes won and if he doesnt get it correct he gets a message telling him the correct No then terminates.
The code has to call an outside method called[b] Public Static Boolean CheckGuess
I have tried to create this and got it to compile with no errors (eventually) but i keep getting a message saying i have whenever i type any number in. I think the problem is the way i am calling the method i havnt got much experience this is all pretty new to me any help would be really appreciated. Thanks.
import javax.swing.*;
import java.util.*;
public class Coursework1{
public static void main(String args[]){
int randomnumber,usersguessint,checkguess,guessvalid,attempts;
String usersguess,output;
boolean match;
//create random number generator
Random numGenerator = new Random();
//generate a random number between 1 & 10 inclusive
randomnumber = Math.abs(numGenerator.nextInt(9))+1;
//initialize variable attempts
for ( attempts = 0; attempts < 3; attempts++ ) {
//ask user for his first guess
usersguess=JOptionPane.showInputDialog("Please enter your guess between 1 & 10");
//convert users guess to integer
usersguessint = Integer.parseInt(usersguess);
//validate input
while (usersguessint<1||usersguessint>10){
usersguess=JOptionPane.showInputDialog("You entered an incorrect number \nPlease enter a numberbetween 1 & 10");
//convert users guess to integer
usersguessint = Integer.parseInt(usersguess);
} //end while loop
//call boolean method
if (match=true){
//display text area in JoptionPane
output="You won";
JOptionPane.showMessageDialog(null,output,"You Won",JOptionPane.INFORMATION_MESSAGE);
break;}
else{
output="Try again";
JOptionPane.showInputDialog("Try again");
} //end if
} //end for
}//end main
//user defined method
public static boolean checkGuess(int usersguessint,int randomnumber){
boolean match = false;
if (usersguessint == randomnumber){
match = true;
return match;
}//end method
}//endclassThank you very much that worked a treat the program is working better now. I have just realised that my for loopcontaining my counter may be in the wrong place as the program is running though both messages 3 times e.g
"Please enter your guess between 1 & 10"
"Try again"
"Please enter your guess between 1 & 10"
"Try again"
"Please enter your guess between 1 & 10"
"Try again"
"Please enter your guess between 1 & 10"
"Try again"
I want my program to run like
"Please enter your guess between 1 & 10"
"Try again"
"Try again"
"Try again"
Do u think if i placed my for stament (counter) in between the two messages it would eliminate this problem. -
hey to all my java Pals =)
i am working on an application right now
and my exit method behaves strangly
when you go to File|Exit
it will say
"this will exit are you sure
if the user says yes it will exit the program but if he says no it wont
but when you close it from the X up the Corner of the screen
it will say
"this will exit are you sure
but regardless of what user chose Yes|NO it will exit
what am i doing wrong thanks
my code
//File | Exit action performed
public void jMenuFileExit_actionPerformed(ActionEvent e) {
int forExit;
forExit = JOptionPane.showConfirmDialog(null,"This will Exit..........!!!!"+"\n"+"Are you Sure?","Exit?",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
System.out.println(forExit);
if(forExit==0){
System.exit(0);
//and for overriding the (X) on corner
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
jMenuFileExit_actionPerformed(null);
}sorry for my spelling its 12 at night and i didnt spell check
Thanks in advancehere is the code
public Frame1() {
addWindowListener(new java.awt.event.WindowAdapter(){
public void windowClosing(java.awt.event.WindowEvent evt){
jMenuFileExit_actionPerformed(null);
});and the exit
public void jMenuFileExit_actionPerformed(ActionEvent e) {
int forExit;
forExit = JOptionPane.showConfirmDialog(null,"This will Exit..........!!!!"+"\n"+"Are you Sure?","Exit?",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
System.out.println(forExit);
if(forExit==0){
System.exit(0);
} -
Hi, I am new to java and need help with sound methods.
q: create a new method that will halve the volume of the positive values and double the volume of the negative values.
Message was edited by:
Apaula30duplicate message #2
-
Need help with JTextArea and Scrolling
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
public class MORT_RETRY extends JFrame implements ActionListener
private JPanel keypad;
private JPanel buttons;
private JTextField lcdLoanAmt;
private JTextField lcdInterestRate;
private JTextField lcdTerm;
private JTextField lcdMonthlyPmt;
private JTextArea displayArea;
private JButton CalculateBtn;
private JButton ClrBtn;
private JButton CloseBtn;
private JButton Amortize;
private JScrollPane scroll;
private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
private JComboBox rateTermList;
double interest[] = {5.35, 5.5, 5.75};
int term[] = {7, 15, 30};
double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
int termInMonths, month, termLoop, monthLoop;
public MORT_RETRY()
Container pane = getContentPane();
lcdLoanAmt = new JTextField();
lcdMonthlyPmt = new JTextField();
displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
rateTermList = new JComboBox(rateTerm);
scroll = new JScrollPane(displayArea);
scroll.setSize(600,170);
scroll.setLocation(150,270);//DEFINE BUTTONS
CalculateBtn = new JButton("Calculate");
ClrBtn = new JButton("Clear Fields");
CloseBtn = new JButton("Close");
Amortize = new JButton("Amortize");//DEFINE PANEL(S)
keypad = new JPanel();
buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
keypad.add(new JLabel("Loan Amount$ : "));
keypad.add(lcdLoanAmt);
keypad.add(new JLabel("Term of loan and Interest Rate: "));
keypad.add(rateTermList);
keypad.add(new JLabel("Monthly Payment : "));
keypad.add(lcdMonthlyPmt);
lcdMonthlyPmt.setEditable(false);
keypad.add(new JLabel("Amortize Table:"));
keypad.add(displayArea);
displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
buttons.add(CalculateBtn);
buttons.add(Amortize);
buttons.add(ClrBtn);
buttons.add(CloseBtn);//ADD ACTION LISTENER
CalculateBtn.addActionListener(this);
ClrBtn.addActionListener(this);
CloseBtn.addActionListener(this);
Amortize.addActionListener(this);
rateTermList.addActionListener(this);//ADD PANELS
pane.add(keypad, BorderLayout.NORTH);
pane.add(buttons, BorderLayout.SOUTH);
pane.add(scroll, BorderLayout.CENTER);
addWindowListener( new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
public void actionPerformed(ActionEvent e)
String arg = lcdLoanAmt.getText();
int combined = Integer.parseInt(arg);
if (e.getSource() == CalculateBtn)
try
JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
if ((e.getSource() == CalculateBtn) && (arg != null))
try{
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
monthlyInterest = interest[0] / (12 * 100);
termInMonths = term[0] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
monthlyInterest = interest[1] / (12 * 100);
termInMonths = term[1] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
monthlyInterest = interest[2] / (12 * 100);
termInMonths = term[2] * 12;
monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest, -termInMonths))));
lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
catch(NumberFormatException ev)
JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
} //IF STATEMENTS FOR AMORTIZATION
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
loopy(7, 5.35);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
loopy(15, 5.5);
if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
loopy(30, 5.75);
if (e.getSource() == ClrBtn)
rateTermList.setSelectedIndex(0);
lcdLoanAmt.setText(null);
lcdMonthlyPmt.setText(null);
displayArea.setText(null);
if (e.getSource() == CloseBtn)
System.exit(0);
private void loopy(int lTerm,double lInterest)
double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
int amount, months, termloop, monthloop;
String lcd2 = lcdLoanAmt.getText();
amount = Integer.parseInt(lcd2);
termloop = 1;
paid = 0.00;
monthlyrate = lInterest / (12 * 100);
months = lTerm * 12;
monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
total = months * monthly;
balance = amount;
while (termloop <= lTerm)
displayArea.setCaretPosition(0);
displayArea.append("\n");
displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
displayArea.append("\n");
displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
monthloop = 1;
while (monthloop <= 12)
monthint = balance * monthlyrate;
monthprin = monthly - monthint;
balance -= monthprin;
paid += monthly;
displayArea.setCaretPosition(0);
displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
monthloop ++;
termloop ++;
public static void main(String args[])
MORT_RETRY f = new MORT_RETRY();
f.setTitle("MORTGAGE PAYMENT CALCULATOR");
f.setBounds(600, 600, 500, 500);
f.setLocationRelativeTo(null);
f.setVisible(true);
}need help with displaying the textarea correctly and the scroll bar please.
Message was edited by:
new2this2020What's the problem you're having ???
PS. -
Need Help With File Matching Records
I need help with my file matching program.
Here is how it suppose to work: FileMatch class should contain methods to read oldmast.txt and trans.txt. When a match occurs (i.e., records with the same account number appear in both the master file and the transaction file), add the dollar amount in the transaction record to the current balance in the master record, and write the "newmast.txt" record. (Assume that purchases are indicated by positive amounts in the transaction file and payments by negative amounts.)
When there is a master record for a particular account, but no corresponding transaction record, merely write the master record to "newmast.txt". When there is a transaction record, but no corresponding master record, print to a log file the message "Unmatched transaction record for account number ..." (fill in the account number from the transaction record). The log file should be a text file named "log.txt".
Here is my following program code:
// Exercise 14.8: CreateTextFile.java
// creates a text file
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class CreateTextFile
private Formatter output1; // object used to output text to file
private Formatter output2; // object used to output text to file
// enable user to open file
public void openTransFile()
try
output1 = new Formatter("trans.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
output2 = new Formatter("oldmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openOldMastFile
// add transaction records to file
public void addTransactionRecords()
// object to be written to file
TransactionRecord record1 = new TransactionRecord();
Scanner input1 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0) and amount.","? ");
while (input1.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record1.setAccount(input1.nextInt()); // read account number
record1.setAmount(input1.nextDouble()); // read amount
if (record1.getAccount() > 0)
// write new record
output1.format("%d %.2f\n", record1.getAccount(), record1.getAmount());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input1.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0) ",
"and amount.","? ");
} // end while
} // end method addTransactionRecords
// add account records to file
public void addAccountRecords()
// object to be written to file
AccountRecord record2 = new AccountRecord();
Scanner input2 = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s\n%s",
"Enter account number (> 0), first name, last name and balance.","? ");
while (input2.hasNext()) // loop until end-of-file indicator
try // output values to file
// retrieve data to be output
record2.setAccount(input2.nextInt()); // read account number
record2.setFirstName(input2.next()); // read first name
record2.setLastName(input2.next()); // read last name
record2.setBalance(input2.nextDouble()); // read balance
if (record2.getAccount() > 0)
// write new record
output2.format("%d %s %s %.2f\n", record2.getAccount(), record2.getFirstName(),
record2.getLastName(), record2.getBalance());
} // end if
else
System.out.println("Account number must be greater than 0.");
} // end else
} // end try
catch (FormatterClosedException formatterClosedException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input2.nextLine(); // discard input so user can try again
} // end catch
System.out.printf("%s %s\n%s", "Enter account number (> 0),",
"first name, last name and balance.","? ");
} // end while
} // end method addAccountRecords
// close file
public void closeTransFile()
if (output1 != null)
output1.close();
} // end method closeTransFile
// close file
public void closeOldMastFile()
if (output2 != null)
output2.close();
} // end method closeOldMastFile
} // end class CreateTextFile--------------------------------------------------------------------------------------------------
// Exercise 14.8: CreateTextFileTest.java
// Testing class CreateTextFile
public class CreateTextFileTest
// main method begins program execution
public static void main( String args[] )
CreateTextFile application = new CreateTextFile();
application.openTransFile();
application.addTransactionRecords();
application.closeTransFile();
application.openOldMastFile();
application.addAccountRecords();
application.closeOldMastFile();
} // end main
} // end class CreateTextFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.8: TransactionRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
public class TransactionRecord
private int account;
private double amount;
// no-argument constructor calls other constructor with default values
public TransactionRecord()
this(0,0.0); // call two-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public TransactionRecord(int acct, double amt)
setAccount(acct);
setAmount(amt);
} // end two-argument TransactionRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set amount
public void setAmount(double amt)
amount = amt;
} // end method setAmount
// get amount
public double getAmount()
return amount;
} // end method getAmount
} // end class TransactionRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: AccountRecord.java
// A class that represents on record of information
package org.egan; // packaged for reuse
import org.egan.TransactionRecord;
public class AccountRecord
private int account;
private String firstName;
private String lastName;
private double balance;
// no-argument constructor calls other constructor with default values
public AccountRecord()
this(0,"","",0.0); // call four-argument constructor
} // end no-argument AccountRecord constructor
// initialize a record
public AccountRecord(int acct, String first, String last, double bal)
setAccount(acct);
setFirstName(first);
setLastName(last);
setBalance(bal);
} // end four-argument AccountRecord constructor
// set account number
public void setAccount(int acct)
account = acct;
} // end method setAccount
// get account number
public int getAccount()
return account;
} // end method getAccount
// set first name
public void setFirstName(String first)
firstName = first;
} // end method setFirstName
// get first name
public String getFirstName()
return firstName;
} // end method getFirstName
// set last name
public void setLastName(String last)
lastName = last;
} // end method setLastName
// get last name
public String getLastName()
return lastName;
} // end method getLastName
// set balance
public void setBalance(double bal)
balance = bal;
} // end method setBalance
// get balance
public double getBalance()
return balance;
} // end method getBalance
// combine balance and amount
public void combine(TransactionRecord record)
balance = (getBalance() + record.getAmount());
} // end method combine
} // end class AccountRecord -------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatch.java
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Formatter;
import java.util.FormatterClosedException;
import org.egan.AccountRecord;
import org.egan.TransactionRecord;
public class FileMatch
private Scanner inTransaction;
private Scanner inOldMaster;
private Formatter outNewMaster;
private Formatter theLog;
// enable user to open file
public void openTransFile()
try
inTransaction = new Scanner(new File("trans.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openTransFile
// enable user to open file
public void openOldMastFile()
try
inOldMaster = new Scanner(new File("oldmast.txt"));
} // end try
catch (FileNotFoundException fileNotFoundException)
System.err.println("Error opening file.");
System.exit(1);
} // end catch
} // end method openOldMastFile
// enable user to open file
public void openNewMastFile()
try
outNewMaster = new Formatter("newmast.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openNewMastFile
// enable user to open file
public void openLogFile()
try
theLog = new Formatter("log.txt");
catch (SecurityException securityException)
System.err.println("You do not have write access to this file.");
System.exit(1);
} // end catch
catch (FileNotFoundException filesNotFoundException)
System.err.println("Error creating file.");
System.exit(1);
} // end method openLogFile
// update records
public void updateRecords()
TransactionRecord transaction = new TransactionRecord();
AccountRecord account = new AccountRecord();
try // read records from file using Scanner object
System.out.println("Start file matching.");
while (inTransaction.hasNext() && inOldMaster.hasNext())
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
account.setAccount(inOldMaster.nextInt()); // read account number
account.setFirstName(inOldMaster.next()); // read first name
account.setLastName(inOldMaster.next()); // read last name
account.setBalance(inOldMaster.nextDouble()); // read balance
if (transaction.getAccount() == account.getAccount())
while (inTransaction.hasNext() && transaction.getAccount() == account.getAccount())
account.combine(transaction);
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
transaction.setAccount(inTransaction.nextInt()); // read account number
transaction.setAmount(inTransaction.nextDouble()); // read amount
else if (transaction.getAccount() != account.getAccount())
outNewMaster.format("%d %s %s %.2f\n",
account.getAccount(), account.getFirstName(), account.getLastName(),
account.getBalance());
theLog.format("%s%d","Unmatched transaction record for account number ",transaction.getAccount());
} // end while
System.out.println("Finish file matching.");
} // end try
catch (NoSuchElementException elementException)
System.err.println("File improperly formed.");
inTransaction.close();
inOldMaster.close();
System.exit(1);
} // end catch
catch (IllegalStateException stateException)
System.err.println("Error reading from file.");
System.exit(1);
} // end catch
} // end method updateRecords
// close file and terminate application
public void closeTransFile()
if (inTransaction != null)
inTransaction.close();
} // end method closeTransFile
// close file and terminate application
public void closeOldMastFile()
if (inOldMaster != null)
inOldMaster.close();
} // end method closeOldMastFile
// close file
public void closeNewMastFile()
if (outNewMaster != null)
outNewMaster.close();
} // end method closeNewMastFile
// close file
public void closeLogFile()
if (theLog != null)
theLog.close();
} // end method closeLogFile
} // end class FileMatch-------------------------------------------------------------------------------------------------
// Exercise 14.8: FileMatchTest.java
// Testing class FileMatch
public class FileMatchTest
// main method begins program execution
public static void main( String args[] )
FileMatch application = new FileMatch();
application.openTransFile();
application.openOldMastFile();
application.openNewMastFile();
application.openLogFile();
application.updateRecords();
application.closeLogFile();
application.closeNewMastFile();
application.closeOldMastFile();
application.closeTransFile();
} // end main
} // end class FileMatchTest-------------------------------------------------------------------------------------------------
Sample data for master file:
Master file
Account Number Name Balance
100 Alan Jones 348.17
300 Mary Smith 27.19
500 Sam Sharp 0.00
700 Suzy Green -14.22Sample data for transaction file:
Transaction file Transaction
Account Number Amount
100 27.14
300 62.11
300 83.89
400 100.56
700 80.78
700 1.53
900 82.17 -------------------------------------------------------------------------------------------------
My FileMatch class program above has bugs in it.
The correct results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 173.19
500 Sam Sharp 0.00
700 Suzy Green 68.09The correct results for the log.txt:
Unmatched transaction record for account number 400Unmatched transaction record for account number 900------------------------------------------------------------------------------------------------
My results for the newmast.txt:
100 Alan Jones 375.31
300 Mary Smith 111.08
500 Sam Sharp 0.00
700 Suzy Green -12.69My results for the log.txt
Unmatched transaction record for account number 700-------------------------------------------------------------------------------------------------
I am not sure what is wrong with my code above to make my results different from the correct results.
Much help is appreciated. Please help.From the output, it looks like one problem is just formatting -- apparently you're including a newline in log entries and not using tabs for the newmast output file.
As to why the numbers are off -- just from glancing over it, it appears that the problem is when you add multiple transaction values. Since account.combine() is so simple, I suspect that you're either adding creating transaction objects incorrectly or not creating them when you should be.
Create test input data that isolates a single case of this (e.g., just the Mary Smith case), and then running your program in a debugger or adding debugging code to the add/combine method, so you can see what's happening in detail.
Also I'd recommend reconsidering your design. It's a red flag if a class has a name with "Create" in it. Classes represent bundles of independant state and transformations on that state, not things to do. -
I need Help with a website I've created
I need help with a website I've created (www.jonathanhazelwood.com/lighthouse) I created the folowing site with dreamweaver at my current resolution 1366 by 768. Looks great on my screen resolution but if it is viewed on other resolutions the menu moves and some of the text above and below. How can I keep all content centered and working like it does on 1366 by 768 on all resolutions. The htm to my site is below I started off with a blank template through dreamweaver CS5.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The Lighthouse Church</title>
<style type="text/css">
<!--
body {
font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
background: #42413C;
margin: 0;
padding: 0;
color: #000;
background-color: #000;
/* ~~ Element/tag selectors ~~ */
ul, ol, dl { /* Due to variations between browsers, it's best practices to zero padding and margin on lists. For consistency, you can either specify the amounts you want here, or on the list items (LI, DT, DD) they contain. Remember that what you do here will cascade to the .nav list unless you write a more specific selector. */
padding: 0;
margin: 0;
h1, h2, h3, h4, h5, h6, p {
margin-top: 0; /* removing the top margin gets around an issue where margins can escape from their containing div. The remaining bottom margin will hold it away from any elements that follow. */
padding-right: 15px;
padding-left: 15px; /* adding the padding to the sides of the elements within the divs, instead of the divs themselves, gets rid of any box model math. A nested div with side padding can also be used as an alternate method. */
a img { /* this selector removes the default blue border displayed in some browsers around an image when it is surrounded by a link */
border: none;
/* ~~ Styling for your site's links must remain in this order - including the group of selectors that create the hover effect. ~~ */
a:link {
color: #42413C;
text-decoration: underline; /* unless you style your links to look extremely unique, it's best to provide underlines for quick visual identification */
a:visited {
color: #6E6C64;
text-decoration: underline;
a:hover, a:active, a:focus { /* this group of selectors will give a keyboard navigator the same hover experience as the person using a mouse. */
text-decoration: none;
/* ~~ this fixed width container surrounds all other elements ~~ */
.container {
width: 960px;
background: #FFF;
margin: 0 auto; /* the auto value on the sides, coupled with the width, centers the layout */
/* ~~ This is the layout information. ~~
1) Padding is only placed on the top and/or bottom of the div. The elements within this div have padding on their sides. This saves you from any "box model math". Keep in mind, if you add any side padding or border to the div itself, it will be added to the width you define to create the *total* width. You may also choose to remove the padding on the element in the div and place a second div within it with no width and the padding necessary for your design.
.content {
padding: 10px 0;
/* ~~ miscellaneous float/clear classes ~~ */
.fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */
float: right;
margin-left: 8px;
.fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */
float: left;
margin-right: 8px;
.clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the overflow:hidden on the .container is removed */
clear:both;
height:0;
font-size: 1px;
line-height: 0px;
#apDiv1 {
position:absolute;
width:352px;
height:2992px;
z-index:1;
top: 171px;
left: 507px;
#apDiv2 {
position:absolute;
width:961px;
height:1399px;
z-index:1;
left: 187px;
top: 1px;
#apDiv3 {
position:absolute;
width:961px;
height:1001px;
z-index:1;
top: -2px;
#apDiv4 {
position:absolute;
width:963px;
height:58px;
z-index:1;
left: 0px;
top: 101px;
#apDiv5 {
position:absolute;
width:961px;
height:1505px;
z-index:1;
top: -5px;
#apDiv6 {
position:absolute;
width:962px;
height:150px;
z-index:1;
left: 0px;
top: -1px;
#apDiv7 {
position:absolute;
width:361px;
height:25px;
z-index:2;
left: 35px;
top: 1308px;
#apDiv8 {
position:absolute;
width:320px;
height:24px;
z-index:2;
left: 200px;
top: 1479px;
#apDiv9 {
position:absolute;
width:962px;
height:63px;
z-index:3;
left: -10px;
top: -1292px;
#apDiv10 {
position:absolute;
width:270px;
height:27px;
z-index:2;
left: 200px;
top: 1478px;
#apDiv11 {
position:absolute;
width:961px;
height:44px;
z-index:3;
left: 195px;
top: 183px;
-->
</style>
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#apDiv12 {
position:absolute;
width:295px;
height:23px;
z-index:4;
left: 198px;
top: 1px;
#apDiv13 {
position:absolute;
width:135px;
height:22px;
z-index:5;
left: 1001px;
top: 3px;
#apDiv14 {
position:absolute;
width:309px;
height:992px;
z-index:1;
left: 33px;
top: 479px;
#apDiv15 {
position:absolute;
width:327px;
height:999px;
z-index:1;
left: 324px;
#apDiv16 {
position:absolute;
width:262px;
height:1000px;
z-index:2;
left: 674px;
top: 477px;
#apDiv17 {
position:absolute;
width:85px;
height:34px;
z-index:1;
left: -379px;
top: 1001px;
#apDiv18 {
position:absolute;
width:200px;
height:115px;
z-index:6;
#apDiv19 {
position:absolute;
width:168px;
height:31px;
z-index:3;
left: 448px;
top: 1451px;
#apDiv20 {
position:absolute;
width:94px;
height:33px;
z-index:3;
left: 384px;
top: 1477px;
body {
background-color: #000;
margin-left: 0px;
margin-right: 0px;
#apDiv21 {
position:absolute;
width:920px;
height:200px;
z-index:4;
left: 19px;
top: 233px;
</style>
</head>
<body>
<div class="container">
<div class="content">
<div id="apDiv5">
<div id="apDiv16">
<div id="apDiv17">
<map name="Map2" id="Map2">
<area shape="rect" coords="4,2,77,28" href="http://www.myspace.com/lighthousechurch1" />
</map>
<img src="paypal-donate-button.png" width="83" height="33" border="0" usemap="#Map" />
<map name="Map" id="Map">
<area shape="rect" coords="2,2,80,30" href="https://www.paypal.com/us/cgi-bin/webscr?cmd=_flow&SESSION=HgApKd0bxyPQv1ixwBW3HgWXaLxPIiT Po9gSsRELLQp72IZ2-_8uvSmCLRO&dispatch=5885d80a13c0db1f8e263663d3faee8d9384d85353843a619606 282818e091d0" />
</map>
</div>
</div>
<div id="apDiv21">
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<p><img src="faithexplosion.png" width="314" height="225" /></p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
</div>
<div id="apDiv14">
<div id="apDiv15">
<div>
<div>
<p> Special Message from Perry Stone </p>
<h2> Was Jesus Born on December 25?</h2>
<p> 12/20/2010 </p>
<p><img alt="iStock_000003631829XSmall" src="http://www.voe.org/images/iStock_000003631829XSmall.jpg" width="300" height="234" /></p>
<p>Last year, in response to the growing number of Christians who celebrate Hanukkah but hate Christmas, I wrote an article for this website titled “Hanukkah or Christmas?” I explained why I think Jesus was either conceived or birthed on December 25.</p>
</div>
</div>
<div>
<div><a href="http://www.voe.org/Prophecy-Update/what-happened-to-global-warming.html"> READ MORE</a>
<p> Prophecy Update </p>
<h2> What Happened to Global Warming?</h2>
<p> 12/17/2010 </p>
<p> </p>
</div>
</div>
<div>
<div></div>
</div>
<div>
<div></div>
</div>
</div>
<div>
<p><font size="2">Special Word</font></p>
<p><font size="2">January 7th, 2011</font></p>
<p> <font size="2">Dear Viewers:</font></p>
<p><font size="2">We have now entered into one of the most trying times; but also one of the most glorious times in church history. Many things are coming upon the world and also upon the church and we (the church) must be totally prepared to take up our cross daily and venture out into the lost and</font></p>
<p> <a href="http://sermon.lighthousechurchinc.org/2011/01/07/special-word-1711-evangelist-barbara-lync h.aspx" target="_parent">Click Here for More</a></p>
</div>
<p> </p>
<div></div>
<div>
<!--// weAddFlash("lhi09hdr.swf",800, 100,"true","true","high","showall","true","#ffffff"); //--></div>
<div></div>
<p> </p>
</div>
<img src="lighthousegraphic2.jpg" width="960" height="1509" />
<div id="apDiv20"><img src="myspacebutton.jpg" width="89" height="30" border="0" usemap="#Map3" />
<map name="Map3" id="Map3">
<area shape="rect" coords="3,2,87,28" href="http://www.myspace.com/lighthousechurch1" />
</map>
</div>
</div>
<p> </p>
</div>
<!-- end .container --></div>
<div id="apDiv10"><font size="1"><font color="#FFFFFF">Copyright 2011 The Lighthouse Church Inc.</font></font></div>
<div id="apDiv11">
<ul id="MenuBar1" class="MenuBarHorizontal">
<li><a href="#">Home</a> </li>
<li><a href="#" class="MenuBarItemSubmenu">Our Pastor</a>
<ul>
<li><a href="#">Fresh Word</a></li>
<li><a href="#">Itinerary</a></li>
<li><a href="#">Prophetic Word</a></li>
<li><a href="#">Sermons</a></li>
<li><a href="#">Special Words</a></li>
<li><a href="#">Word of Month</a></li>
</ul>
</li>
<li><a href="#">Men Ministry</a></li>
<li><a href="#" class="MenuBarItemSubmenu">Ministers</a>
<ul>
<li><a href="#">Chris Gore</a></li>
</ul>
</li>
<li><a href="#" class="MenuBarItemSubmenu">Our Church</a>
<ul>
<li><a href="#">Contact Us</a></li>
<li><a href="#">Donate</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Our Store</a></li>
<li><a href="#">Prayer Request</a></li>
<li><a href="#">Salvation</a></li>
<li><a href="#">Subscribe</a></li>
<li><a href="#">Vision</a></li>
<li><a href="#">We Believe</a></li>
</ul>
</li>
<li><a href="#" class="MenuBarItemSubmenu">Resources</a>
<ul>
<li><a href="#">Prepare for Disaster</a></li>
<li><a href="#">How to Fast</a></li>
<li><a href="#">Heaven & Hell</a></li>
<li><a href="#">Warfare Prayers</a></li>
<li><a href="#">Wisdom Words</a></li>
</ul>
</li>
<li><a href="#" class="MenuBarItemSubmenu">Prophetic</a>
<ul>
<li><a href="#">Article Archive</a></li>
<li><a href="#">Audio Prophecies</a></li>
<li><a href="#">Color for Year</a></li>
<li><a href="#">Major Articles</a></li>
<li><a href="#">Prophecy Archive</a></li>
<li><a href="#">Prophetic Articles</a></li>
<li><a href="#">Word for Year</a></li>
</ul>
</li>
</ul>
</div>
<div id="apDiv12"><font size="1"><font color="#FFFFFF">6 South Railroad Ave Wyoming,DE 19934</font></font></div>
<div id="apDiv13"><font size="1"><font color="#FFFFFF">Phone:(302) 697-1472</font></font></div>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
</script>
</body>
</html>Look at all the apdiv's you have. Those are absolutely positioned layers. I'm assuming by your post that you are very new to Dreamweaver and HTML and CSS. I would highly recommend not using absolutely positioned layers until you have a better grasp on HTML and CSS.
Looking at your code I would suggest that you consider using one of Dreamweaver's built in, or downloadable templates as a starting point and work from there.
http://www.adobe.com/devnet/dreamweaver/articles/dreamweaver_custom_templates.html -
I need help with a VB Application
I need help with building an application and I am on a tight deadline. Below I have included the specifics for what I need the application to do as well as the code that I have completed so far. I am having trouble getting the data input into
the text fields to save to a .txt file. Also, I need validation to ensure that the values entered into the text fields coincide with the field type. I am new to VB so please be gentle. Any help would be appreciated. Thanx
•I need to use the OpenFileDialog and SaveFileDialog in my application.
•Also, I need to use a structure.
1. The application needs to prompt the user to enter the file name on Form_Load.
2. Also, the app needs to use the AppendText method to write the Employee Data to the text file. My project should allow me to write multiple Employee Data to the same text file. The data should be written to the text file in the following format (comma
delimited)
FirstName, MiddleName, LastName, EmployeeNumber, Department, Telephone, Extension, Email
3. The Department dropdown menu DropDownStyle property should be set so that the user cannot enter inputs that are not in the menu.
Public Class Form1
Dim filename As String
Dim oFile As System.IO.File
Dim oWrite As System.IO.StreamWriter
Dim openFileDialog1 As New OpenFileDialog()
Dim fileLocation As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
fileLocation = openFileDialog1.FileName
End If
'filename = InputBox("Enter output file name")
'oWrite = oFile.CreateText(filename)
cobDepartment.Items.Add("Accounting")
cobDepartment.Items.Add("Administration")
cobDepartment.Items.Add("Marketing")
cobDepartment.Items.Add("MIS")
cobDepartment.Items.Add("Sales")
End Sub
Private Sub btnSave_Click(ByValsender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
'oWrite.WriteLine("Write e file")
oWrite.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}{5,10}{6,10}{7,10}", txtFirstname.Text, txtMiddlename.Text, txtLastname.Text, txtEmployee.Text, cobDepartment.SelectedText, txtTelephone.Text, txtExtension.Text, txtEmail.Text)
oWrite.WriteLine()
End Sub
Private Sub btnExit_Click(ByValsender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
oWrite.Close()
End
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtFirstname.Text = ""
txtMiddlename.Text = ""
txtLastname.Text = ""
txtEmployee.Text = ""
txtTelephone.Text = ""
txtExtension.Text = ""
txtEmail.Text = ""
cobDepartment.SelectedText = ""
End Sub
End ClassHi Mikey81,
Your issue is about VB programming, so Visual Basic forum is a better forum for your case. I moved this thread there,
Thanks,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Need help with my usecase based on transient ViewObject
I am using 11.1.1.4.0 Jdev version. I need help with my usecase.Been trying it for 2 days but couldn't figure out the issue.
I have a transientVO . In this VO Rows will be populated programmatically. CountryId is an attribute of this VO. I have created a viewAccessor "CountriesVA" from Country VO of HR schema.
I have a LOV for the countryId which is based on this VA ,getting countries from CountryTable.
This is the model part which works fine.
Before the page load i have called a method to create a row for this transientVO.Once the row is created i can see the SOC in my page which i have created as below.
Now i want to insert a row in the transientVO if user selects a country and restrict duplicate entry . (As One row is already created 1st time there will be no rows created.after that rows will be inserted)
The issue is :: Suppose there are 2 countries. A & B .When user does the following actions :
Insert A . Done //as 1st entry
Insert B . Done //as 1st time entry
Insert A . duplicate not inserted
Insert B . getting inserted // the bug.
<af:selectOneChoice value="#{bindings.CountryId.inputValue}"
label="#{bindings.CountryId.label}"
required="#{bindings.CountryId.hints.mandatory}"
shortDesc="#{bindings.CountryId.hints.tooltip}" id="soc1"
immediate="true" autoSubmit="true"
valueChangeListener="#{pageFlowScope.managedBean.countryIdVC}">
public void countryIdVC(ValueChangeEvent valueChangeEvent) {
// Add event code here...
String oldValue=null;
setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getOldValue());
if(evaluateEL("#{bindings.CountryId.attributeValue}")!=null)
oldValue =evaluateEL("#{bindings.CountryId.attributeValue}").toString();
setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getNewValue());
String newValue=evaluateEL("#{bindings.CountryId.attributeValue}").toString();
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("ViewObj1Iterator");
//access the underlying RowSetIterator
RowSetIterator rsi = dciter.getRowSetIterator();
boolean duplicate=true;
if(oldValue!=null){
rsi.getCurrentRow().setAttribute("CountryId", oldValue);
// Row row= rsi.findByKey(new Key(new Object[] { newValue}), 1)[0];
Key key =new Key(new Object[] { newValue});
Row row=rsi.getRow(key);
if(row==null){
System.err.println(duplicate);
duplicate=false;
}else{
rsi.setCurrentRow(row);
if(!duplicate){
//get handle to the last row
Row lastRow = rsi.last();
//obtain the index of the last row
int lastRowIndex = rsi.getRangeIndexOf(lastRow);
//create a new row
Row newRow = rsi.createRow();
newRow.setAttribute("CountryId", newValue);
//initialize the row
newRow.setNewRowState(Row.STATUS_INITIALIZED);
//add row to last index + 1 so it becomes last in the range set
rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
//make row the current row so it is displayed correctly
rsi.setCurrentRow(newRow);I read the reply from Andrejus Baranovskis and thought of studying and implementing that in my useCase.Well it worked . I implemented the same Logic but rowIteration was done in AppModule.
Con-Fusion, Bugs, Facts &amp; Workarounds: Iterating through View Object RowIterator Bug.(NOT ADF BUG, Development B…
http://docs.oracle.com/cd/E15523_01/web.1111/b31974/bcservices.htm#sm0206
9.7.6 What You May Need to Know About Programmatic Row Set Iteration
The problem is solved ,the above links helped me solve the problem.
what i did is i have created a method in appmodule to iterate rows and all the method y operation bindings and my logic works fine ....
MY Advice to all Adf developers ,though i am not an expert but i can assure you to follow the above process for rowIteration.If you use the iterator binding in the manage bean to navigate the rows u'll face issues which are unexpected.
In AppModule :::::
public boolean createRow(String oldValue,String newValue){
System.err.println(oldValue+""+newValue);
ViewObjectImpl vo=getViewObj1();
boolean duplicate=false;
if(oldValue!=null){
RowSetIterator iter = vo.createRowSetIterator(null);
System.err.println("iterating rows ");
while (iter.hasNext()) {
Row r = iter.next();
System.err.println(iter.getRangeIndexOf(r)+" row is "+r.getAttribute("CountryId"));
if(r.getAttribute("CountryId").toString().equals(newValue)){
duplicate=true;
break;
// Do something with the current row.
// close secondary row set iterator
iter.closeRowSetIterator();
return duplicate;
In ManageBean :::::
public void countryIdVC(ValueChangeEvent valueChangeEvent) {
// Add event code here...
String oldValue=null;
System.err.println("Old Value"+valueChangeEvent.getOldValue());
setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getOldValue());
if(evaluateEL("#{bindings.CountryId.attributeValue}")!=null)
oldValue =evaluateEL("#{bindings.CountryId.attributeValue}").toString();
setEL("#{bindings.CountryId.inputValue}", valueChangeEvent.getNewValue());
String newValue=evaluateEL("#{bindings.CountryId.attributeValue}").toString();
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
//access the name of the iterator the table is bound to. Its "allDepartmentsIterator"
//in this sample
DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("ViewObj1Iterator");
//access the underlying RowSetIterator
RowSetIterator rsi = dciter.getRowSetIterator();
if(oldValue!=null){
rsi.getCurrentRow().setAttribute("CountryId", oldValue);
OperationBinding operation = bindings.getOperationBinding("createRow");
operation.getParamsMap().put("oldValue", oldValue);
operation.getParamsMap().put("newValue", newValue);
if(!(Boolean)operation.execute()){
//get handle to the last row
Row lastRow = rsi.last();
//obtain the index of the last row
int lastRowIndex = rsi.getRangeIndexOf(lastRow);
//create a new row
Row newRow = rsi.createRow();
newRow.setAttribute("CountryId", newValue);
//initialize the row
newRow.setNewRowState(Row.STATUS_INITIALIZED);
//add row to last index + 1 so it becomes last in the range set
System.err.println("Inserting row at index "+lastRowIndex+1);
rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
//make row the current row so it is displayed correctly
rsi.setCurrentRow(newRow);
else{
System.err.println("Data found So not inserting,only setting current Row");
Key key =new Key(new Object[] { newValue});
rsi.setCurrentRow(rsi.getRow(key)); -
Need help with my graphic calculator!!!
Hello everybody!! I need help with my little program I made.... The problem is that I am unable to use to calculate but it is possible to compile the code!! What should I do?? Thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Aritmetik extends JFrame implements ActionListener{
private JLabel l1 = new JLabel("Tal1: ", JLabel.LEFT);
private JLabel l2 = new JLabel("Tal2: ", JLabel.LEFT);
private JLabel l3 = new JLabel("Resultat",JLabel.LEFT);
private JLabel l4 = new JLabel(" ", JLabel.RIGHT);
private JTextField t1 = new JTextField(" ",10);
private JTextField t2 = new JTextField(" ",10);
private JButton b1 = new JButton("+");
private JButton b2 = new JButton("-");
private JButton b3 = new JButton("*");
private JButton b4 = new JButton("/");
public Aritmetik(){
Container v = getContentPane();
v.setLayout(new GridLayout(5,2));
v.add(l1);
v.add(t1);
v.add(l2);
v.add(t2);
v.add(b1);
v.add(b2);
v.add(b3);
v.add(b4);
v.add(l3);
v.add(l4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
pack();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent e){
int tal1 = Integer.parseInt(t1.getText());
int tal2 = Integer.parseInt(t2.getText());
if(e.getSource() == b1){
if(t1.getText().equals("") || t2.getText().equals(""))
JOptionPane.showMessageDialog(null, "Mata in tal!");
else{
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
else if(e.getSource() == b2){
int sub = tal1-tal2;
l4.setText(" " + (sub));
else if(e.getSource() == b3){
int multi = tal1*tal2;
l4.setText(" " + (multi));
else if(e.getSource() == b4){
int div = tal1/tal2;
l4.setText(" " + (div));
public static void main(String[] arg){
Aritmetik A =new Aritmetik();Here is your problem:
public void actionPerformed(ActionEvent e){
int tal1 = Integer.parseInt(t1.getText().trim()); // add the trim()
int tal2 = Integer.parseInt(t2.getText().trim()); // add the trim()
if(e.getSource() == b1){
if(t1.getText().equals("") || t2.getText().equals(""))
JOptionPane.showMessageDialog(null, "Mata in tal!");
else{
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
}... Better ...
public void actionPerformed(ActionEvent e) throws NumberFormatException {
String tala = t1.getText().trim();
String talb = t2.getText().trim();
if ( tala == null || "".equals(tala) || talb == null || "".equals(talb) ) {
JOptionPane.showMessageDialog(null, "Mata in tal!");
return();
int tal1 = Integer.parseInt(tala);
int tal2 = Integer.parseInt(talb);
if(e.getSource() == b1){
l3.setText("Resultat ");
l4.setText(" " + (tal1+tal2));
else if(e.getSource() == b2){
int sub = tal1-tal2;
l4.setText(" " + (sub));
else if(e.getSource() == b3){
int multi = tal1*tal2;
l4.setText(" " + (multi));
else if(e.getSource() == b4){
int div = tal1/tal2;
l4.setText(" " + (div));
}Message was edited by:
abillconsl
Maybe you are looking for
-
How do i sync my iphone4 contacts to mobile me or outlook 07?
hi there....please help. i signed up for mobile me thinking it would solve my issue and i can't figure it out. i am trying to sync my iphone contacts into my computer or to mobile me??? i dont have an activated contact list in outlook. when i connect
-
BI Foundation domain not visible in the EM after forms and Reports install
We installed OBIEE 11g successfully and it has created a domain i.e. bifoundation_domain. Whenever we used to login to EM and Weblogic Console, it was showing "bifoundation_domain". Yesterday we have further installed Oracle Forms/reports 11g server.
-
Hi, I have the scenerio where I am trying to send the data from File to SAP,so we have file adapters in XI and ABAP Proxies at th SAP side.Now I want to debug how exactly the flow is in like when I put files at the filezone then how XI Picks this and
-
Creating unsubscribe page in spaces application
Hi , In our application we are using spaces with custom task flow .We having some notification to send every time for some action.I have to create a new page , on which user can enter email id and click unsubscribe . This page should open from the li
-
ERPi database not updating from 11.1.2.1 to 11.1.2.2
I am in the process of updating from ERPI 11.1.2.1 to 11.1.2.2. I have moved the ERPI Oracle schema to a new DB and ERPI 11.1.2.2 is on a new server, in a new environment. When running the config tool to do the "configure database" task, I tried choo