Need help with generic class with comparable type
Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
I cant get the code to compile which I have written.
I get the error: OBTComparable.java uses unchecked or unsafe operations
this is the more detailed information of the error when I compile with -Xlint:unchecked
OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
a member of the raw type OBTComparable
left.insert(insertValue);
^
OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
a member of the raw type OBTComparable
right.insert(insertValue);
^
OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
member of the raw type OBTComparable
return left.find(findValue);
^
OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
member of the raw type OBTComparable
return right.find(findValue);
^
and here is my code for the class
public class OBTComparable<OBTType extends Comparable<OBTType>>
// A tree is either empty or not
private boolean empty;
// If the tree is not empty then it has
// a value, a left and a right.
// These are not used it empty == true
private OBTType value;
private OBTComparable left;
private OBTComparable right;
// Create an empty tree.
public OBTComparable()
setEmpty();
} // OBTComparable
// Make this tree into an empty tree.
private void setEmpty()
empty = true;
value = null; // arbitrary
left = null;
right = null;
} // setEmpty
// See if this is an empty (Sub)tree.
public boolean isEmpty()
{ return empty; }
// Get the value which is here.
public OBTType getValue()
{ return value; }
// Get the left sub-tree.
public OBTComparable getLeft()
{ return left; }
// Get the right sub-tree.
public OBTComparable getRight()
{ return right; }
// Store a value at this position in the tree.
private void setValue(OBTType requiredValue)
if (empty)
empty = false;
left = new OBTComparable<OBTType>(); // Makes a new empty tree.
right = new OBTComparable<OBTType>(); // Makes a new empty tree.
} // if
value = requiredValue;
} // setValue
// Insert a value, allowing multiple instances.
public void insert(OBTType insertValue)
if (empty)
setValue(insertValue);
else if (insertValue.compareTo(value) < 0)
left.insert(insertValue);
else
right.insert(insertValue);
} // insert
// Find a value
public boolean find(OBTType findValue)
if (empty)
return false;
else if (findValue.equals(value))
return true;
else if (findValue.compareTo(value) < 0)
return left.find(findValue);
else
return right.find(findValue);
} // find
} // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
If anyone can help me with my problem that would be great!
Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
Thanks in advance
David
I have good news and undecided news.
First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.
Similar Messages
-
Need Help with data type conversion
Hello People,
I am new to java, i need some help with data type conversion:
I have variable(string) storing IP Address
IPAddr="10.10.103.10"
I have to call a library function which passes IP Address and does something and returns me a value.
The problem I have is that external function call in this library excepts IP Address in form of a byte array.
Here is the syntax for the function I am calling through my program
int createDevice (byte[] ipAddress).
now my problem is I don't know how to convert the string IPAddr variable into a byte[] ipAddress to pass it through method.Class InetAddress has a method
byte[] getAddress() You can create an instance using the static method getByName() providing the IP address string as argument. -
Need help with DOC type web service
hi,
I am trying to write a simple message style ( doc type ) web service but no success so far. I have tried to search for examples but no use. I already implemented some simple RPC style web services like calculator etc and able to use them. I am more interested in the DOC type ( which sends SOAP message and receives SOAP message back). Can Anybody give me an example for implementing this type of service ( very-simple say HellowWorld ) or point me to some website . I am not able to generate the response envelope. I can write the client program which will send a SOAP Envelope to this services with one parameter NAME and the services should return Hello Name but in a SOAP envelope form. I can create a SOAP message in this Client using SOAPConnection and MessageFactory etc. Your help will be really appreciated. There is very little stuff about webservices on the internet as well on this forum.
Thanks
VinodHello kwilding2,
Thanks for the quick response and pointing to some useful websites. I downloaded the code from web service essentials BUT all the examples are using SOAP RPC calls. They create a call object and call one of the service methods and a response is returned. I am little confused about this stuff. I am looking for something which returns the response in a SOAP envelope for which i think i need to use JAXM API which I already have downloaded. I have created a client which composes a SOAP envelope using SOAPConnection and other MessageFactory classes etc and can send this SOAP envelope to a web service. In return I want the web service to give the SOAP envelope.
I have gone thru xmethods.net and picked the following stock quote request and response:
Sample Request envelope:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<ns1:getQuote xmlns:ns1="urn:xmethods-delayed-quotes" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<symbol xsi:type="xsd:string">IBM</symbol>
</ns1:getQuote>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Sample Response Envelope:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<ns1:getQuoteResponse xmlns:ns1="urn:xmethods-delayed-quotes" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<return xsi:type="xsd:float">133.625</return>
</ns1:getQuoteResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I also want the things in this order. This webservice at xmethods just returns the price for a stock, so how they say it returns this Response Envelope. Is this Envelope something implied. I am getting more confused.
any help will be appreciated.
Thanks
Vinod -
Need help with output type EDI for ERS
All,
I want to be able to run and ERS settlement and have the invoices created sent via EDI/XML to the supplier. I have several questions on the set up.
1) I have output type ERS6 which is defined as ERS EDI. I assume because it does not start with Z* this is SAP standard, so I shouldn't have to modify any of this.
2) I've added my supplier to this output type.
3) I assume I need to create a partner profile for this supplier? If so can someone tell me the message type to use?
Is there any set up I'm missing in this process? I've executed ERS but do not get an idoc and I'm fairly certain it's because I haven't done the partner profile set-up.
Thanks for your help.
SandraHi,
You don't have to modify thise setup unless you have any customized requirement.
You are missing partner profile setup.Carry out the setup and run MRRL tcode to create the idocs
Enter the following values using tcode WE20.
Field Value
Message type GSVERF
Partner type LI (vendor)
Partner function LF (vendor)
Port SUBSYSTEM ( Port to your middleware)
Output mode such as Collect IDocs
Basic type GSVERF01
Application MR
Output type ERS6 or the type you have defined
Regards,
Karuna -
Need help with comparing Query data
See Attached query
I need to only show Sales Employee Name that does NOT match Email
Example: Sales Employee Name KSLM-130
E-Mail does NOT start with the same KSLM-130 @ XXX.com
In other words need to report on unmatched Sales Employee Name to Email Name.
Thank you!Hi!
Try this. It might work for you.
SELECT
T0.[CardCode], T0.[CardName], T2.[SlpCode], T1.[Name], T1.[E_MailL], T2.[SlpName]
FROM OCRD T0
INNER JOIN OCPR T1 ON T0.CardCode = T1.CardCode
INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode
WHERE LEFT(T1.[E_MailL],LEN(T2.[SlpName])) <> T2.[SlpName]
Regards, -
Need help with FLV type SWF playback in flash movie
Hi,
I have three external SWF files from a client without FLA
sources. The SWFs were done 3 years ago by someone else so there is
no way to modify the existing SWF files. These contain no
interactivity but may involve nested clips on the main timeline.
They are AS1 or AS2 files so they need to be done with AS2
scripting to keep it simple.
I need to call these SWF files inside another flash movie and
play them in a player window as if they were video files with
play/pause, seekbar and volume controls. The needed functionality
is similar to FLV players. My controls will use custom graphic
buttons and sliders mimicking the look of CNN video player window.
Does anyone know a good tutorial on how to script these
controls for SWF?
Most likely I think I will load it in a clip and I am
thinking that I will need to get the duration of the loaded swf in
order to set up the seekbar.
Thanks in advance,
AttilaI think your professor, or somebody, gave you directions with ActionScript 2 programming. In AS2, what oyu have here would have worked just fine. But, in AS3, you need to use a fairly different approach. Your buttons, and their instance name, can remain the same. But now, in AS3, you have to add event listeners in the following manner:
yourButtonName.addEventListener(MouseEvent.CLICK, yourListenerFunction);
In your case, you can do one of two things - A) assign a unique listener function to each button, or B) assign the same listsner to both functions:
A)
start_btn.addEventListener(MouseEvent.CLICK, startPolygon);
stop_btn.addEventListener(MouseEvent.CLICK, stopPolygon);
function startPolygon(e:MouseEvent):void{
polygon.play();
function stopPolygon(e:MouseEvent):void{
polygon.stop();
B)
start_btn.addEventListener(MouseEvent.CLICK, controlPolygon);
stop_btn.addEventListener(MouseEvent.CLICK, controlPolygon);
function controlPolygon(e:MouseEvent):void{
if (e.target.name == "start_btn") {//Test for the name of the object that dispatched the CLICK event
polygon.play();
} else if (e.target.name == "stop_btn") {
polygon.stop();
When I'm using several buttons that do the same/nearly similar things, I favor approach B over A, as it keeps me to jsut one single function to deal with. -
NEED HELP WITH CHOPPY TYPE AFTER BURNED TO DVD
I have about 20 jpgs (RGB) of just copy on a black background. I've brought those jpgs into iMovie HD and they look fine.
When I render those jpgs as a movie (basically a slideshow) to a DVD and play it back on your average television...each slide of copy on a black background, comes out horrible. Grainy, pixelated, and out of focus.
Please, I need to know if there is anything anyone has tried and had work. I feel that I've exhausted quite a few methods for executing the problem...but still nothing better.
G5 Mac OS X (10.4.9)I don't think the problem is happening in the
"burning" of the DVD, it is happening right when I am
previewing. I can see that the text I have currently
up on screen looks great, it's fine, nothing is wrong
with the copy. But as soon as I view it before I put
it to disc, it becomes completely distorted and
choppy. Like I've imported a low res file to begin
with or something.
The preview function in iDVD should be though of as a 'for position only' function. It DOES NOT represent how the final mpg-2 compressed DVD will look.
Preparing images for DVD slideshows at http://docs.info.apple.com/article.html?path=iDVD/6.0/en/17.html will give you some recommendations on image sizes to use.
F Shippey -
Need help with comparing cursor row to a collection
I have been racking my brain trying to get get the code below to work properly. I am loading a table via bulk collect into a collection. I want to run code that tells me if the value of batch_REC.co_id exists or not in co.id collection. The best I have is below. The compiler does not like the MEMBER statement, and I do not know why. I am running 9i if that makes a difference. Any pointers would be extremely helpfull. Thank you.
Allan Richards
Washington, D.C.
--Initiate Procedure
procedure Check_Company_ID (Batches_cv_in IN refgas.batchCurTyp, truth boolean default null) is
--DECLARATIONs
TYPE CO_ID_Array IS TABLE OF NUMBER ;
Batch_REC t_batch%ROWTYPE;
number_check EXCEPTION;
PRAGMA EXCEPTION_INIT(number_check,-6502);
answer boolean;
co_id CO_ID_Array;
c NUMBER;
--Begin Code
BEGIN
dbms_output.put_line('-----');
dbms_output.put_line('Here is the data from the result set:');
--Setup Truth Output
IF truth IS NOT NULL THEN
dbms_output.put_line(CASE truth WHEN TRUE THEN 'True' WHEN FALSE THEN 'False' END);
END IF;
--Select T_COMPANY.COMPANY_ID into a collection
select t_company.COMPANY_ID
bulk collect into co_id
from t_company;
--Loop through the Cursor
LOOP
FETCH Batches_cv_in INTO Batch_REC;
EXIT WHEN Batches_cv_in%NOTFOUND;
--Check each co_id per loop for existance in t_company
BEGIN
--To detect if an entry is not a compliant number
c := to_number(Batch_REC.co_id);
--Checking each number as existing
answer := c MEMBER OF co_id;
check_company_id(truth => anwser);
--Setup for error catching
EXCEPTION
When number_check
Then
dbms_output.put_line('Company ID has invalid Characters! ' || Batch_REC.co_id ||' '|| Batch_REC.facility_id ||' '|| Batch_REC.batch_id||' '|| Batch_REC.report_date);
end;
END LOOP;
--Output Total Number of Records in Collection
dbms_output.put_line('Number of Records: ' || co_id.COUNT);
--Give "All Good" Statement if all records compare properly
IF co_id IS NULL THEN
dbms_output.put_line('All Company IDs are Good');
end if ;
end;I guess what I looking for then is a work around for 9i. Don't know if you're still watching this thread but you may be interested in this code from Steven Feuerstein (Whom God Preserve).
Cheers, APC -
I need help with comparing Objects of an ArrayList
Hi,
I am trying to compare a certain variable of objects which are stored in an arrayList.
for example i have a class called AuctionBid(String bidderID, BitSet itemSet, int bidValue)
and i have another class called AuctionBidFactory which creates AuctionBid objects and stores them into an arrayList
I have another Gui class which acts as a user interface where the user can create bids but then i want to compare the itemSet of the AuctionBid which is created by the user to the itemSets of the AuctionBid objects which already exist in the arrayList and if that itemSet does not exist in the arraylist then will add the new AuctionBid to the arrayList.
I have the following method in the AuctionBidFactory which is supposed to compare the itemSets of the AuctionBids in the arrayList and it does not work:
public boolean containsItem(AuctionBid auctionBid) {
if (auctionBids.contains(auctionBid.itemSet)) {
return true;
return false;
where auctionBids is the arrayList where the AuctionBid objects are stored
I hope the information above is enough to see where the problem is.
many thanksAmit, unfortunately I dont have a different object for the user bids. Basically I just have the AuctionBid(String bidder,BitSet items, int value) and the reason why im using bitSet is that im modelling a combinatorial auction where the bidder can bid on combination of items.
now when the user puts a bid that bid is added to an arrayList of ArrayList<AuctionBid>
then once all the bidings have finished i want to create autoBids for those single items only for which there are no bids. so for example lets say there are 6 items for auction and if there are the following bids in the arrayList:
AuctionBid(bidder1,{1},5)
AuctionBid(bidder2,{5},8)
i want to create autobids as follow:
AuctionBid(autoBid,{0},0)
AuctionBid(autoBid,{2},0)
AuctionBid(autoBid,{3},0)
AuctionBid(autoBid,{4},0)
and then i want to add these created bids to the same arrayList where all the bids are.
but if I use the arrayList.contains() method it will compare the whole objects to each other rather than just comparing the bitSets(items) in each bid.
so i dont know whether i can still do this without overriding the equals() method in the AuctionBid class or not
regards
Arneh -
Need help with specifying type range in dynamic text box
is it possible to specify my type range in a dynamic text box
that is loading images as well as type? Everytime i specify the
range flash quits. if i take out the image loading actionscript
then it's fine. grrrrrI assume that you have added this field to the field catalog, so make sure that the name in the field catalog is exactly the same as in the internal table which holds your data, and make sure that you are filling the field name as uppercase.
Regards,
RIch Heilman -
I have written a java program using jdk1.5. After completing my program I noticed that the compiler was outputting a warning. It tells me that there were a few unsafe operations in my code. Anyway I found out that my code needed to include generics. I was able to figure out how too include some of the generics. I am having trouble with the following:
[javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:105: warning: [unchecked] unchecked conversion
[javac] found : personalInfo.logic.FNComparator
[javac] required: java.util.Comparator<? super java.lang.Object>
[javac] Arrays.sort(sort, fn);
[javac] ^
[javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:105: warning: [unchecked] unchecked method invocation: <T>sort(T[],java.util.Comparator<? super T>) in java.util.Arrays is applied to (java.lang.Object[],personalInfo.logic.FNComparator)
[javac] Arrays.sort(sort, fn);
[javac] ^
[javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:109: warning: [unchecked] unchecked conversion
[javac] found : personalInfo.logic.LNComparator
[javac] required: java.util.Comparator<? super java.lang.Object>
[javac] Arrays.sort(sort, ln);
[javac] ^
[javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:109: warning: [unchecked] unchecked method invocation: <T>sort(T[],java.util.Comparator<? super T>) in java.util.Arrays is applied to (java.lang.Object[],personalInfo.logic.LNComparator)
[javac] Arrays.sort(sort, ln);
[javac] ^
The FN/LNComparator class implements the java.util.Comparator class. I have looked at the generics tutorial on the java.sun.com website. I can't figure out what I replace the <T> with to make the code compile and the warning to go away. I have tried <Comparator> but that just gives me an error that says FNComparator does not take any parameters.
If anyone knows how to fix these warnings let me know
-HockeyfanI know how to fix it.
Step 1. Stop writing subject-lines like "Need help with generics". Everyone who starts a topic needs help, that's why people post here!
Step 2. Don't just post the error message, post the relevant code. In [code ][code ] tags of course.
Step 3. Stop watching hockey, it'll stunt your growth
Step 4. Have the FN/LNComparator implement, not the raw Comparator, but Comparator<Object> -
<p>Need help with the following error.....what does it mean....</p><p>28943 3086739136 XML-240304 3/7/07 7:13:23 PM |SessionNew_Job1<br /><font color="#ff0000">28943 3086739136 XML-240304 3/7/07 7:13:23 PM XML parser failed: Error <An exception occurred! Type:UnexpectedEOFException, Message:The end of input was not expected> at</font><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM line <7>, char <8> in <<?xml version="1.0" encoding="WINDOWS-1252" ?><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <DSConfigurations><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <DSConfiguration default="true" name="Configuration1"><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <case_sensitive>no</case_sensitive><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <database_type>Oracle</database_type><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <db_alias_name1>ODS_OWNER</db_alias_name1><br />28943 3086739136 XML-240304 3/7/07 7:13:23 PM <db_ali>, file <>.<br />28943 3086739136 XML-240307 3/7/07 7:13:23 PM |SessionNew_Job1<br />28943 3086739136 XML-240307 3/7/07 7:13:23 PM XML parser failed: See previously displayed error message.</p><p>Any help would be greatly appreciated. It's something to do with my datasource and possibly the codepage but I'm really not sure.</p><p>-m<br /></p>
please export your datastore as ATL and send it to support. Somehow the internal language around configurations got corrupted - never seen before.
-
FormsCentral retiring in July???!!! Are you freaking kidding me? My clients use this feature all the time. What do you suggest I do now? What service do I go with that is comparable to it? I need help with this asap!
I would suggest checking out http://www.logiforms.com. They have really good PDF support for both hosted PDF's and generating PDFs. You can:
populate PDF forms from a web form submission
Merge multiple PDF's together using conditional logic
Include uploaded images in the generated PDF
Get Electronic signatures on PDF's
Use conditional logic when creating PDF's
Convert HTML to PDF. You design in HTML and CSS and use form field wildcards and generate the PDF
More of the PDF features are explained here:
PDF Form Creator | PDF Form Maker | V3.Logiforms.com
They are also offering a 25% discount to anyone coming from Forms Central... -
I''ve just started out with Java and I need help with my latest program.
The program looks someting like this:
public class MultiServer {
public static void main(Straing[] args) {
ServerGUI GUI = new ServerGUI();
public class ServerGUI extends JFrame implements ActionListener {
private TextArea textArea;
public ServerGUI() {
//setting up the JFrame and stuff like that
public void actionPerformed(ActionEvent event) {
if(button == addButton) {
addGUI add = new addGUI();
public class addGUI extends JFrame implements ActionListener {
private TextField t1 = new TextField(25);
public addGUI() {
//setting up the JFrame and stuff like that
public void actionPerformed(ActionEvent event) {
if(button == printButton) {
textArea.append("THIS DOES NOT WORK!");
} The problem is as follows: I want to be able to write text in the textArea in class ServerGUI from the class addGUI, but I can't. I hope you understand what I mean.
How is this fixed? Please help me!public void actionPerformed(ActionEvent event) {
if(button == addButton) {
addGUI add = new addGUI(textArea);
public class addGUI extends JFrame implements ActionListener {
private TextArea textArea;
public addGUI(TextArea textArea) {
this.textArea = textArea;
}/Kaj -
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 Template - unbalanced #EndEditable tag
I am unable to use this template to create a new page and get the "unbalanced #EndEditable tag" error.
If I open the file independently it looks great - otherwise I get the error.
Code for internal_students.dwt
There is an error at line 45, column 79 (absolute position 2188)
<div id="metanav"><!-- #BeginLibraryItem "/Library/metaNav.lbi" -->
<p><a href="../Library/contact/index.html">Contact Us</a></p>
<!-- #EndLibraryItem --></div>
<div id="navigation">
<div id="navigation_l">
<div id="navigation_r"><!-- #BeginLibraryItem "/Library/mainNav.lbi" --> <ul>
<li><a href="../index.html" class="first"><img src="../images/spacer.gif" alt="CAITE Homepage" width="75" height="20" border="0" /></a></li>
<li><a href="../about/index.html">About</a></li>
<li><a href="../news/index.html">News And Events</a></li>
<li><a href="../educators/index.html">For Educators</a></li>
<li><a href="../students/index.html">For Students</a></li>
<li><a href="../industry/index.html" class="last">For Industry</a></li>
</ul>
<!-- #EndLibraryItem --></div>
I need help with this as the site and templates were created 2/3 years before I arrived on the job.
Thank you
CherylOkay
- This is on-line page http://caite.cs.umass.edu/students/index.html
If you want code from template here it is:
<!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"><!-- InstanceBegin template="/Templates/internal_about.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<!-- InstanceBeginEditable name="doctitle" -->
<title>CAITE - Commonwealth Alliance for Information Technology Education</title>
<!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="head" -->
<meta name="Description" content="Commonwealth Alliance for Information Technology Education (CAITE) to design and carry out comprehensive programs that address under representation in information technology (IT) education and the workforce. CAITE will focus on women and minorities in groups that are underrepresented in the Massachusetts innovation economy" />
<meta name="Keywords" content="Commonwealth Alliance for Information Technology Education CAITE Massachusetts women minorities information technology IT" />
<meta name="robots" content="all, index, follow" />
<meta name="revisit-after" content="14 days" />
<meta name="author" content="Outreach Web Team" />
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable --><!-- InstanceEndEditable -->
<link rel="shortcut icon" href="/images/favicon.ico" />
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript" src="../scripts/jquery.easing.js"></script>
<script type="text/javascript" src="../scripts/jquery.pngfix.js"></script>
<script language="JavaScript" type="text/JavaScript">
<!--
$(document).ready(function() {
$("img[@src$=png], div#wrapper_l, div#wrapper_r, div#whatsnew").pngfix();
//-->
</script>
<link href="../css/screenstyle.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/printstyle.css" rel="stylesheet" type="text/css" media="print" />
</head>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<body>
<div id="wrapper">
<div id="metanav"><!-- #BeginLibraryItem "/Library/metaNav.lbi" -->
<p><a href="../Library/contact/index.html">Contact Us</a></p>
<!-- #EndLibraryItem --></div>
<div id="navigation">
<div id="navigation_l">
<div id="navigation_r"><!-- #BeginLibraryItem "/Library/mainNav.lbi" --> <ul>
<li><a href="../index.html" class="first"><img src="../images/spacer.gif" alt="CAITE Homepage" width="75" height="20" border="0" /></a></li>
<li><a href="../about/index.html">About</a></li>
<li><a href="../news/index.html">News And Events</a></li>
<li><a href="../educators/index.html">For Educators</a></li>
<li><a href="../students/index.html">For Students</a></li>
<li><a href="../industry/index.html" class="last">For Industry</a></li>
</ul>
<!-- #EndLibraryItem --></div>
<!-- end navigation right -->
</div><!-- end navigation left -->
</div><!-- end navigation -->
<div id="wrapper_l">
<div id="wrapper_r">
<div id="innerwrapper">
<div id="internalBanner-print"> <h1>Commonwealth Alliance for Information Technology Education (CAITE)</h1></div>
<div id="internalBanner"><!-- InstanceBeginEditable name="internalBanner" -->
<div class="students-banner">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="125" height="188" align="left" valign="top" id="homeImage"><img src="../images/logo_vertical_small.png" alt="CAITE" width="105" height="188" /></td>
<td align="left" valign="top" id="internal-banner-quote"><div id="internalQuote">
<div id="internalQuote-inner">
<p>CAITE designs and carrys out comprehensive programs that address under-representation in information technology (IT).</p>
</div>
</div></td>
</tr>
</table>
</div>
<!-- InstanceEndEditable --></div> <!-- end banner -->
<div id="internalContent">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="317" align="left" valign="top" id="secondary-content">
<!-- InstanceBeginEditable name="SecondaryNav" --><!-- #BeginLibraryItem "/Library/studentNav.lbi" -->
<h3><a href="../students/index.html">For Students</a></h3>
<div id="secondaryNav">
<ul>
<li><a href="http://www.takeITgoanywhere.org" target="_blank">TakeITgoanywhere.org</a></li>
</ul>
</div><!-- #EndLibraryItem --><!-- InstanceEndEditable -->
</td>
<td align="left" valign="top" id="contentCell"><!-- InstanceBeginEditable name="mainContent" -->
<h1>For Students</h1>
<p>The University of Massachusetts Amherst is leading a Commonwealth Alliance for Information Technology Education (CAITE) to design and carry out comprehensive programs that address under representation in information technology (IT) education and the workforce. CAITE will focus on women and minorities in groups that are underrepresented in the Massachusetts innovation economy; that is, economically, academically, and socially disadvantaged residents.</p>
<p>The project will pilot a series of outreach programs supported by educational pathways in three regions (one rural, one suburban, and one urban). The project will include work with high school teachers, staff, and counselors. CAITE will identify best practices and disseminate, deploy, extend and institutionalize these best practices statewide and nationally.</p>
<p>Community colleges are the centerpiece of CAITE because of the central role they play in reaching out to underserved populations and in serving as a gateway to careers and further higher education.</p>
<p>This project will build a broad alliance built on its leadership in and partnership with the Commonwealth Information Technology Initiative (CITI), the Boston Area Advanced Technological Education Center (BATEC), regional Louis Stokes Alliances and NSF EGEP programs, and other partnerships and initiatives focused on information technology education and STEM pipeline issues</p>
<p> </p>
<!-- InstanceEndEditable --></td>
</tr>
</table>
</div>
<div id="alliances">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="30" align="left" valign="top"><h2><a href="../about/alliances.html">Alliances</a></h2></td>
</tr>
<tr>
<td align="center" valign="middle"><!-- #BeginLibraryItem "/Library/AllianceTable.lbi" --><p>
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td width="35" align="center" valign="middle"> </td>
<td align="center" valign="middle"><a href="http://www.citi.mass.edu/" target="_blank"><img src="../images/logo_citi.jpg" alt="Citi" width="65" height="50" border="0 /"></a></td>
<td align="center" valign="middle"><a href="http://www.batec.org/index.php" target="_blank"><img src="../images/logo_batec.jpg" alt="BATEC" width="69" height="46" border="0" /></a></td>
<td align="center" valign="middle"><a href="http://www.nsf.gov/index.jsp" target="_blank"><img src="../images/nsflogo.gif" alt="NSF" width="64" height="65" border="0" ></a></td>
<td align="center" valign="middle"><a href="http://www.nelsamp.neu.edu/" target="_blank"><img src="../images/nelsamplogo.gif" width="100" border="0"></a></td>
<td align="center" valign="middle"><p><a href="http://mysite.verizon.net/milnerm/" target="_blank"><img src="../images/umlsamp.png" width="85" height="63" border="0"></a></p> </td>
<td align="center" valign="middle"><a href="http://www.neagep.org/index.asp" target="_blank"><img src="../images/nealogo.gif" border="0" ></a></td>
</tr>
</table>
<!-- #EndLibraryItem --></td>
</tr>
</table>
</div>
</div> <!-- end inner wrapper -->
</div><!-- end wrapper right -->
</div><!-- end wrapper left -->
<div id="bottom">
<div id="bottom_l">
<div id="bottom_r"> </div><!-- end bottom right -->
</div><!-- end bottom left -->
</div> <!-- end bottom -->
</div><!-- end wrapper -->
<div id="copyright"><!-- #BeginLibraryItem "/Library/copyright.lbi" -->
<p>Sponsored by CAITE an NSF CISE Broadening Participation in Computing Alliance<br />
© copyright 2008 <a href="http://www.umass.edu/" target="_blank">University of Massachusetts, Amherst</a></p>
<font color="#666666"><br>
</font>
<p><font color="#666666" size=2> This material is based upon work supported by the National Science Foundation under Grant No.s NSF-0634412 and NSF-0837739. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.</font> </p>
<!-- #EndLibraryItem --></div>
<!-- end copyright -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-7435501-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
<!-- InstanceEnd --></html>
Maybe you are looking for
-
New computer + New iTunes Version = No syncing of new purchases!
A few months back, my husband and I had to purchase a new computer. Once we got the computer up and running, we naturally downloaded iTunes to it so that we could purchase new music to add to both of our iPods (we each have the 30GB iPod w/ video). P
-
We have OAS10g installed on one server and we have SSO server using port 443. Since the port 443 is the default port in the server. We can give the users the url: https://<host>/oiddas for sso server We have the portal and another app installed on th
-
Printed document in once, 2nd time it will show duplication
Hi, I can print delivery document and no problem at all. but i want when 2nd time i will take print of this delivery document it will show copy or already printed in the printed document. How can i do this? Regards, Mizan
-
Example of a formula in a text field
Is it possible to input an example of a formula in a text field? For example: (To get abc - EFG) HIJ= KLM thanks
-
Ipad won't open, charge and be recognized
My sister's ipad mini hasn't been charged for about 2 months because its original cable charger has been lost. Now it won't even open, charge or even recognized in iTunes. Please help me. Send me an email please? ******* <Edited by Host>