Need help combining cd's
Please Help..When downloading cd's...it seperates some of them..for example Tracy Lawrence Strong..it put the first three songs on one..then right next to it is another cd with the remaining songs..Ray Charles Genius loves company has TWELVE seperate album covers with one song each? How the heck do I get them under one?? I have tried and tried..Kid Rock and Eminem are a MESS..and all over the place!! ty for any help
Generally setting a common Album Artist will fix things.
For deeper problems see Grouping tracks into albums.
tt2
Similar Messages
-
Need help combining docs in Pages or Preview--glitches
I'm trying to combine about 20 short docs into one, so it will print as one document. I've tried the following, and run into these problems:
1) Copying thumbnails in Pages. This works most of the time--however, every now and then, it will only copy one page of a multiple-page document. It doesn't seem to matter what/where I click, only the first page of the doc will copy over. This seems to happen every fourth document or so.
2) In Preview: tried combining PDFs by dragging and dropping from the sidebar. However, that created something that, while looking like a 38 page single document, still considered each document as separate. When I went to print, it would only print the document that was in the window.
3) In Preview: tried doing the drag-and-drop by dragging directly on to the page in the sidebar, instead of below or above (as recommended for Snow Leopard in a MacWorld article). Didn't work. The green plus sign appeared, but after I dragged and dropped, the new pages would disappear.
It would be incredibly helpful if I could solve this problem. I've combined a number of how-to sheets into a packet, and not being able to combine them into a single document means a very long night of collating!
Thanks for any help.
BTW, I'm on an iMac, Snow Leopard (10.6.8), Preview 5.0.3 and Pages 4.1.When copying the Thumbnails in Pages '09 to paste into the Thumbnails of a 2nd document, they both must have the same page dimensions and orientation.
When selecting make sure you have all the sections selected (surrounded by a yellow border). Hold down the shift key and select a range or individual selections if need be.
I have tested this and it works. Even between Word Processing and Layout templates.
In Preview I tested the merge and yes there appears to be a bug, even after saving, then printing.
It is not just the two parts treated as separate however, it seems to drop pages at random. Some from the dragged over version and some from the original.
Possibly it is retaining only pages with different numbers, because it did not renumber them. I will test it further later on when I have time.
Peter -
Powershell - Need help combining multiple commands (?) into one script
Scenario:
When a user is terminated from our company, I run these scripts separately:
1. I use the script below in Windows Powershell ISE to launch an entry box so I can enter in the username@domain and get a list of distribution groups the termed employee currently manage export to a CSV file on my desktop:
Add-PSSnapin quest.activeroles.admanagement
$USerID = Read-host "Enter in Username@domain. Example: [email protected]"
connect-QADService -service blah.dc1.cba.corp -UseGlobalCatalog
get-qadgroup -ManagedBy $UserID -Verbose | select Name,Type,DN | export-csv -
NoTypeInformation "$home\desktop\$UserID.csv" -Verbose -Force
2. I launch Powershell as an Administrator and run the following to activate Exchange Management in Powershell and to give me access to the entire forest of accounts:
Add-PSSnapin -name "Microsoft.Exchange.Management.PowerShell.E2010"
Set-AdServerSettings -ViewEntireForest $true
3. Next, I run this script to remove the former owner's write permissions from the list of distribution lists they managed in the above CSV file:
import-csv -Path "<PATH>" | Foreach-Object {Remove-ADPermission -Identity $_.Name -
User '<domain\username>' -AccessRights WriteProperty -Properties “Member” -
Confirm:$false}
4. I run this script to show the new owner of the DLs, allow DL management via Webmail and add info in the Notes section on the DLs:
import-csv -Path "<PATH>" | Foreach-Object {set-Group -Identity $_.Name -ManagedBy
"<domain\username>" –Notes “<Enter Here>”}
5. I run this script to allow management via Outlook and to automatically check the box in Active Directory "Manager can update membership list" under the Managed By tab within the Group's Properties:
import-csv -Path "<PATH>" | Foreach-Object {Add-ADPermission -Identity $_.Name -User
‘<domain\username’ -AccessRights WriteProperty -Properties “Member”}
Is there a way I can combine this into one Powershell script or two, at the most instead of having to copy and paste 6 different times and use two programs (Powershell and Powershell ISE)?Rhys, again, thanks to your script, I was able to add even more to it to run nicely in PowerShell ISE (running as an Administrator):
The following happens in the script below in this order:
1. The script allows searching across multiple e-mail domains that we manage in Exchange
2. It prompts for entry of the old owner's ID, the new owner's ID and notes that I want to add to the DLs.
3. It exports a copy of lists owned by the old owner to a CSV file on my desktop.
4. Powershell pauses and allows me to modify the old owner's.CSV file so I can remove any lists that should not be transferred, save the changes to the CSV file and click continue in Powershell ISE. If all lists should be transferred to the new owner, I
would simply not edit the CSV export and click OK in Powershell ISE.
5. Powershell ISE updates the DLs from the CSV export using the information I entered in the entry boxes.
6. Powershell sleeps for about 1 minute after updating the DLs to allow Active Directory to register the changes. Then, Powershell ISE exports a copy of the lists transferred to the new owner to a <newownerID>.csv file on my desktop. This allows me
to compare the CSV files (which should have the same exact lists on them) and make sure all of the lists were successfully transferred.
7. If the lists are not the same because Active Directory didn't update in time while the file csv export was running for the new owner, I can run the script again with the exception of using the newownerID for the entry boxes in Step 2 (Notes don't matter
as we won't execute any additional steps after capturing the updated export). You would simply select Cancel during the pause window that comes after the export completes to prevent the script from continuing a second time and overwriting your previous entries.
8. You can now compare the updated newowner.csv to the oldowner.csv file on your desktop.
Add-PSSnapin -name "Microsoft.Exchange.Management.PowerShell.E2010"
Add-PSSnapin quest.activeroles.admanagement
Set-AdServerSettings -ViewEntireForest $true
connect-QADService -service xyz-fakeserver.corp -UseGlobalCatalog
Do {
$FormerOwner = Read-host "Enter in former DL owner as Username@domain."
$UserID = Read-host "Enter in new DL owner as Username@domain."
$Notes = Read-host "Enter in Notes for DL"
Try {
get-qadgroup -ManagedBy $FormerOwner -Verbose -ErrorAction Stop | select Name | export-csv -NoTypeInformation "$home\desktop\$FormerOwner.csv" -Verbose -Force
Read-Host 'Edit <FormerOwner>.CSV file on desktop to remove groups that should stay with current owner, save changes and press Enter or click OK to continue script. If all groups need to be transferred to new owner, do not modify CSV file and press Enter
or click OK to continue.'
import-csv -Path "$home\desktop\$FormerOwner.csv"
$UserList = import-csv "$home\desktop\$FormerOwner.csv"
$Userlist | Foreach-Object {
Remove-ADPermission -Identity $_.Name -User $FormerOwner -AccessRights WriteProperty -Properties “Member” -Confirm:$false
set-Group -Identity $_.Name -ManagedBy $UserID –Notes $Notes
Add-ADPermission -Identity $_.Name -User $UserID -AccessRights WriteProperty -Properties “Member”
Start-Sleep -s 60
get-qadgroup -ManagedBy $UserID -Verbose -ErrorAction Stop | select Name | export-csv -NoTypeInformation "$home\desktop\$UserID.csv" -Verbose -Force
$Flag = $True
} Catch {
Write-Host "Invalid username or user not found, please try again"
} While (!$Flag) -
Need help combining multiple audiobook cds into single mpeg file for Ipod
I have been unable to find an application that will let me combine multiple MPEG audio files into a single MPEG file. My goal is to combine several CDs from an audiobook into a single file so that I can listen to it on my Ipod. Also, it would take up a lot less space as an ITunes listing. Mediajoiner was recommended on some other forums, but I could not find a version that worked with OS X and Java 1.5.
Any help is appreciated[MP3Trimmer|http://www.deepniner.net/mp3trimmer>
-
Need help combining values in a drop down
I have a prompt which uses sql results to populate the values in a drop down...
sql results, select "table".column from "db" where "table".column in ('value1','value2','value3','value4',value5',etc)
Is it possible to have one of the values in the drop down be a combination of other values in the drop down? I would want to have something like value1, value2, value3, value2 and value3 combined. I would also like to choose a name for the combined values, which will show up in the drop down.
thanks,
Brianyou can try multiselect in the drop down
-
Need help combining a Layout and Graphics
Okay, I've been working on this for a long time now, and I'm getting close...but not quite.
I want to have a JApplet where I can use Graphics methods, as well as JButton, etc. However, if I set my applet to use a certain type of Layout (setLayout), it will only display the JButton and none of the graphics that I drew in paintComponent(). If I don't define a Layout at all, the JButton covers the entire applet. If I take out the JButton and the Layout, then I do see the Graphics. So, it's like the Graphics are being hidden underneath the Layout, and I don't know how to get them to show through.
Here's what I have...as you can see from the billion commented lines, I tried a lot of different things.
import javax.swing.*; // Imports JButton, JTextArea, JTextField
import java.awt.*; // Imports Canvas
import java.awt.event.*; // Imports ActionEvent, ActionListener
public class HashTableApplet extends JApplet
public void init()
PaintStuff paint = new PaintStuff();
Container contentPane = getContentPane();
JButton startButton = new JButton("Start");
//Determine the "look" of the Applet:
contentPane.setLayout(null);
contentPane.add(paint);
// Add in the button:
Insets insets = contentPane.getInsets();
contentPane.add(startButton);
startButton.setBounds(25 + insets.left, 5 + insets.top, 75, 20);
class PaintStuff extends JPanel
public PaintStuff()
//setBackground(Color.lightGray);
public void paintComponent(Graphics g)
super.paintComponent(g);
//setOpaque(false);
g.setColor(Color.yellow);
// drawLine(x1, y1, x2, y2)
g.drawLine(50, 50, 100, 100);
g.drawLine(0, 200, 700, 200);
g.drawRect(200, 200, 200, 200);
}/* <applet code="GraphicApplet" width="400" height="300"></applet>
* use: >appletviewer GraphicApplet.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class GraphicApplet extends JApplet {
GraphicPanel graphicPanel = new GraphicPanel();
int colorCount = 0;
public void init() {
final Color[] colors = {
Color.orange, Color.yellow, Color.pink
final JButton button = new JButton("Change Background");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = colors[colorCount++ % colors.length];
graphicPanel.setBackgroundColor(color);
JPanel northPanel = new JPanel();
northPanel.add(button);
Container cp = getContentPane();
// default layout for JPanel (== JApplet) is Flow Layout
cp.setLayout(new BorderLayout());
cp.add(northPanel, "North");
cp.add(graphicPanel, "Center");
* Convenience method allows you to run this from the command line.
public static void main(String[] args) {
JFrame f = new JFrame("Grpahic Applet");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new GraphicApplet();
f.getContentPane().add(applet);
f.setSize(400,300);
f.setLocationRelativeTo(null);
applet.init();
applet.start();
f.setVisible(true);
class GraphicPanel extends JPanel {
Color bgColor;
public GraphicPanel() {
setBackground(Color.black);
bgColor = Color.red;
// add listeners here
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int width = getSize().width;
int height = getSize().height;
int cx = width/2;
int cy = height/2;
int diameter = Math.min(width, height)*2/3;
g2.setPaint(bgColor);
g2.fill(new Rectangle2D.Double(width/8, height/8, width*3/4, height*3/4));
g2.setPaint(Color.blue);
g2.draw(new Rectangle2D.Double(cx - diameter/2, cy - diameter/2,
diameter, diameter));
g2.setPaint(Color.green);
g2.draw(new Ellipse2D.Double(cx - diameter/2, cy - diameter/2,
diameter, diameter));
public void setBackgroundColor(Color color) {
this.bgColor = color;
repaint();
} -
Is this the right software to download if I want to put together a short video? I have about 10 clips on my video camera, but have no experience video editing!
Thanks!
DawnNo, Prelude isn't the right tool. Premiere is Adobe's video editing program, but be warned - it is a professional piece of software that isn't designed to be very approachable by someone who has no video editing experience. Kind of like jumping into a Ferrari on your first driving lesson...
If you are on a mac, try iMovie. On a PC...I don't know what the equivalent is.... -
Need HELP (Project Issue) : Having 3 individual VIs, datalogger.vi, start vi, amksms.vi done.
(How to run the VIs in sequence order - datalogger > start > amksms combine into 1 VIs? )VIs in icon.
how would it able to run in the sequence order:
data first, follow by start and lastly amk sms.
Attachments:
dsa.jpg 10 KB -
Need help in combining two similair SQLs into one
DB Version:10gR2
I need to combine the following two queries into one query and return the following three columns
Unprocessed Quantity1,Unprocessed Quantity2, Total Uprocessed Cost
Unprocessed Quantity1 can be determined using
select t.ITEM, sum(t.QTY)
from (select cd.ITEM_ID ITEM, cd.ACTL_QTY QTY
from CONVEY_HDR ch, CURRENT_INVN cd, ALLOC_HDR ah
where ........
UNION
select sd.ITEM_ID ITEM, sd.INVN_QTY QTY
from shp_dtl pd
UNION
Select item_id, inv_qty from another table
GROUP BY.....
ITEM SUM(T.QTY)
88JAT 25
000002395 1
300108396 27
000004397 7
73984290 15Unprocessed quantity2 can be determined using
select t.ITEM, sum(t.QTY)
from (select cd.ITEM_ID ITEM, cd.ACTL_QTY QTY
from CONVEY_HDR ch, CURRENT_INVN cd, ALLOC_HDR ah
where rownum<6
group by t.ITEM
order by t.ITEM;
ITEM SUM(T.QTY)
189436171 2
009438837 160
000040685 16
000032410 18Total Unprocessed Cost can found using the sum of Quantities for a particular Item from above two queries multiplied by
ITEM_COST for that ITEM (which is found in ITEM_DTL table). For every item; ITEM_DTL.item_id=CARTON_dTL.carton_id
Total Unprocessed Cost= (Unprocessed Quantity1+Unprocessed Quantity2)*ITEM_DTL. ITEM_COST
Note: Unprocessed Quantity2 query looks very similair to first SQL in UNION of Unprocessed Quantity1, but ah.STAT_CODE < 90 for Unprocessed Quantity2 query
Edited by: user636669 on Jan 14, 2009 10:40 AM
Edited by: user636669 on Jan 14, 2009 10:57 AM
Corrected typo
Edited by: user636669 on Jan 14, 2009 7:07 PMHi,
Put the two queries you posted in sub-queries. You can then use their result sets as if they were tables.
Do something like this:
WITH uq1 AS
select t.ITEM, sum(t.QTY) AS total
from (select cd.ITEM_ID ITEM, cd.ACTL_QTY QTY
from CASE_HDR ch, CASE_DTL cd, ASN_HDR ah
... the rest of your first query goes here
, uq2 AS
select t.ITEM, sum(t.QTY) AS total
from (select cd.ITEM_ID ITEM, cd.ACTL_QTY QTY
from CASE_HDR ch, CASE_DTL cd, ASN_HDR ah
... the rest of your second query goes here
SELECT uq1.item
, uq1.total AS "Unprocessed Quantity1"
, uq2.total AS "Unprocessed Quantity2"
, (uq1.total + uq2.total) * dtl.item_cost
AS "Total Uprocessed Cost"
FROM uq1
JOIN uq2 ON uq1.item = uq2.item
JOIN item_dtl dtl ON uq1.item = dtl.item;If some items are in uq1 but not in uq2 (or vice-versa), then you'll probably want to do outer joins.
I don't have any of the tables used, so I can't test this myself.
If you need more help. then post a little sample data from each of the tables, and the results you want from that data.
It looks like you're doing the same join in each of your original queries.
You can add another sub-query that does that join once, and then use that sub-query in sub-queries uq1 and uq2. -
I have 6 pictures that I need to combine in one.
if1996 wrote:
I have 6 pictures that I need to combine in one.
if1996,
I am assuming that you wish to place these pictures on one background as a collage, and that your paper stock is 8.5"x11".
Ideally, these 6 pictures will have the same resolution. You can check this via Image>resize>image size. It is expressed in px/in. The rule of thumb is that for printing, the resolution should be in 240-300px/in range
Do the math so that the 6 pictures will fit on to the canvas - perhaps some are in landscape orientation, some portrait.
If you need to crop a picture(s) to a specific size, use the crop tool (on a duplicate picture).
If you are with me so far, try the following:
Go to File>new>blank file, enter width& height of the paper, and resolution the same value as that of the pictures or as close as possible., background color to suit
Open picture A, go to Select>all, go to Edit>copy to place it on the clipboard
Go back to the blank file, then Edit>paste
Use the move tool to position picture A, and to resize it with the corner handles of the bounding box, if necessary
Repeat steps 2-4 for pictures B,C,D,E,F.
You should have 7 layers: Background (the canvas) and 6 layers with the pictures. No doubt you will have to adjust the position of the pictures - just activate the appropriate layer, and use the move tool.
For orientation, it is very helpful to have the grid open (View>grid). This will not print. -
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 trim and null function
Hi all,
I need help with a query. I use the trim function to get the first three characters of a string. How do I write my query so if a null value occurs in combination with my trim to say 'Null' in my results?
ThanksHi,
Thanks for the reply. What am I doing wrong?
SELECT trim(SUBSTR(AL1.user_data_text,1,3)),NVL
(AL1.user_data_text,'XX')
FROM Table
I want the XX to appear in the same column as the
trim.The main thing you're doing wrong is not formatting your code. The solution may become obvious if you do.
What you're saying is:
SELECT trim ( SUBSTR (AL1.user_data_text, 1, 3))
, NVL ( AL1.user_data_text, 'XX' )
FROM Tablewhich makes it clear that you're SELECTing two columns, when you only want to have one.
If you want that column to be exactly like the first column you're currently SELECTing, except that when that column is NULL you want it to be 'XX', then you have to apply NVL to that column, like this:
SELECT NVL ( trim ( SUBSTR (AL1.user_data_text, 1, 3))
, 'XX'
FROM Table -
first of all, who has heard of the game called zuul? It is a very boring text based game I am currently having the pleasure of improving.
Basically, you are in a room, that is connected to a bunch of other rooms and depending on the room you are in, you have different exists and different items in the room.
The goal is to navigate through the collection of Rooms and there is no real win condition, It is more for learning then for actually playing.
You navigate by a series of commands such as: go (direction)( as in "direction of exit", NSEW), quit, a few other odd bits.
ex: go south, quit, go west etc
The game has several classes: Game, Command, CommandWords, Item, Parser, Room.
Obviously Game is the main central head conch, (it is not the super class.)
Game makes use of Item, Room, Parser, and Command.
Item is the class that deals with the number of items in the Room.
Room is the class that deals with the rooms the player will navigate to and from.
Command reads in the commands such as "go-(direction)" or "quit".
Parser makes everybody understand each other by using both Command and CommandWords.
CommandWords is a list of commands such as "go", "quit" etc.
The problem I am having right now is to allow a player to move through the rooms while holding a certain item. The item has to come from the rooms and the player should be able to drop it.
So I have to add two new commands: take and drop. The problem is that I have been asked to do this without creating a new class. Otherwise I would have just created class Player and be done with it. So I am trying to figure out whose responsibility should it be to take care of the take and drop command. I have done some preliminary work in class Game, it is the take(Command command) and drop() methods.
I have also a few questions concerning other aspects of the project, I have listed their locations here:
1. The take() method in class Game, the for-each loop, a complier error with ArrayList
2. class Parser, a general question about the string tokenzier
If you want to see how the game is suppose to run, just comment out the bodies of take() and drop(). Not the declaration. Everything else works.
I shall now provide the code to all classes. I wish there were an option to upload a zip file, then you don't have to read through all the codes and copy&paste all the codes. The complier I am using is BlueJ. And the SDK version is 1.6. With the exception of class Game, everything else can be assumed to be error free.
Thank you for your time,
Davy
class Game
import java.util.*;
* This class is the main class of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. Users
* can walk around some scenery. That's all. It should really be extended
* to make it more interesting!
* To play this game, create an instance of this class and call the "play"
* method.
* This main class creates and initialises all the others: it creates all
* rooms, creates the parser and starts the game. It also evaluates and
* executes the commands that the parser returns.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
public class Game
private Parser parser;
private Room currentRoom;
private Room previousRoom;
private Stack<Room> previousRooms;
* Create the game and initialise its internal map.
public Game()
createRooms();
parser = new Parser();
* Create all the rooms and link their exits together.
private void createRooms()
Room outside, theatre, pub, lab, office;
// create the rooms
outside = new Room("outside the main entrance of the university");
theatre = new Room("in a lecture theatre");
pub = new Room("in the campus pub");
lab = new Room("in a computing lab");
office = new Room("in the computing admin office");
// create some items
Item desk, chair, beer, podium, tree;
desk = new Item("desk", "student desk",10);
chair = new Item("chair", "student chair",5);
beer = new Item("beer", "glass of beer", 0.5);
podium = new Item("podium", "lecture podium", 100);
tree = new Item("tree", "a tree", 500.5);
// put items in some of the rooms
outside.addItem(tree);
theatre.addItem(desk);
theatre.addItem(chair);
theatre.addItem(podium);
pub.addItem(beer);
pub.addItem(beer);
office.addItem(desk);
lab.addItem(chair);
lab.addItem(beer);
// initialise room exits
outside.setExit("east", theatre);
outside.setExit("south", lab);
outside.setExit("west", pub);
theatre.setExit("west", outside);
pub.setExit("east", outside);
lab.setExit("north", outside);
lab.setExit("east", office);
office.setExit("west", lab);
currentRoom = outside; // start game outside
previousRooms = new Stack<Room>(); // no rooms on the stack
previousRoom = null;
* Main play routine. Loops until end of play.
public void play()
printWelcome();
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
System.out.println("Thank you for playing. Good bye.");
* Print out the opening message for the player.
private void printWelcome()
System.out.println();
System.out.println("Welcome to the World of Zuul!");
System.out.println("World of Zuul is a new, incredibly boring adventure game.");
System.out.println("Type 'help' if you need help.");
System.out.println();
System.out.println(currentRoom.getLongDescription());
* Given a command, process (that is: execute) the command.
* @param command The command to be processed.
* @return true If the command ends the game, false otherwise.
private boolean processCommand(Command command)
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return false;
String commandWord = command.getCommandWord();
if (commandWord.equals("help")) {
printHelp();
else if (commandWord.equals("go")) {
goRoom(command);
else if (commandWord.equals("look")) {
look(command);
else if (commandWord.equals("eat")) {
eat(command);
else if (commandWord.equals("back")) {
back(command);
else if (commandWord.equals("stackBack")) {
stackBack(command);
else if (commandWord.equals("take")){
take(command);
else if (commandWord.equals("drop")) {
drop(command);
else if (commandWord.equals("quit")) {
wantToQuit = quit(command);
// else command not recognised.
return wantToQuit;
// implementations of user commands:
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
private void printHelp()
System.out.println("You are lost. You are alone. You wander");
System.out.println("around at the university.");
System.out.println();
System.out.println("Your command words are:");
System.out.println(parser.getCommands());
* Try to go to one direction. If there is an exit, enter the new
* room, otherwise print an error message.
* @param command The command entered.
private void goRoom(Command command)
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
String direction = command.getSecondWord();
// Try to leave current room.
Room nextRoom = currentRoom.getExit(direction);
if (nextRoom == null) {
System.out.println("There is no door!");
else {
previousRooms.push(currentRoom);
previousRoom = currentRoom;
currentRoom = nextRoom;
System.out.println(currentRoom.getLongDescription());
* "Look" was entered.
* @param command The command entered.
private void look(Command command)
if(command.hasSecondWord()) {
System.out.println("Look what?");
return;
System.out.println(currentRoom.getLongDescription());
* "Eat" was entered.
* @param command The command entered.
private void eat(Command command)
if(command.hasSecondWord()) {
System.out.println("Eat what?");
return;
System.out.println("You have eaten and are no longer hungry!");
* "Back" was entered.
* @param command The command entered.
private void back(Command command)
if(command.hasSecondWord()) {
System.out.println("Back what?");
return;
if (previousRoom==null) {
System.out.println("Can't go back.");
return;
// push current room on stack (for stackBack)
previousRooms.push(currentRoom);
// swap current and previous rooms (for back)
Room temp = currentRoom;
currentRoom = previousRoom;
previousRoom = temp;
// You could replace the previous three lines with the following
// which use the stack to get the previous room
// but note that this makes "back" dependent on "stackBack".
// (If you do it this way you no longer need "temp".
// currentRoom = previousRoom;
// previousRoom = previousRooms.peek();
System.out.println("You have gone back:");
System.out.println(currentRoom.getLongDescription());
* "StackBack" was entered.
* @param command The command entered.
private void stackBack(Command command)
if(command.hasSecondWord()) {
System.out.println("StackBack what?");
return;
if (previousRooms.isEmpty()) {
System.out.println("Can't go StackBack.");
return;
// set previous room (for "back")
previousRoom = currentRoom;
// set new current room (using stack)
currentRoom = previousRooms.pop();
System.out.println("You have gone StackBack:");
System.out.println(currentRoom.getLongDescription());
* allows a player to take something from the room
* @param command
private void take(Command command){
String a;
a=command.getSecondWord();
for (Item i:currentRoom.items()) { //a for each loop, since the room's items are kept in a list, but this gives a //compiler error, it doesn't work because items is an ArrayList, but I need a way to pick up the item. I thought that if //given the item's name, I could run a check through the room's ArrayList of items via a for-each loop
if (a==i.getName()) {
removeItem (i);
return;
* allows a player to drop an item in the room
* @param command
private void drop(Command command) {
if(command.hasSecondWord()) {
System.out.println("drop what?");
return;
//add item method is suppose to be used here
* "Quit" was entered. Check the rest of the command to see
* whether we really quit the game.
* @param command The command entered.
* @return true, if this command quits the game, false otherwise.
private boolean quit(Command command)
if(command.hasSecondWord()) {
System.out.println("Quit what?");
return false;
else {
return true; // signal that we want to quit
}class Room
import java.util.*;
* Class Room - a room in an adventure game.
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* A "Room" represents one location in the scenery of the game. It is
* connected to other rooms via exits. For each existing exit, the room
* stores a reference to the neighboring room.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.03 October 25, 2007
public class Room
private String description;
private HashMap<String, Room> exits; // stores exits of this room.
// The items in the room
private ArrayList<Item> items;
* Create a room described "description". Initially, it has
* no exits. "description" is something like "a kitchen" or
* "an open court yard".
* @param description The room's description.
public Room(String description)
this.description = description;
exits = new HashMap<String, Room>();
items = new ArrayList<Item>();
* Define an exit from this room.
* @param direction The direction of the exit.
* @param neighbor The room to which the exit leads.
public void setExit(String direction, Room neighbor)
exits.put(direction, neighbor);
* Gives a short description of the room.
* @return The short description of the room
* (the one that was defined in the constructor).
public String getShortDescription()
return description;
* Return a description of the items in the room
* (Note that this could be combined with getLongDescription, but
* this way shows better cohesion, and could avoid code duplication
* for future enhancements.)
* @return A description of the items in this room
public String getItemsDescription()
String s = new String();
if (items.size()==0)
s += "There are no items in this room.\n";
else {
s += "The item(s) in the room are:\n";
for (Item item : items ) {
s += item.getInfo() + "\n";
return s;
* Return a description of the room in the form:
* You are in the kitchen.
* Exits: north west
* and information on the items in the room
* @return A long description of this room
public String getLongDescription()
String s = "You are " + description + ".\n" + getExitString() + "\n";
s += getItemsDescription();
return s;
* Return a string describing the room's exits, for example
* "Exits: north west".
* @return Details of the room's exits.
private String getExitString()
String returnString = "Exits:";
Set<String> keys = exits.keySet();
for(String exit : keys) {
returnString += " " + exit;
return returnString;
* Return the room that is reached if we go from this room in direction
* "direction". If there is no room in that direction, return null.
* @param direction The exit's direction.
* @return The room in the given direction.
public Room getExit(String direction)
return exits.get(direction);
* Adds the given item to the room.
* @param item The item to be added
public void addItem(Item item)
items.add(item);
* Removes an item if the person picks it up
* @param item the item to be removed
public void removeItem (Item item)
items.remove(item);
}class Item
* This represents an item in a room in zuul.
* @author L.S. Marshall
* @version 1.00 October 9, 2007
public class Item
// The description of the item
private String description;
// The weight of the item
private double weight;
private String name;
* Constructor for objects of class Item
* @param desc description of the item
* @param weight the weight of the item
public Item(String name, String desc, double weight)
description = desc;
this.weight = weight;
this.name=name;
* Returns a string representing this item
* @return string representing this item
public String getInfo()
return ("Item: " + description + ", weighs " + weight + ".");
* returns the name of the string
* @ return the name in a string
public String getName()
return ( name );
}class Command
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* This class holds information about a command that was issued by the user.
* A command currently consists of two strings: a command word and a second
* word (for example, if the command was "take map", then the two strings
* obviously are "take" and "map").
* The way this is used is: Commands are already checked for being valid
* command words. If the user entered an invalid command (a word that is not
* known) then the command word is <null>.
* If the command had only one word, then the second word is <null>.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
public class Command
private String commandWord;
private String secondWord;
* Create a command object. First and second word must be supplied, but
* either one (or both) can be null.
* @param firstWord The first word of the command. Null if the command
* was not recognised.
* @param secondWord The second word of the command.
public Command(String firstWord, String secondWord)
commandWord = firstWord;
this.secondWord = secondWord;
* Return the command word (the first word) of this command. If the
* command was not understood, the result is null.
* @return The command word.
public String getCommandWord()
return commandWord;
* @return The second word of this command. Returns null if there was no
* second word.
public String getSecondWord()
return secondWord;
* @return true if this command was not understood.
public boolean isUnknown()
return (commandWord == null);
* @return true if the command has a second word.
public boolean hasSecondWord()
return (secondWord != null);
}class Parser
import java.util.Scanner;
import java.util.StringTokenizer;
//I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
//Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
//yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
//Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
//it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class Parser
private CommandWords commands; // holds all valid command words
private Scanner reader; // source of command input
* Create a parser to read from the terminal window.
public Parser()
commands = new CommandWords();
reader = new Scanner(System.in);
* Command returns the command typed by the user.
* @return The next command from the user.
public Command getCommand()
String inputLine; // will hold the full input line
String word1 = null;
String word2 = null;
System.out.print("> "); // print prompt
inputLine = reader.nextLine();
// Find up to two words on the line.
Scanner tokenizer = new Scanner(inputLine);
if(tokenizer.hasNext()) {
word1 = tokenizer.next(); // get first word
if(tokenizer.hasNext()) {
word2 = tokenizer.next(); // get second word
// note: we just ignore the rest of the input line.
// Now check whether this word is known. If so, create a command
// with it. If not, create a "null" command (for unknown command).
if(commands.isCommand(word1)) {
return new Command(word1, word2);
else {
return new Command(null, word2);
* Returns a list of valid command words.
* @string list of valid command words
public String getCommands()
return commands.getCommandList();
}class CommandWords
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* This class holds an enumeration of all command words known to the game.
* It is used to recognise commands as they are typed in.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class CommandWords
// a constant array that holds all valid command words
private static final String[] validCommands = {
"go", "quit", "help", "look", "eat", "back", "stackBack",
"take", "drop",
* Constructor - initialise the command words.
public CommandWords()
// nothing to do at the moment...
* Check whether a given String is a valid command word.
* @param aString the command word
* @return true if it is, false if it isn't.
public boolean isCommand(String aString)
for(int i = 0; i < validCommands.length; i++) {
if(validCommands.equals(aString))
return true;
// if we get here, the string was not found in the commands
return false;
* Return a string containing all valid commands.
* @return string of all valid commands
public String getCommandList()
String s="";
for(String command: validCommands) {
s += command + " ";
return s;
right, sorry, that was thoughtless of me.
class Parser
import java.util.Scanner;
import java.util.StringTokenizer;
//I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
//Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
//yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
//Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
//it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class Parser
private CommandWords commands; // holds all valid command words
private Scanner reader; // source of command input
* Create a parser to read from the terminal window.
public Parser()
commands = new CommandWords();
reader = new Scanner(System.in);
* Command returns the command typed by the user.
* @return The next command from the user.
public Command getCommand()
String inputLine; // will hold the full input line
String word1 = null;
String word2 = null;
System.out.print("> "); // print prompt
inputLine = reader.nextLine();
// Find up to two words on the line.
Scanner tokenizer = new Scanner(inputLine);
if(tokenizer.hasNext()) {
word1 = tokenizer.next(); // get first word
if(tokenizer.hasNext()) {
word2 = tokenizer.next(); // get second word
// note: we just ignore the rest of the input line.
// Now check whether this word is known. If so, create a command
// with it. If not, create a "null" command (for unknown command).
if(commands.isCommand(word1)) {
return new Command(word1, word2);
else {
return new Command(null, word2);
* Returns a list of valid command words.
* @string list of valid command words
public String getCommands()
return commands.getCommandList();
} -
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. -
Need Help with complex query and computing values
I have an issue trying to combine data from several tables. I need help trying to compute the "Total Hours", "Max Pressure" ,"Average Pressure" while displaying the "Manufacturer",
"Part Type" , "Serial Number", "District", "Status","Truck Type",and "truck number" for a certain Part on all Trucks. I need to be able check and see if the serial number was on
a particular job and calculate the hours of that serial number if it was on that job and the jobdate falls between the install date and removal date. Ive tried but keep getting either
repeating rows, total hrs of the truck instead of the serial number. Ive considered doing a pivot to display it but have been having trouble putting it together.
table 1
(*records of parts*)
Contains serial number,truck number, part type, part number, install date, removal date, status
table 2
(*records of Jobs*)
contains Jobnumber, JobStartdate, Max pressure, average pressure, and Totalhrs
table 3
(records related to jobs and trucks)
contains jobnumber, district , and truck numbers
Table 4
(records of manufacturers and part numbers)
contains partnumber, manufacturer name, and truck type
I would like to get it to show like below
SerialNo PrtType
MFG TruckNo
TrkType TtlHrs
MaxPr AvgPr
Status
Dst
AB345 1200series
NGK 2G34
Boss X 400 10,000
9500 NonOp
NE
Thanks in advanceHope this helps
Note: (Date of Mar 1 2014 was just extended to a further date so the system would know that its still operating when calculating current hours)
Table 1
SerialNo TruckNo InstallDate RemovalDate Status PartNo PartType
BJ1002 F917 2013-09-17 2014-03-01 Oper L871235 BJ 3000 GL
CWS1002 F104 2012-11-21 2013-03-29 NonOper L76088-450 CWS 2000
CWS1003 F104 2013-04-24 2013-08-01 NonOper L76088-450 CWS 2000
CWS1005 F187 2012-11-21 2013-04-04 NonOper L76088-450 CWS 2000
CWS1006 F187 2013-04-24 2013-06-30 NonOper L76088-450 CWS 2000
CWS1007 F187 2013-06-30 2013-03-01 Oper L76088-450 CWS 2000
CWS1009 2F60 2013-05-05 2013-03-01 Oper L76088-450 CWS 2000
CWS1011 F809 2013-05-28 2013-08-28 NonOper L76088-400 CWS 2000
CWS1013 F990 2013-06-11 2013-10-29 NonOper L76088-450 CWS 2000
CWS1015 F783 2013-06-28 2013-03-01 Oper L76088-450 CWS 2000
Table 2
JobNumber Date District PrAvTreat PrMaxTr TotalHrs
553811287 2012-01-19 Fairmount 7337 8319 1.53
652110088 2012-08-20 San Antonio 6340 7075 0.47
652110090 2012-08-21 San Antonio 6134 7131 0.62
652110091 2012-08-22 San Antonio 6180 2950 0.58
652110092 2012-08-23 San Antonio 5959 6789 0.64
652110093 2012-08-23 San Antonio 6165 7466 0.62
Table 3
TruckNo District JobNumber
1F01 Odessa 10011012329
1F01 Odessa 10011012333
1F01 Odessa 10011014831
1F01 Odessa 10011014834
1F01 Odessa 10011012332
1F01 Odessa 10011012328
1F01 Odessa 10011014829
Table 4
PartNumber Manufacturer TruckType
L322020-2 Jimmy Dean Ford T
L322738-2 Lucas Ford T
L47869-1 Jimmy Dean Ford T
L76070-650 NGK Ford T
Sam Howard
Maybe you are looking for
-
According to our records, this serial number is registered to another Apple ID.
I bought an iMac from an ARC thrift store that had been donated. When I try to register the iMac to my AppleID to see if there's any Applecare left I get the message "According to our records, this serial number is registered to another Apple ID."
-
How do I stretch (or compress) the viewing time of a video clip in Elements 12?
How do I stretch (or compress) the viewing time of a video clip in Elements 12?
-
I just installed the new Itunes 7.3. After it successfully installed and Itunes automatically started, i noticed that order of artists is now completely messed up. the list now starts with a-z, then to numbers, where before it went numbers-english ch
-
i tried paying by the same means last time and it did the same again,but managed a payment then but today i had to telephone them,but need to pay online in future could you please help me sort this out,thank you m j wilson.
-
How to authorize computer to itunes
I am having trouble with my itunes, it's not allowing me to play my music. It says computer not authorized.