Stupid Java Question (Help Needed!!!)
I have a piece of Java Code that dynamically builds a SQL statement (including VARCHAR2 columns). Oracle gives an error if my string has a single quote in it. I need to replace each single quote with two single quotes in Java, i.e. I need a Java equivalent of PL/SQL REPLACE function.
Java str.replace only replaces an individual character (see below).
String l_str = "O'Hara";
String l_str2 = l_str.replace('\'', '\'');
I need to replace "O'Hara" with "O''Hara". Any help is appreciated
Please don't post same question on both forums.
Please find the answer at:
Re: ORA-09004
Similar Messages
-
About Java 2 opaque font color question, help needed!
About Java 2 opaque font color question, help needed!
I was trying to test opaque font (the string has a foreground color and a background color), but i can't find the method for doing that.
i can change foreground by Graphics2D.setPaint(Color.black).
Anybody know how to change the background of the string?
Thanks!Hi. The way I'd do it would be to use the font metrics to find the length of a string and draw a rectangle and then drawstring over the rectangle. If you want an example, I can post it although I suspect theres a better way.
-
Interesting Java Questions. Need answers Pls
Hi All,
I have come accross few java question, could any one please provide best answers please?
1. Why the wait() method is there in the Object class? Not in the Threads?
2. Why JDBC has all interfaces & not classes?
3. Which type of collection do u prefer to make the incoming objects in sort order?
4. Why the hasCode() method should be implemented if we are overiding the equals(0 method?
Please provide me best answers ASAP.
Girish.Kdo u prefer tohttp://www.catb.org/~esr/faqs/smart-questions.html#writewell
How To Ask Questions The Smart Way
Eric Steven Raymond
Rick Moen
Write in clear, grammatical, correctly-spelled language
We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes. -
Stupid Question Help needed....
Hi Folks...
I have a very Stupid Question....
but i think you Folks here can help me Quick...
Here is what i want to do...
01 class ourCar {
02
03 public String color;
04
05 public void PrintValue(String YourValue){
06 System.out.println(this.YourValue );
07
08 }
09 }
10
11 public class myApp {
12 public static void main (String[] args) {
13
14 ourCar Car1;
15 Car1 = new ourCar();
16
17 Car1.color = "red";
18 Car1.PrintValue("color");
19 }
20 }
So the Compiling Problem starts at 05 it seems i cant
get Parameter Names with Strings... so what i want to do is...
type
Car1.PrintValue("color");
and it should print out red
i Know i could write
System.out.println(car1.color);
But i want to do it the other way...
a other thing would be to make
myVar = "car1.color"
and then run
System.out.println(myVar);
but these is also not working...
any idears?
greetings from munich
peterbut where is the Thinking Error i have?
KJKrum wrote i should not use the language this way...
what would be the right way for doing a job like this?You have a very simple example. Reflection which is what both threads suggest as a solution is complex and should be used with caution because of the performance and maintenance problems that can arise.
So one has to wonder, for such a simple problem, does it not suggest that perhaps your design is not correct and if you took another look at it you could come up with a solution that is more appropriate and leads to code with is much simpler.
I believe that was the intent of the suggestion.
For example if you really must access 'attributes' via a key then have you considered that perhaps you don't have attributes but rather 'properties'. And if so there is already a Properties class. And if the Properties class is a little to constraining then the Hashtable might also fulfill what you are trying do. Keep in mind that these depend on whether the best design for your project really requires accessing values via a string. -
Adobe Lightroom 4 - Some Questions / Help Needed
Hi everyone.
After advice from several experts, I've just purchased Adobe Lightroom 4. I've already got Photoshop CS5, but I was looking for something proper to organise my photos, plus I found Lightroom easier to do the sort of editing I am wanting to do. Now, I only really use photoshop for things like colour pops, or really in-depth editing. Anyway, I'm loving Lightroom so far, but there is some stuff I'm not very sure of, so I'd appreciate some help
1. Organising
Firstly, I'm not really sure how to organise. At the moment, I've just got lots of folders with random events in My Pictures on W7, so I might have a folder called April 11, which contains photos from that month but that might have been a wedding or an easter holiday or both. So it doesn't really work. \
I understand in Lightroom what catalogs are. But I know enough to know that I don't want to group mine into those, its getting too complicated. What I don't know though is the difference between a collection and a folder. Basically, I'm wanting to reimport and reorganise all my photos, so I want to put them into "events" as such like you can do on iPhoto on a mac, so I would have "France Summer Holiday 11" for example, or "Mia's Wedding". I'm not really sure on the best way to do this ...?
2. Editing
I've played around quite a bit so far, and I really like what I've seen. On a lot of photos, I've made a lot of changes. But from what I can see, these changes are stored merely in Lightroom itself. For example, at the moment I'm importing photos from my external disk into Lightroom, which then saves them in C://My Pictures/Lightroom/Pictures . When I go look at these photos in windows explorer which I know I have edited, it doesn't show any of the changes or editing I've done on them. Now I realise this is me being stupid, but why doesn't it? Supposing I then want to email that photo to a friend that I have edited? How would I do that? I don't want to have to open lightroom and export every single photo I edit? There must be a simpler way?
Likewise for backing up, because all my files are in subfolders within C:// My pictures / Lightroom / Pictures, to back up I was simply going to set up windows to copy that latter folder onto my external HDD everytime I plugged it in. This would be pointless however if it isn't physically overwriting the original photo with my edited version?
3. Editing 2
Something else I like to do is make lots of different edits to the same photo. For example, at the moment I'm editing a photo of a pier at night. I spent ages adjusting colours and lighting and so on, and now it looks great. But I would also like to save a copy of that photo with the "old age photo" effect preset on. Is this possible? and how do I do it? Other than obviously importing a duplicate?
4. & 5. & 6 - Misc:
4. Simple question - how do I add tags, keywords or comments if I haven't done it on import?
5. My camera doesn't have built in GPS. Is it possible for me to manually geotag photos (in a batch, say for a Summer Holiday to NY), could I manually add a geotag for all these photos?
6. I also forgot to add copyright information on import for some, is it possible to do this after import and how?
7. I normally shoot in JPEG. I probably shoot shoot in RAW as everyone tells me to do so. Are there any significant advantages in terms of quality, and for editing with?
Thanks for any help given. I appreciate this is a lot of questions, but I could really use the advice.Hi William,
1. Organising
Firstly, I'm not really sure how to organise. At the moment, I've just got lots of folders with random events in My Pictures on W7, so I might have a folder called April 11, which contains photos from that month but that might have been a wedding or an easter holiday or both. So it doesn't really work. \
I understand in Lightroom what catalogs are. But I know enough to know that I don't want to group mine into those, its getting too complicated. What I don't know though is the difference between a collection and a folder. Basically, I'm wanting to reimport and reorganise all my photos, so I want to put them into "events" as such like you can do on iPhoto on a mac, so I would have "France Summer Holiday 11" for example, or "Mia's Wedding". I'm not really sure on the best way to do this ...?
I am not so sure if you understand *catalogs*.
You need a catalog, exactly 1 in my opinion. A catalog is a database. The Lightroom database, where records about your images are stored, including the pointers to your images, which are not inside a catalog! LR backups just does the backup of the catalog (i.e. a file ending .lrcat). You need to take care separately that your real images are backed up !
Inside your LR database the best way to organize is via collections - this will give you what you want with "France summer holiday 11" etc.
Folders are relatively unimportant, just storage buckets. They should be *handy portions*, I would prefer them with below 3000 images each, as there currently some bugs to those bigger ones.
Before you start with LR, you can organize your pictures in Mac Finder / WindowsExplorer.
Or you could do it with the help of LR, by copying your images over during import into the destination folders (and deleting today's folders afterwards after having verified that everything is fine).
A simple date-based structure will do, I'd recommend a root parent folder like "LR images", underneath one folder per year (\2010\, \2011\, \2012\...) and underneath them either
just one folder per month (LR can auto-create them for you)
or you create the folders in import dialog as e.g. "YYYY-MM-DD description of shoot", to have a mini-diary overview also in your OS.
Apart from that you create collections, either *dumb ones*, where you drag images into, or smart ones, where you specify criteria according to which they get auto-filled.
2. Editing
I've played around quite a bit so far, and I really like what I've seen. On a lot of photos, I've made a lot of changes. But from what I can see, these changes are stored merely in Lightroom itself. For example, at the moment I'm importing photos from my external disk into Lightroom, which then saves them in C://My Pictures/Lightroom/Pictures . When I go look at these photos in windows explorer which I know I have edited, it doesn't show any of the changes or editing I've done on them. Now I realise this is me being stupid, but why doesn't it? Supposing I then want to email that photo to a friend that I have edited? How would I do that? I don't want to have to open lightroom and export every single photo I edit? There must be a simpler way?
Likewise for backing up, because all my files are in subfolders within C:// My pictures / Lightroom / Pictures, to back up I was simply going to set up windows to copy that latter folder onto my external HDD everytime I plugged it in. This would be pointless however if it isn't physically overwriting the original photo with my edited version?
LR will never overwrite your original photos.
You can save most of the catalog content into the xmp-part of the original photo, which is either a sidecar-file (.xmp) or part of the file format, like for DNG, TIFF, PSD, JPG. To do so you select the image in LR and hit <ctrl> s. Or you set it up for continuous update, which creates a lot of operations while you play back and forth in develop.
I do that on my own, typically twice per file: once I am done with develop, once I am done with keywording and other metadata update.
LR contains records about your images, i.e. a set of instructions how they are to be interpreted. That is all.
So of course you need LR to export the result of these instructions, which is actually pretty quick.
To backup your images you need to do that just once, plus you backup your LR catalog. Or if you save xmp to the files, you can do another backup once xmp is ready.
I would not consider this pointless. You just have to think that there are 2 places with data for your images: the images themselves and a database with interpretation instructions.
3. Editing 2
Something else I like to do is make lots of different edits to the same photo. For example, at the moment I'm editing a photo of a pier at night. I spent ages adjusting colours and lighting and so on, and now it looks great. But I would also like to save a copy of that photo with the "old age photo" effect preset on. Is this possible? and how do I do it? Other than obviously importing a duplicate?
Yes, this is one of LR's beauties: you create a so-called *virtual copy*, which is just a 2nd record for the same original image file with different interpretation settings, like black-and-white, a different crop size, different development etc. You can have as many virtual copies as you like, and you'll see them as additional thumbnails.
Virtual copies are not saveable into xmp, though. There is another concept which is saveable into xmp: snapshots. but these are different states in develop history, and you do not see outside develop module that you have several.
If you export virtual copies e.g. to jpg one file per virutal copy will be created.
4. & 5. & 6 - Misc:
4. Simple question - how do I add tags, keywords or comments if I haven't done it on import?
5. My camera doesn't have built in GPS. Is it possible for me to manually geotag photos (in a batch, say for a Summer Holiday to NY), could I manually add a geotag for all these photos?
6. I also forgot to add copyright information on import for some, is it possible to do this after import and how?
7. I normally shoot in JPEG. I probably shoot shoot in RAW as everyone tells me to do so. Are there any significant advantages in terms of quality, and for editing with?
Thanks for any help given. I appreciate this is a lot of questions, but I could really use the advice.
ad 4: you use the library module, metadata panel to enter.
ad 5: you use the map module. Either you manually drop your images on a map, or you have a separate GPS track to load and have LR assign via matching time-stamps.
ad 6: like 4
ad 7: You don't need JPG from your camera, you can achieve better results viy LR from RAW. Yes, there are significant advantages as to editing headroom.
Overall, may I suggest my favorite learning material for LR? First watch Julieanne's Tutorial Videos.
Then go play and use Victoria Bampton's eBook or paper copy of her "Missing FAQs to LR4": http://www.lightroomqueen.com/books/adobe-lightroom-4-missing-faq/
Have fun,
Cornelia -
Java newbie help: Need to change a graphic on screen
Hello everyone. I'm a long time C/C++ programmer, and I've been thrust into the Java world when I inherited an incomplete project. If something I mention later on sounds stupid, it's probably because it came that way, or I'm trying to force it into what I know from old experience.
FWIW, the project is being developed with Netbeans.
What I'm after is how to change a graphic object onscreen from within the code, vs. with a device such as a mouse. I'm trying to emulate an LED indicator.
What I've done so far is to try using the enable state, and defining GIFs to display. That didn't work.
I've switched gears a bit, and tried something similar with the selected property, but that will only work if I hit the item with my mouse and click. Also, the item is defined as a jToggleButton.
In general terms, what do I need to do to set this up for the displayed item to change without device input? I've been reading stuff about Buttons, ToggleButtons, Graphics, Images, and Icons, and I'm waaaaaay lost right now.
To add to the frustration is that I've done something similar with Visual C++, and that worked as intended. Harumph.
Help?!?FWIW, the project is being developed with Netbeans.
In case you don't know, you can use any editor to develop java code.
What I'm after is how to change a graphic object onscreen from within the code, vs. with a device such as a mouse. I'm trying to emulate an LED indicator.
What I've done so far is to try using the enable state, and defining GIFs to display. That didn't work.
What happend?
I've switched gears a bit, and tried something similar with the selected property, but that will only work if I hit the item with my mouse and click. Also, the item is defined as a jToggleButton.
Is this not what you wanted? -
Basic Java Program help needed urgently.
I have posted the instructions to my project assignment on here that is due tomorrow. I have spent an extremely large amount of time trying to get the basics of programming and am having some difficulty off of the bat. Someone who has more experience with this and could walk me through the steps is what I am hoping for. Any Help however will be greatly appreciated. I am putting in a lot of effort, but I am not getting the results I need. Thank you for the consideration of assisting me with my issues. If you have any questions please feel free to ask. I would love to open up a dialogue.
CIS 120
Mathematical Operators
Project-1
Max possible pts 100
Write a program “MathOperators” that reads two integers, displays user’s name, sum, product,
difference, quotients and modulus of the two numbers.
1. Create a header for your project as follows:
* Prgrammer: Your Name (1 pt) *
* Class: CIS 120 (1 pt) *
* Section: (1 pt) *
* Instructor: (1 pt) *
* Program Name: Mathematical Operators (1 pt) *
* Description: This java program will ask the user to enter two integers and *
display sum, product, difference, quotients and modulus of the two numbers
* (5 pts) *
2. Display a friendly message e.g. Good Morning!! (2 pts)
3. Explain your program to the user e.g. This java program can add, subtract, multiply,
divide and calculate remainder of any two integer numbers entered by you. Let’s get
started…. (5 pts)
4. Prompt the user- Please enter your first name, store the value entered by user in a
string variable name. Use input.next() instead of input.nextLine(). (8 pts)
5. Prompt the user- name, enter first integer number , store the value entered by user in
an integer variable num1.(5 pts)
6. Prompt the user- name, enter second integer number , store the value entered by user in
an integer variable num2.(5 pts)
7. Display the numbers entered by the user as: name has entered the numbers num1and
num2.(5 pts)
8. Calculate sum, product, difference, quotients and modulus of the two numbers. ( 30 pts)
9. Display sum, product, difference, quotients and modulus of the two numbers. ( 10 pts)
10. Terminate your program with a friendly message like- Thanks for using my program,
have a nice day!!(2 pts)Nice try. You have not demonstrated that you've at least TRIED to do something. No one is going to do your homework for you. Your "urgency" is yours alone.
-
Beginner Question - Help Needed for EJB QL Sample Application
I'm working with a group of student interns, like myself, and we've been given an assignment to work with Oracle. All of us have no training or experience with this, so we're just learning as we go.
I've been trying to run the EJB QL Sample Application (http://www.oracle.com/technology/sample_code/tech/java/ejb_corba/ejbql/Install.html), but I keep running into problems at step 3.
Now, we will deploy the sample application onto OC4J. Open another command prompt and go to the folder <OC4J_HOME>/j2ee/home and run the following commands one-by-one
> java -jar admin.jar ormi://<machine_name>:<admin_port> admin <admin_pwd> -deploy -file <SAMPLE_HOME>/build/ejbql.ear -deploymentName Ejbql
> java -jar admin.jar ormi://<machine_name>:<admin_port> admin <admin_pwd> -bindWebApp Ejbql ejbql-war http-web-site /ejbql
where,
<machine_name> Name of the machine where OC4J Server is running
<admin_port> Admin Port on which the OC4J server listens. This value by default is 23791 unless explicitly changed by the user
<admin_pwd> Adminstrator password to access OC4J. The default value is welcome
When I do this step I get this error:
Error: Unable to find java:comp/ServerAdministrator: Lookup error: javax.naming.
AuthenticationException: Invalid username/password for default (sds); nested exc
eption is:
javax.naming.AuthenticationException: Invalid username/password for defa
ult (sds)
com.evermind.client.orion.AdminCommandException: Unable to find java:comp/Server
Administrator: Lookup error: javax.naming.AuthenticationException: Invalid usern
ame/password for default (sds); nested exception is:
javax.naming.AuthenticationException: Invalid username/password for defa
ult (sds)
at com.evermind.client.orion.Oc4jAdminConsole.executeCommand(Oc4jAdminCo
nsole.java:105)
at com.evermind.client.orion.Oc4jAdminConsole.main(Oc4jAdminConsole.java
:27)
javax.naming.NamingException: Lookup error: javax.naming.AuthenticationException
: Invalid username/password for default (sds); nested exception is:
javax.naming.AuthenticationException: Invalid username/password for defa
ult (sds) [Root exception is javax.naming.AuthenticationException: Invalid usern
ame/password for default (sds)]
at com.evermind.server.rmi.RMIContext.lookup(RMIContext.java:153)
at com.evermind.client.orion.Oc4jAdminConsole.executeCommand(Oc4jAdminCo
nsole.java:102)
at com.evermind.client.orion.Oc4jAdminConsole.main(Oc4jAdminConsole.java
:27)
Caused by: javax.naming.AuthenticationException: Invalid username/password for d
efault (sds)
at com.evermind.server.rmi.RMIConnection.connect(RMIConnection.java:2410
at com.evermind.server.rmi.RMIConnection.connect(RMIConnection.java:2226
at com.evermind.server.rmi.RMIConnection.lookup(RMIConnection.java:1692)
at com.evermind.server.rmi.RMIServer.lookup(RMIServer.java:727)
at com.evermind.server.rmi.RMIContext.lookup(RMIContext.java:134)
... 2 more
---- Embedded exception
javax.naming.AuthenticationException: Invalid username/password for default (sds
at com.evermind.server.rmi.RMIConnection.connect(RMIConnection.java:2410
at com.evermind.server.rmi.RMIConnection.connect(RMIConnection.java:2226
at com.evermind.server.rmi.RMIConnection.lookup(RMIConnection.java:1692)
at com.evermind.server.rmi.RMIServer.lookup(RMIServer.java:727)
at com.evermind.server.rmi.RMIContext.lookup(RMIContext.java:134)
at com.evermind.client.orion.Oc4jAdminConsole.executeCommand(Oc4jAdminCo
nsole.java:102)
at com.evermind.client.orion.Oc4jAdminConsole.main(Oc4jAdminConsole.java
:27)
Any suggestions to fix this error?
Thanks in advance for any help.George,
The Readme.html file is available with the ejbqlsample.jar downloadable (Extract and find the doc in Ejbql\docs\Readme.html) which is printable.
Or,
If you are trying to print the file directly from OTN site, you need to set the Page-Setup Orientation to 'Landscape'.
Hope this helps.
Regards
Pushkala -
Pricing : ABAP to Java conversion help needed
Hi all.
I am basically an ABAP developer. My recent assignment needs some java coding.
It will be very helpful if we anybody helps me in finding the corresponding pricing fields in java.
The abap code is as follows
check : xkomv - kgrpe = ' '.
check: xkomv - xkbetr ne 0.
check : komp - kpein ne 0.
if komp - netwr < 0.
komp - netpr = 0 - komp - netpr.
endif.
xkwert = ( ( ( komp - netpr * ( 100000 + xkomv - xkbetr)) / 100000)
komp-mglme / komp-kumza * komp - kumne / 1000 / komp - kpein )
- komp-netwr.
Please help in converting this abap code to its corresponding java code.
Thanks and Regards
DeepikaHere is the code I have developed: Please check and let me know if there are any changes
import java.math.BigDecimal;
import com.sap.spe.pricing.customizing.PricingCustomizingConstants;
import com.sap.spe.pricing.transactiondata.PricingTransactiondataConstants;
import com.sap.spe.pricing.transactiondata.userexit.IPricingConditionUserExit;
import com.sap.spe.pricing.transactiondata.userexit.IPricingItemUserExit;
import com.sap.spe.pricing.transactiondata.userexit.ValueFormulaAdapter;
public class ZS2S_IPC_ZDCP extends ValueFormulaAdapter {
public BigDecimal overwriteConditionValue(
IPricingItemUserExit item,
IPricingConditionUserExit condition) {
BigDecimal kompKumza = new BigDecimal(String.valueOf(condition.getFraction().getNumerator()));
BigDecimal kompKumne = new BigDecimal(String.valueOf(condition.getFraction().getDenominator()));
boolean xkomvKgrpe = condition.isGroupCondition();
BigDecimal kompKpein = condition.getPricingUnit().getValue();
BigDecimal kompNetwr = item.getNetValue().getValue();
BigDecimal kompNetpr = item.getNetPrice().getValue();
BigDecimal xkomvKbetr = condition.getConditionRate().getValue();
BigDecimal kompMglme = item.getBaseQuantity().getValue();
if ( xkomvKgrpe = true )
return PricingTransactiondataConstants.ZERO;
if ( kompKumza != PricingTransactiondataConstants.ZERO )
return PricingTransactiondataConstants.ZERO;
if ( kompKumne != PricingTransactiondataConstants.ZERO )
return PricingTransactiondataConstants.ZERO;
if ( kompKpein != PricingTransactiondataConstants.ZERO )
return PricingTransactiondataConstants.ZERO;
if (kompNetwr.compareTo(PricingTransactiondataConstants.ZERO) < 0 )
kompNetpr = (PricingTransactiondataConstants.ZERO).subtract(kompNetwr);
BigDecimal y = new BigDecimal("100000");
BigDecimal a = y.add(xkomvKbetr);
BigDecimal temp = kompNetpr.multiply(a);
BigDecimal result1 = temp.divide(y, 2, BigDecimal.ROUND_HALF_UP);
BigDecimal result2 = result1.multiply(kompMglme)
.divide(kompKumza, 2 BigDecimal.ROUND_HALF_UP).multiply(kompKumne).divide(kompKpein, 2, BigDecimal.ROUND_HALF_UP);
BigDecimal Result = result2.subtract(kompNetwr);
return Result;
Edited by: Deepika Mallya on Aug 6, 2009 9:08 AM -
Java Progrramming HELP, Needed Urgently, T hanks
hey guys,
I have this lab I need to be done tomorrow, its been weeks lol of thinking and figuring things out can someone make it work ? Pleaseeeee !
I feel like going out and yelling for help lol I have been trying to figure this out for weeks now.
I am pasting my Lab and My Codes I did so far, And Please I really need this done today at any rate, all help would be kindly appreciated.
A Java program is required that will produce a number of reports based on the data from the Product file. This file contains the product name, cost, quantity and UPC. The file name must be input. Valid data from the file will be loaded into an array.
A menu will provide the following options: (Note there are changes from previous assignment.)
1 Display of all valid product information including extended price and GST including totals sorted by name.
2 Display of all invalid records sorted by name.
3 Search and display a certain product by name.
4 Sort by UPC and use a binary search and display a certain product by UPC. (valid records)
9 Exit.
Processing requirements:
Input the data from a file and load the records into an object array. Use this object array to produce the above reports.
Code a class definition exactly as given in the following UML.
(For specific students: you may code the UPC as an integer but if not numeric throw an exception that is handled in main. Document your choice in your submission).
Product
? Name : String
? UPC : String
? Cost : Real
? Quantity : Integer
+ Product (Name : String, UPC : String, Cost : Real, Quantity : Integer)
+ Calculate Extended Cost() : Real
+ Calculate GST(): Real
Input Record:
Product name: String
UPC: String
Cost: real
Quantity: integer
Output Reports
1. Display of all product information including extended cost and GST including totals of these 3 fields.
Following is a sample of the output required:
************************ Product Cost REPORT ****************************
Product Cost Quantity Extended Cost GST Total Cost
Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 10,723,160.83
Tissues 98989898989x 1.99 2 3.98 0.20 4.18
TOTALS 10,212,538.10 510,626.91 10,723,165.01
2. Display of all invalid records and the count.
Following is a sample of the output required:
Invalid UPC Records = 1
Count Record
1 Tiara Diamond, 12345678901x, 36020.00, 2
3. Search and display a certain product by name. Display appropriate message if not found.
Following is a sample of the output required:
Enter product name: CrownJewels
CrownJewels 99999999991x 100,000.00 1 100,000.00 5,000.00 $105,000.00
6. Display the product information sorted by name
Following is a sample of the output required:
************************ Product Cost REPORT ****************************
Product Cost Quantity Extended Cost GST Total Cost
CrownJewels 99999999991x 100,000.00 1 100,000.00 5,000.00 $105,000.00
Diamond Necklace 12345678901x 54,321.99 188 10,212,534.12 510,626.71 $10,723,160.83
Pearls 88888888881x 10,000.00 1 10,000.00 500.00 $10,500.00
RubyRing 77777777771x 10,000.00 1 10,000.00 500.00 $10,500.00
Tissues 98989898989x 1.99 2 3.98 0.20 $4.18
TOTALS (complete these values) xxx xxx xxx
Java coding requirements for this assignment
Main methods required
1. Load array with all records. Display exception messages only for records that have invalid data in any of the fields. Return array of valid records and logical size.
2. Validate the UPC. Display each report when requested from the menu.
3. Justify the data in the columns. Right justify numeric fields; left justify the alpha fields.
4. A method for each report required in the menu.
Class methods
5. Use the object method for the extended cost.
6. Use the object method for the GST.
You may use additional methods in the main program but do not add any methods in the class definition.
Use DecimalFormat for rounding.
Create an array to hold the objects. Assume that we only need to process a file of a maximum of 500 records but the file may be larger than 500 records.
A Universal Product Code consists of 12 digits. The first digit (from the left) is the UPC type. The next five digits are the Manufacturer code. The next five digits are the product code which is assigned by the manufacturer. The final digit is the check digit. A person can determine the check digit of a Universal Product Code by doing the following:
Step 1: Sum all of the digits in the odd positions together.
0+4+0+1+5+9 = 19
Step 2: Multiply the sum from Step 1 by 3.
3 * 19 = 57
Step 3: Sum all of the digits in the even positions together.
6+2+0+1+8 = 17
Step 4: Sum together the results from Step 2 and Step 3.
17 + 57 = 74
Step 5: Subtract the sum from the next highest multiple of 10.
80 - 74 = 6 [check digit]
TEST DATA:
Step 1: Create 5 or MORE additional records that will test all conditions. Include these in your documentation. Identify what field is tested in your test data. (Example: error in each field of the record, rounding up, rounding down, valid UPC, invalid UPC, formatting of report, file too large
Step 2: Use the file attached.
GODDDDDDDDDDDDDD lol pasting it made me go crazy,
these are my codes so far, HOwever the problem is ONLY DISPLAY MENU SHOWS, nothing else even though i have enough codes that it can show something,
My codes are as follows:
I am working on Eclipse.
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.io.IOException;
* Name : Sana Ghani
* Date : July 10
public class lab56
public static Scanner file;
public static Scanner parse;
public static Scanner input = new Scanner(System.in);
public static Scanner searchInput = new Scanner(System.in);
public static void main(String[] args) throws Exception
Product1[] validProduct = new Product1[500];
int logicalSize = 0;
int menuChoice=0;
String FileName = getFileName();
displayMenu();
switch(menuChoice)
case 1:
displayAllValidRecords(validProduct, logicalSize);
try
// Open an output stream
OutputStream fout = new FileOutputStream ("myfile.txt");
// Print a line of text
new PrintStream(fout).println ("hello world!");
// Close our output stream
fout.close();
// Catches any error conditions
catch (IOException e)
System.err.println ("Unable to write to file");
System.exit(-1);
break;
case 2:
break;
case 3:
binarySearchByName( validProduct,logicalSize);
break;
case 4:
break;
case 5:
break;
menuChoice = displayMenu();
public static void display(Product1[]validProduct, int logicalSize)throws Exception
String Product, UPC;
double Cost;
int Quantity;
for(int index =0; index<logicalSize; index++)
Product = validProduct[index].GetName();
UPC = validProduct[index].GetUPC();
Cost=validProduct[index].GetCost();
Quantity=validProduct[index].GetQuantity();
System.out.println(Product+"\t\t"+UPC+"\t\t"+Cost+"\t\t"+Quantity);
public static String getFileName()
String fileName;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a file name: ");
fileName = input.next();
return fileName;
public static int displayMenu()
int menuChoice;
boolean validFlag = false;
do
System.out.println("\n\n*************************************");
System.out.println(" Product Display Menu ");
System.out.println("*************************************");
System.out.println("(1)Display All Records");
System.out.println("(2)Display All Invalid Records");
System.out.println("(3)Search by Product Name");
System.out.println("(4)Sort by Product Name");
System.out.println("(5)Exit");
System.out.println("*************************************");
System.out.print("Enter your choice(1-5): ");
menuChoice = input.nextInt();
if ((menuChoice >= 1) && (menuChoice <= 5))
validFlag = true;
if (!validFlag)
System.out.println("You have chosen " + menuChoice + ", " + menuChoice +
" is not valid. Please try again");
}while(!validFlag);
return menuChoice;
public static String loadArray(Product1 [] ValidProduct, String fileName)throws Exception
int logicalSize=0;//will always have to declare
String record;//will always have to declare
String Product, UPC;//variable names from
double Quantity;
double Cost;
Scanner file = new Scanner(new File(fileName));//open
record = file.nextLine();//read a line
record = file.nextLine();//read a line
for(int index = 0; index < ValidProduct.length && file.hasNext(); index++)//check to see if the file has data
record = file.nextLine();
parse = new Scanner(record).useDelimiter(",");
String Name = parse.next();
UPC = parse.next();
Cost = parse.nextDouble();
Quantity=parse.nextDouble();
ValidProduct[index] = new Product1 ( Name, UPC, Cost, (int) Quantity);
// create the object-- call the constructor and pass info
logicalSize++;
return logicalSize+".txt";
public static double roundDouble(double value, int position)
java.math.BigDecimal bd = new java.math.BigDecimal(value);
bd = bd.setScale(position,java.math.BigDecimal.ROUND_UP);
return bd.doubleValue();
* This method will print report about valid records
public static void displayAllRecords( Product1[]valid, int ValidProduct,
Product1[] invalid, int InvalidProduct)
// Print valid records
displayAllValidRecords(valid, ValidProduct);
// Print invalid UPC records
displayAllValidRecords(invalid, InvalidProduct);
public static void displayOneRecord(Product1[]valid, int index)
double extendedCost, GST, SumofGST = 0, // Total Extended Cost
totalCost, SumOfTotalCost = 0; // Total Extended Cost + GST
// Print title
System.out.println(leftJustify("Product", 50) +
leftJustify("UPC", 15) +
rightJustify("Cost", 10) +
rightJustify("Quantity", 5) +
rightJustify("Extended Cost", 15) +
rightJustify("GST", 5) +
rightJustify("Total Cost", 13));
extendedCost = valid[index].CalculateExtendedCost();
extendedCost = roundDouble(extendedCost, 2);
GST = valid[index].CalculateGST();
GST = roundDouble(GST, 2);
totalCost = extendedCost + GST;
totalCost = roundDouble(totalCost, 2);
// justify method ensures all values are of the same size
System.out.println(//leftJustify(i+"",3) + ": " +
leftJustify(valid[index].GetName(), 50) +
leftJustify(valid[index].GetUPC(), 15) +
rightJustify(valid[index].GetCost()+"", 10) +
rightJustify(valid[index].GetQuantity()+"", 5) +
rightJustify(extendedCost+"", 10) +
rightJustify(GST+"", 10) +
rightJustify(totalCost+"", 10));
* This method will print report about valid records
public static void displayAllValidRecords( Product1[]valid, int validCounter)
double extendedCost, sumOfExtendedCost = 0, // Total Extended Cost
GST, sumOfGST = 0, // Total GST
totalCost, sumOfTotalCost = 0; // Total Extended Cost + GST
System.out.println("************************ XYZ Product " +
"Cost REPORT ****************************" +
// Print title
System.out.println(leftJustify("Product", 50) +
leftJustify("UPC", 15) +
rightJustify("Cost", 10) +
rightJustify("Qty", 5) +
rightJustify("Extended Cost", 15) +
rightJustify("GST", 5) +
rightJustify("Total Cost", 13));
// Print Records
for(int i=0; i<validCounter; i++)
extendedCost = valid.CalculateExtendedCost();
extendedCost = roundDouble(extendedCost, 2);
GST = valid[i].CalculateGST();
GST = roundDouble(GST, 2);
totalCost = extendedCost + GST;
totalCost = roundDouble(totalCost, 2);
// justify method ensures all values are of the same size
System.out.println(//leftJustify(i+"",3) + ": " +
leftJustify(valid[i].GetName(), 50) +
leftJustify(valid[i].GetUPC(), 15) +
rightJustify(valid[i].getClass()+"", 10) +
rightJustify(valid[i].GetQuantity()+"", 5) +
rightJustify(extendedCost+"", 10) +
rightJustify(GST+"", 10) +
rightJustify(totalCost+"", 10));
sumOfExtendedCost += extendedCost;
sumOfGST += GST;
sumOfTotalCost += totalCost;
private static void sortByName(Product1 [] ValidProduct, int logicalSize) throws Exception
Product1 temp;
for (int outer = logicalSize-1; outer > 1; outer --)
for (int inner = 0; inner < outer; inner ++)
if (ValidProduct[inner].GetName().compareToIgnoreCase(ValidProduct[inner+1].GetName())>0)
temp = ValidProduct[inner];
ValidProduct[inner] = ValidProduct[inner + 1];
ValidProduct [+ 1] = temp;
public static void binarySearchByName(Product1 [] ValidProduct, int logicalSize)
int high = logicalSize - 1;
int low = 0;
int mid = 0;
int count = 0;
int compare = 0;
boolean found = false;
System.out.print("Enter a product name");
String product = input.nextLine();
while (high >= low && !found)
count += 1;
mid = (high + low) / 2;
compare = ValidProduct[mid].GetName().compareToIgnoreCase(product);
if (compare == 0)
System.out.println("Found: " + ValidProduct[mid].GetName());
found = true;
else if (compare < 0)
low = mid + 1;
else
high = mid - 1;
if (!found)
System.out.println(product + " not found.");
System.out.println(count + " steps");
System.out.println();
public static String leftJustify(String field, int width)
StringBuffer buffer = new StringBuffer(field);
while (buffer.length() < width)
buffer.append(' ');
return buffer.toString();
public static String rightJustify(String field, int width)
StringBuffer buffer = new StringBuffer(field);
while (buffer.length() < width)
buffer.append(' ');
return buffer.toString();
public static void displayValidRecords(Product1 [] ValidProduct, int logicalSize) throws Exception {
long longMAX_POSSIBLE_UPC_CODE = 999999999999L;
// set input stream and get number
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a 12-digit UPC number: ");
long input =stdin.nextLong();
long number = input;
// determine whether number is a possible UPC code
if ((input < 0)|| (input > longMAX_POSSIBLE_UPC_CODE)) {
// not a UPC code
System.out.println(input +"is an invalid UPC code");
else {
// might be a UPC code
// determine digits
int d12 = (int) (number % 10);
number /= 10;
int d11 = (int) (number % 10);
number /= 10;
int d10 = (int) (number % 10);
number /= 10;
int d9 = (int) (number % 10);
number /= 10;
int d8 = (int) (number % 10);
number /= 10;
int d7 = (int) (number % 10);
number /= 10;
int d6 = (int) (number % 10);
number /= 10;
int d5 = (int) (number % 10);
number /= 10;
int d4 = (int) (number % 10);
number /= 10;
int d3 = (int) (number % 10);
number /= 10;
int d2 = (int) (number % 10);
number /= 10;
int d1 = (int) (number % 10);
number /= 10;
// compute sums of first 5 even digits and the odd digits
int m = d2 + d4 d6 d8 + d10;
int n = d1 + d3 d5 d7 + d9 + d11;
// use UPC formula to determine required value for d12
int r = 10 - ((m +3*n) % 10);
// based on r, can test whether number is a UPC code
if (r == d12) {
// is a UPCcode
System.out.println(input+" is a valid UPC code");
else {
// not a UPCcode
System.out.println(input+" is not valid UPC code");
Any help would be great thanks !!
Take care,1) It's your problem that you waited until the last minute before you went for help...not ours. We'll give your problem the same attention as anyone elses...therefore your problem isn't any more urgent than any other problem here.
2) I don't intend on doing your entire assignment. Nor do I intend on reading all of it. If you need help with a specific requirement, then post the information/code relevant to that requirement. I don't know how to help you when you bury the problem inside a 9 mile long essay.
3) Post code in tags so it's formatted and readable. (there's a *code* button up above that makes the tags for you). -
Java Calendar Help Needed :)
Hi,
I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
If anyone has any suggestions please could you help me out :)
Sorry if what im trying to do is a bit confusing.
I've included the code i've been using for the monthly calendar
THANKS!!
public class CalendarPanel extends JPanel implements ActionListener {
private Calendar panelDate;
private Label monthLabel;
private Label yearLabel;
private Panel daysPanel;
private Vector calendarListeners;
private static final String days[] = {"S","M","T","W","T","F","S"};
public CalendarPanel(){
super(new BorderLayout());
panelDate = Calendar.getInstance();
buildUI();
public CalendarPanel(Calendar date){
super(new BorderLayout());
panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
buildUI();
public CalendarPanel(Date date){
super(new BorderLayout());
panelDate = Calendar.getInstance();
if(date != null) panelDate.setTime(date);
buildUI();
public Calendar getCalendar(){ return panelDate;}
public void setCalendar(Calendar date){
if(date != null){
panelDate = (Calendar)date.clone();
redrawPanel();
public void setCalendar(Date date){
if(date != null){
panelDate.setTime(date);
redrawPanel();
public int getYear(){ return panelDate.get(Calendar.YEAR);}
public String getMonthName(){
switch(panelDate.get(Calendar.MONTH)){
case Calendar.JANUARY: return "January";
case Calendar.FEBRUARY: return "February";
case Calendar.MARCH: return "March";
case Calendar.APRIL: return "April";
case Calendar.MAY: return "May";
case Calendar.JUNE: return "June";
case Calendar.JULY: return "July";
case Calendar.AUGUST: return "August";
case Calendar.SEPTEMBER: return "September";
case Calendar.OCTOBER: return "October";
case Calendar.NOVEMBER: return "November";
case Calendar.DECEMBER: return "December";
case Calendar.UNDECIMBER: return "Undecimber";
default: return "Unknown";
private void buildUI(){
this.add(buildHeaderPanel(), BorderLayout.NORTH);
daysPanel = new Panel(new GridBagLayout());
redrawPanel();
this.add(daysPanel, BorderLayout.CENTER);
// build the part of the gui that contains the month and year
// labels with their incrementors / decrementors
private Panel buildHeaderPanel(){
monthLabel = new Label(getMonthName(), Label.CENTER);
yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
Label.CENTER);
GridBagConstraints gbc = new GridBagConstraints();
Panel headerPanel = new Panel(new GridBagLayout());
// month label and buttons
Panel panel = new Panel(new GridBagLayout());
Button button = new Button("-");
button.setActionCommand("decrease month");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.EAST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
panel.add(monthLabel, gbc);
button = new Button("+");
button.setActionCommand("increase month");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.WEST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
headerPanel.add(panel, gbc);
// year label and buttons
panel = new Panel(new GridBagLayout());
button = new Button("-");
button.setActionCommand("decrease year");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 0;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
panel.add(yearLabel, gbc);
button = new Button("+");
button.setActionCommand("increase year");
button.addActionListener(this);
gbc.anchor = GridBagConstraints.WEST;
panel.add(button, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
headerPanel.add(panel, gbc);
return headerPanel;
// redraws the entire panel, including relaying out of
// the days buttons
private void redrawPanel(){
monthLabel.setText(getMonthName());
yearLabel.setText(Integer.toString(getYear()));
// redraw days panel
GridBagConstraints gbc = new GridBagConstraints();
// clear current days panel
daysPanel.removeAll();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
// add days of week
for(int i = 0; i < days.length; i++, gbc.gridx++)
daysPanel.add(new Label(days, Label.CENTER), gbc);
gbc.gridx = 0;
gbc.gridy++;
// days of month
Button button; // day buttons
JTable day = new JTable();
Calendar today = Calendar.getInstance();
Calendar cellDay = (Calendar)today.clone();
int month = panelDate.get(Calendar.MONTH);
int year = panelDate.get(Calendar.YEAR);
// start with first of panels month
cellDay.set(year, month, 1);
gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
while( cellDay.get(Calendar.MONTH) == month ){
if(gbc.gridx > 6){
gbc.gridy++;
gbc.gridx = 0;
button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
button.addActionListener(this);
if( cellDay.equals(today)){
button.setForeground(Color.red);
daysPanel.add(button, gbc);
gbc.gridx++;
cellDay.add(Calendar.DAY_OF_MONTH, 1);
// re validate entire panel
validate();
// implementation of ActionListener interface
// currently no real need to create subclassed action
// events for calendar. All actions generated by this
// are action events (generated from the buttons).
// the action command will be one of the four below
// or a number (the label of the day button!).
public void actionPerformed(ActionEvent ae){
String command = ae.getActionCommand();
if(command.equals("increase month")){
panelDate.add(Calendar.MONTH, 1);
redrawPanel();
} else if(command.equals("decrease month")){
panelDate.add(Calendar.MONTH, -1);
redrawPanel();
} else if(command.equals("increase year")){
panelDate.add(Calendar.YEAR, 1);
redrawPanel();
} else if(command.equals("decrease year")){
panelDate.add(Calendar.YEAR, -1);
redrawPanel();
notifyCalendarListeners(ae);
// methods for keeping track of interested listeners
public void addCalendarActionListener(ActionListener al){
if(al != null){
if(calendarListeners == null) calendarListeners = new Vector();
calendarListeners.addElement(al);
public void removeCalendarActionListener(ActionListener al){
if((calendarListeners != null) && (al != null)){
calendarListeners.removeElement(al);
private void notifyCalendarListeners(ActionEvent ae){
if((calendarListeners != null) && (!calendarListeners.isEmpty())){
java.util.Enumeration e = calendarListeners.elements();
while(e.hasMoreElements())
((ActionListener)e.nextElement()).actionPerformed(ae);Hi,
Sorry for the change of screen name, i'm having trouble with my old account.
I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
* @category CalendarSystem
* @author Daniel Barrett
public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener {
JPanel events = new JPanel();
JPanel action = new JPanel();
//Events Panel
DateComboBox eventDateChooser = new DateComboBox();
JTextField ref = new JTextField(10);
JTextArea eventDetails = new JTextArea();
JScrollPane scrollingArea = new JScrollPane(eventDetails);
JTextField dateF = new JTextField(15);
JTextField timeF = new JTextField(15);
String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
JComboBox minsComb = new JComboBox(minutes);
JComboBox hourComb = new JComboBox(hours);
//Actions Panel
JButton delete = new JButton("Delete");
JButton purge = new JButton("Purge");
JButton add = new JButton("Add");
JButton edit = new JButton("Edit");
JButton mview = new JButton("Month View");
protected JLabel monthLabel;
protected JLabel weekLabel;
protected JLabel lmonday = new JLabel("");
protected JLabel ltuesday = new JLabel("");
protected JLabel lwednesday = new JLabel("");
protected JLabel lthursday = new JLabel("");
protected JLabel lfriday = new JLabel("");
protected JLabel lsaturday = new JLabel("");
protected JLabel lsunday = new JLabel("");
protected Calendar calendar;
protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
JPanel monthCont = new JPanel();
JPanel weekCont = new JPanel();
JPanel yearCont = new JPanel();
JPanel daysOfWeek = new JPanel();
JPanel monday = new JPanel();
JPanel tuesday = new JPanel();
JPanel wednesday = new JPanel();
JPanel thursday = new JPanel();
JPanel friday = new JPanel();
JPanel saturday = new JPanel();
JPanel sunday = new JPanel();
JList mondayEvents = new JList();
JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
JList tuesdayEvents = new JList();
JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
JList wednesdayEvents = new JList();
JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
JList thursdayEvents = new JList();
JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
JList fridayEvents = new JList();
JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
JList saturdayEvents = new JList();
JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
JList sundayEvents = new JList();
JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
protected Color selectedBackground;
protected Color selectedForeground;
protected Color background;
protected Color foreground;
public CalendarSystem(){
setupDays();
setupHeaders();
setupEvents();
setupActions();
this.calendar = Calendar.getInstance();
this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
this.add(this.monthCont);
this.add(this.daysOfWeek);
this.add(this.weekCont);
this.add(this.events);
this.add(this.action);
this.setLayout(new BoxLayout(this,1));
this.setMaximumSize(new Dimension(400,30));
this.updateCalendar();
private void setupActions() {
this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
this.action.add(this.add);
this.action.add(this.edit);
this.action.add(this.delete);
this.action.add(this.purge);
this.action.add(this.mview);
private void setupEvents() {
this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
this.events.setLayout(new BoxLayout(this.events,1));
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JLabel la = new JLabel("Reference");
JLabel da = new JLabel("Date");
JLabel time = new JLabel("Time");
JLabel det = new JLabel("Details");
this.ref.setEditable(false);
this.dateF.setEditable(false);
this.timeF.setEditable(false);
this.eventDetails.setEditable(false);
row1.add(la);
row1.add(this.ref);
row1.add(da);
row1.add(this.dateF);
row1.add(time);
row1.add(this.timeF);
row2.add(det);
scrollingArea.setPreferredSize(new Dimension(600,50));
row3.add(this.scrollingArea);
this.events.add(row1);
this.events.add(row2);
this.events.add(row3);
protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
final JLabel label = new JLabel();
final Border selectedBorder = new EtchedBorder();
final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
label.setBorder(unselectedBorder);
label.setForeground(foreground);
label.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
calendar.add(field, amount);
if(month){
updateMCalendar();}
else{
updateCalendar();
public void mouseEntered(MouseEvent e) {
label.setBorder(selectedBorder);
public void mouseExited(MouseEvent e) {
label.setBorder(unselectedBorder);
return label;
private void updateMCalendar() {
this.calendar.set(Calendar.DAY_OF_MONTH, 1);
updateCalendar();
private void setupHeaders() {
//MONTH CONTROLS
monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
monthCont.setBackground(background);
monthCont.setOpaque(true);
JLabel label;
label = createUpdateButton(Calendar.YEAR, -1,false);
label.setText("<<");
label.setToolTipText("Previous Year");
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(label);
monthCont.add(Box.createHorizontalStrut(12));
label = createUpdateButton(Calendar.MONTH, -1,true);
label.setText("< ");
label.setToolTipText("Previous Month");
monthCont.add(label);
monthLabel =new JLabel("", JLabel.CENTER);
monthLabel.setForeground(foreground);
//monthCont.add(Box.createHorizontalGlue());
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(monthLabel);
monthCont.add(Box.createHorizontalStrut(12));
//monthCont.add(Box.createHorizontalGlue());
label =createUpdateButton(Calendar.MONTH, 1,true);
label.setText(" >");
label.setToolTipText("Next Month");
monthCont.add(label);
label = createUpdateButton(Calendar.YEAR, 1,false);
label.setText(">>");
label.setToolTipText("Next Year");
monthCont.add(Box.createHorizontalStrut(12));
monthCont.add(label);
monthCont.add(Box.createHorizontalStrut(12));
//WEEK CONTROLS
weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
weekCont.setBackground(background);
weekCont.setOpaque(true);
JLabel label1;
label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
label1.setText("<<");
label1.setToolTipText("Previous Week");
weekCont.add(label1);
weekLabel =new JLabel("", JLabel.CENTER);
weekLabel.setForeground(foreground);
JLabel lweek =new JLabel("Week: ", JLabel.CENTER);
lweek.setForeground(foreground);
//monthCont.add(Box.createHorizontalGlue());
weekCont.add(Box.createHorizontalStrut(12));
weekCont.add(lweek);
weekCont.add(weekLabel);
weekCont.add(Box.createHorizontalStrut(12));
//monthCont.add(Box.createHorizontalGlue());
label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
label1.setText(">>");
label1.setToolTipText("Next Week");
weekCont.add(label1);
public void setupDays(){
monday.setLayout(new BoxLayout(monday,1));
tuesday.setLayout(new BoxLayout(tuesday,1));
wednesday.setLayout(new BoxLayout(wednesday,1));
thursday.setLayout(new BoxLayout(thursday,1));
friday.setLayout(new BoxLayout(friday,1));
saturday.setLayout(new BoxLayout(saturday,1));
sunday.setLayout(new BoxLayout(sunday,1));
monday.add(this.lmonday);
monday.add(this.mondayEventsScroll);
monday.setBorder(BorderFactory.createTitledBorder("Monday"));
tuesday.add(this.ltuesday);
tuesday.add(this.tuesdayEventsScroll);
tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
wednesday.add(this.lwednesday);
wednesday.add(this.wednesdayEventsScroll);
wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
thursday.add(this.lthursday);
thursday.add(this.thursdayEventsScroll);
thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
friday.add(this.lfriday);
friday.add(this.fridayEventsScroll);
friday.setBorder(BorderFactory.createTitledBorder("Friday"));
saturday.add(this.lsaturday);
saturday.add(this.saturdayEventsScroll);
saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
sunday.add(this.lsunday);
sunday.add(this.sundayEventsScroll);
sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
this.monday.setPreferredSize(new Dimension(145,300));
this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.tuesday.setPreferredSize(new Dimension(145,300));
this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.wednesday.setPreferredSize(new Dimension(145,300));
this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.thursday.setPreferredSize(new Dimension(145,300));
this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
this.friday.setPreferredSize(new Dimension(145,300));
this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
this.saturday.setPreferredSize(new Dimension(145,300));
this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
this.sunday.setPreferredSize(new Dimension(145,300));
daysOfWeek.add(this.sunday);
daysOfWeek.add(this.monday);
daysOfWeek.add(this.tuesday);
daysOfWeek.add(this.wednesday);
daysOfWeek.add(this.thursday);
daysOfWeek.add(this.friday);
daysOfWeek.add(this.saturday);
private void updateCalendar() {
monthLabel.setText(monthFormat.format(calendar.getTime()) );
weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
//Blank out / empty strings for first elements that do not start on sunday
Calendar setupCalendar = (Calendar) calendar.clone();
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
// while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
//System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
//System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
//System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
public void setDayLabels(int day, int dayOfWeek){
if(dayOfWeek == 1){
this.lsunday.setText(String.valueOf(day));
if(dayOfWeek == 2){
this.lmonday.setText(String.valueOf(day));
if(dayOfWeek == 3){
this.ltuesday.setText(String.valueOf(day));
if(dayOfWeek == 4){
this.lwednesday.setText(String.valueOf(day));
if(dayOfWeek == 5){
this.lthursday.setText(String.valueOf(day));
if(dayOfWeek == 6){
this.lfriday.setText(String.valueOf(day));
if(dayOfWeek == 7){
this.lsaturday.setText(String.valueOf(day));
@Override
public void actionPerformed(ActionEvent arg0) {
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
public static void main(String args[]){
JFrame frame = new JFrame();
frame.setSize(1100, 670);
frame.add(new CalendarSystem());
frame.setVisible(true);
}Thanks
Dan -
JAVA QUESTIONS HELP!!!!!
Hi there im a student and have an exam on java coming up next week, i have a few past paper questions that im stuck with if anyone can help that would be great.....
1.) Java implements generic types by erasure: what does this mean?
A. The compiler removes references to parameter types and inserts casts wherever return types refer to parameter types.
B. The programmer must comment out references to parameter types before code is compiled.
C. The compiler removes any casts that may be type-unsafe. 􀀀
D. The compiler removes any references to parameter types and inserts references to the closest super class that will make expressions type-safe.
E. Any type-unsafe casts to parameter types will be ignored by the interpreter at run-time.
2.) In Remote method Invocation, what is meant by �marshalling�?
A. Marshalling is the process of synchronizing all parameters to the method being invoked, in order to
prevent data corruption arising from the concurrent method call. 􀀀
B. Marshalling is the process of sending a copy of the remote object to the client JVM in order to
invoke its method locally. 􀀀
C. Marshalling is the process of sending the state of the client JVM on a byte stream to the remote
object in order that the JVM can be started as a separate thread on the remote host. 􀀀
D. Marshalling is the process of suspending the current thread in the client JVM until a result is obtained
from the remote method invocation. 􀀀
E. Marshalling is the process of sending the state of all parameter instances on a byte stream to the remote object.
3.)What is the immediate superclass of javax.swing.JFrame?
A. java.lang.Object 􀀀
B. javax.swing.Window 􀀀
C. javax.swing.JComponent 􀀀
D. java.AWT.Window 􀀀
E. java.AWT.Frame
4.) What is the immediate superclass of javax.swing.JComponent?
A. java.lang.Object 􀀀
B. java.AWT.Component 􀀀
C. java.AWT.Container 􀀀
D. java.AWT.Window 􀀀
E. javax.swing.Object
5.) Which of the following statements about the java.AWT and javax.swing packages is true?
A. All components in both packages are thread-safe􀀀
B. Most components in both packages are thread-safe􀀀
C. Most components in java.AWT are thread-safe, but most in javax.swing are not􀀀
D. Most components in javax.swing are thread-safe, but most in java.AWT are not􀀀
E. No components in either package are thread-safe􀀀
6.) Which of the following best describes how AWT events are handled in Java?
A. There is a special thread that handles all AWT events. 􀀀
B. Each AWT event causes a new thread to be created to handle that event. 􀀀
C. All AWT events are handled in the main thread. 􀀀
D. The programmer must explicitly create one thread to handle all AWT events. 􀀀
E. For each AWT event, the programmer must explicitly create a thread to handle that event. 􀀀
7.) Which of the following best describes how component-generated events can be handled in Java?
A. All component-generated events are handled automatically by the Java interpreter. 􀀀
B. The programmer creates instances of appropriate listener classes, and registers these instances with
the component; when the component generates an event, the relevant methods of all registered
listeners are executed. 􀀀
C. The programmer creates instances of appropriate listener classes, and registers these instances with
the component; when the component generates an event, one of the registered listeners is chosen by
the interpreter and the relevant method of that instance is executed. 􀀀
D. The programmer must declare a subclass of the component and add one method for each type of
event the component can generate; when the component generates an event, the appropriate method
is executed. 􀀀
E. Each component class has event-handling methods; the programmer declares a subclass of the
component and overrides those methods; when the component generates an event, the overridden
method is executed. 􀀀
Any help would b great thanks guys. Andy1.) Java implements generic types by erasure: what
does this mean?
A. The compiler removes references to parameter types
and inserts casts wherever return types refer to
parameter types.
B. The programmer must comment out references to
parameter types before code is compiled.
C. The compiler removes any casts that may be
type-unsafe. 􀀀
D. The compiler removes any references to parameter
types and inserts references to the closest super
class that will make expressions type-safe.
E. Any type-unsafe casts to parameter types will be
ignored by the interpreter at run-time.None of the above (assuming this is not a Google translation of some non-English text).
2.) In Remote method Invocation, what is meant by
�marshalling�?
A. Marshalling is the process of synchronizing all
parameters to the method being invoked, in order to
prevent data corruption arising from the concurrent
method call. 􀀀
B. Marshalling is the process of sending a copy of
the remote object to the client JVM in order to
invoke its method locally. 􀀀
C. Marshalling is the process of sending the state of
the client JVM on a byte stream to the remote
object in order that the JVM can be started as a
separate thread on the remote host. 􀀀
D. Marshalling is the process of suspending the
current thread in the client JVM until a result is
obtained
from the remote method invocation. 􀀀
E. Marshalling is the process of sending the state of
all parameter instances on a byte stream to the
remote object.None of the above. Although there is one answer that at least describes how Marshalling is used.
3.)What is the immediate superclass of
javax.swing.JFrame?
A. java.lang.Object 􀀀
B. javax.swing.Window 􀀀
C. javax.swing.JComponent 􀀀
D. java.AWT.Window 􀀀
E. java.AWT.FrameAt least this one does have the correct answer. It's in the API docs, so I guess it'd be hard to be wrong.
4.) What is the immediate superclass ofDitto.
5.) Which of the following statements about the
java.AWT and javax.swing packages is true?
A. All components in both packages are
thread-safe􀀀
B. Most components in both packages are
thread-safe􀀀
C. Most components in java.AWT are thread-safe, but
most in javax.swing are not􀀀
D. Most components in javax.swing are thread-safe,
but most in java.AWT are not􀀀
E. No components in either package are
thread-safe􀀀Again, none of the above.
6.) Which of the following best describes how AWT
events are handled in Java?
A. There is a special thread that handles all AWT
events. 􀀀
B. Each AWT event causes a new thread to be created
to handle that event. 􀀀
C. All AWT events are handled in the main thread.
􀀀
D. The programmer must explicitly create one thread
to handle all AWT events. 􀀀
E. For each AWT event, the programmer must explicitly
create a thread to handle that event. 􀀀One answer is almost, sort of, correct. Wow.
I can understand why you're having problems answering these questiosn. Well, there's no excuse for the questions that come out fo the Javadocs, but for the others ... it explains a lot about the quality of recent graduates. -
Basic java problem help needed please
the problem is :
to produce a program which will show membership rates for a golf club..
membership yearly rate new member joining fee
category
full 650 3000
associate 200
ladies 350 2000
under 18 175
new members must pay a joining fee in addition to the yearly rate as shown
full/ladies members also prepay 150
write a program which will enter details of members,calculate and output the total amount each member should pay.
output number of members in each category
the total income for each category....
i need this program to show each category individually...cant do it at all..been at it a week....must be me && and || signs...i think...plz can someone help me as im really stuck now...thank you so much..
import java.util.Scanner;
public class assignmentquestion3 {
public static Scanner key=new Scanner(System.in);
public static void main(String []args){
int fullfee=800,newfullfee=3800,associatefee=200,newla diesfee= 2350,ladiesfee= 350,under18fee = 175;
int selectcat=0;
int reply = 0;
int addmember=0;
int currentfulltotalmem=0,newfulltotalmem=0,associatet otalmem=0,ladiestotalmem=0,under18totalmem=0;
int assoctotalcash=0,ladiestotalcash=0,under18totalcas h=0;
int fullprepay=150;
int ladiesfull=2500;
int completefull = 0;
int ladiescurrent=500;
int under18=175;
//Main introduction screen for the user and selections available. do while loops only allowing numbers 1,2,3 or 4.
do{
do{
System.out.printf("\n\t %90s","********************Membership Rates For The Golf Club********************");
System.out.printf("\n\n %105s","This program will allow users to enter details of members as well as calculating and.");
System.out.printf("\n%106s","outputing the total amount each member should pay. The program allows users to view the");
System.out.printf("\n%106s","total number of members in each category and the total income for each category.");
System.out.printf("\n\n\t %75s","Please select your membership category: ");
System.out.printf("\n\n\t %68s","Please press '1' for FULL");
System.out.printf("\n\n\t %68s","Please press '2' for ASSOCIATE");
System.out.printf("\n\n\t %68s","Please press '3' for LADIES");
System.out.printf("\n\n\t %68s","Please press '4' for UNDER 18");
System.out.printf("\n\n\t %68s","Please enter 1,2,3 or 4: ");
selectcat=key.nextInt();
}while (selectcat>4 || selectcat<1);
do{
System.out.printf("\n\n\t %75s","Are you a Current Member (press 1) or a New Member (press 2): ");
reply=key.nextInt();
}while (reply<1 || reply>2);
//if number '1' for 'FULL' category is selected by the user and reply is 'yes'(1) then new full member fee is shown to user
if (selectcat==1 ||reply==1)
System.out.printf("\n\n\t %68s","CURRENT FULL MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %68s","Current full membership fees yearly are "+fullfee+"");
System.out.printf("\n\n\t %68s","Full members must also pre-pay "+fullprepay+" on a card can be used in the club facilities such as bar and shop ");
System.out.printf("\n\n\t %72s","The total of this membership is: "+fullfee+"");
currentfulltotalmem=currentfulltotalmem+1;
System.out.printf("\n\n\t %72s","The total number of 'CURRENT FULL MEMBERSHIPS = "+currentfulltotalmem+"");
completefull=completefull+fullfee;
System.out.printf("\n\n\t %68s","The total amount of income for 'FULL MEMBERSHIPS' within the club = "+completefull+"");
//if number '1' is selected by the user and reply is 'no' (2) then full member fee is shown to user
else if (selectcat==1 &&reply==2)
System.out.printf("\n\n\t %68s","NEW FULL MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %68s","Full membership fees yearly are "+newfullfee+"");
newfulltotalmem=newfulltotalmem+1;
System.out.printf("\n\n\t %68s","The total number of 'NEW FULL MEMBERSHIPS = "+newfulltotalmem+"");
completefull=completefull+newfullfee;
System.out.printf("\n\n\t %68s","The total amount of income for 'FULL MEMBERSHIPS' within the club = "+completefull+"");
//if number '2' is selected by the user then associate member fee is shown to user
if (selectcat==2 &&(reply==1 || reply==2))
System.out.printf("\n\n\t %75s","ASSOCIATE MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %75s","ASSOCIATE membership fees yearly are "+associatefee+"");
associatetotalmem=associatetotalmem+1;
System.out.printf("\n\n\t %75s","The total number of 'ASSOCIATE MEMBERSHIPS' WITHIN THE CLUB = "+associatetotalmem+"");
assoctotalcash=assoctotalcash+associatefee;
System.out.printf("\n\n\t %68s","The total amount of income for 'ASSOCIATE MEMBERSHIPS' within the club = "+assoctotalcash+"");
//if number '3' is selected by the user and reply is 'yes' then new ladies member fee is shown to user
if (selectcat==3 &&reply==1)
System.out.printf("\n\n\t %68s","LADIES CURRENT MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %68s","Ladies full membership fees yearly are "+ladiesfee+"");
System.out.printf("\n\n\t %68s","Ladies must also pre-pay "+fullprepay+" on a card can be used in the club facilities such as bar and shop ");
System.out.printf("\n\n\t %68s","The total of this membership is: "+ladiescurrent+"");
ladiestotalmem=ladiestotalmem+1;
System.out.printf("\n\n\t %75s","The total number of 'LADIES MEMBERSHIPS' WITHIN THE CLUB = "+ladiestotalmem+"");
ladiestotalcash=ladiestotalcash+ladiescurrent;
System.out.printf("\n\n\t %68s","The total amount of income for 'LADIES MEMBERSHIPS' within the club = "+ladiestotalcash+"");
//if number '3' is selected by the user and reply is 'no' then the current ladies member fee is shown to user
else
if (selectcat==3 && reply==2)
System.out.printf("\n\n\t %68s","LADIES NEW MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %68s","LADIES NEW MEMBERSHIP fees yearly are "+newladiesfee+"");
System.out.printf("\n\n\t %68s","Ladies must also pre-pay "+fullprepay+" on a card can be used in the club facilities such as bar and shop ");
System.out.printf("\n\n\t %68s","The total of this membership is: "+ladiesfull+"");
ladiestotalmem=ladiestotalmem+1;
System.out.printf("\n\n\t %75s","The total number of 'LADIES MEMBERSHIPS' within the club = "+ladiestotalmem+"");
ladiestotalcash=ladiestotalcash+ladiesfull;
System.out.printf("\n\n\t %68s","The total amount of income for 'LADIES MEMBERSHIPS' within the club = "+ladiestotalcash+"");
//if number '4' is selected by the user then under 18 member fee is shown to user
else if (selectcat==4 &&(reply==1||reply==2))
System.out.printf("\n\n\t %75s","UNDER 18 MEMBERSHIP SELECTED");
System.out.printf("\n\n\t %75s","UNDER 18 yearly membership fees are "+under18fee+"");}
System.out.printf("\n\n\t %68s","The total of this membership is: "+under18+"");
under18totalmem=under18totalmem+1;
System.out.printf("\n\n\t %75s","The total number of 'UNDER 18 MEMBERSHIPS' within the club = "+under18totalmem+"");
under18totalcash=under18totalcash+under18;
System.out.printf("\n\n\t %68s","The total amount of income for 'UNDER 18 MEMBERSHIPS' within the club = "+under18totalcash+"");
//allowing user to select '0' to add another member or any other key to exit program
System.out.printf("\n\n\t %68s","Please Press '0' to add another member or any other key to exit.: ");
addmember=key.nextInt();
}while (addmember==0 ||addmember>1);}}
the problem im having is whenever i make the choices 1,2,3,4 (CATEgorys) AND hit 1 or 2(current or new member selections) it brings up more than one category...
for example when i hit 1(Category full) and 1(current member)..it displays this:
Are you a Current Member (press 1) or a New Member (press 2): 1
CURRENT FULL MEMBERSHIP SELECTED
Current full membership fees yearly are 800
Full members must also pre-pay 150 on a card can be used in the club facilities such as bar and shop
The total of this membership is: 800
The total number of 'CURRENT FULL MEMBERSHIPS = 1
The total amount of income for 'FULL MEMBERSHIPS' within the club = 800
The total of this membership is: 175
The total number of 'UNDER 18 MEMBERSHIPS' within the club = 1
The total amount of income for 'UNDER 18 MEMBERSHIPS' within the club = 175
Please Press '0' to add another member or any other key to exit.:
under 18 membership as well?...does this for other selections too...is it my arithmetic operators?....my if loops?...Multi-post [http://forums.sun.com/thread.jspa?threadID=5346248&messageID=10498270#10498270]
And it still doesn't compile. -
Importing XML into Java. Help needed Please!!!
Hi,
I have downloaded j2sdk1.4.1_05 and want to configure it to import XML files into a DOM in Java. I am having trouble doing this and need help. I read that version 1.4 support JAXP 1.1 but I am having trouble finding the JAXP-api.jar file. It says to put all the other Jar files into a folder and leave the JAXP-api.jar.
Could you please tell me how to set up Java so that I can import an XML file. I also downloaded JAXP 1.2. But there seems to be no installer.
Thanx JohnYou can learn about reading xml in java by reading the J2EE tutorial at
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/
Here is sample program to read XML file into a DOM taken from this tutorial
(http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html)
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMException;
import java.io.*;
public class TransformationApp
static Document document;
public static void main(String argv[])
if (argv.length != 1) {
System.err.println (
"Usage: java TransformationApp filename");
System.exit (1);
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
//factory.setNamespaceAware(true);
//factory.setValidating(true);
try {
File f = new File(argv[0]);
DocumentBuilder builder =
factory.newDocumentBuilder();
document = builder.parse(f);
} catch (SAXParseException spe) {
// Error generated by the parser
System.out.println("\n** Parsing error"
+ ", line " + spe.getLineNumber()
+ ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage() );
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
} // main
} If you have java 1.4 sdk installed everything should compile and run. Separate
JAXP package is nor required - JAXP is included in rt.jar in java-home-directory/jre/lib. -
Psuedocode to java.. help needed
this is the start of psuedocode i need to convert into java:
Roll a 12 sided die to choose a number in the range 1.....12
While the user has not made an incorrect guess
Ask the uer to guess whether they think the next number will be higher
or lower
it goes on to other topics but i was just wondering if anyone knew how
to begin, especially the prediction or random output of a number by the
computer..
if anyone can help then that'd be great, thank you
stevehey again, cheers for the hint.. i have been working hard on a simpler program and have only one error surround the 'if' statement.. how does this look to you?? i can't find the error however.
import java.util.Scanner;
public class dice
public static void main (String [] args)
Scanner in = new Scanner(System.in);
Random rnd = new Random();
int r = rnd.nextInt(12) + 1;
System.out.print("guess a number ");
int x = in.nextInt();
while (x != r);
System.out.print("Guess incorrect, choose hi or low ");
int hi = in.nextInt();
int low = in.nextInt();
if
(hi > r); {
System.out.print("correct ");
if (low < r);
System.out.print("correct ");
else
System.out.print("spot on! ")
}
Maybe you are looking for
-
Automator problem parsing variable as filename in disc image
Dear apple/automator forum. I have just recently started using Automator, and i am experiencing a little problem which im hoping to get a helping hand with. First, heres my screenshot (sorry its in danish, ill explain what iwe done): www.bergsorensen
-
Groups functionality in BPEL humal workflow not work for Third party LDAP
Hi, Oracle Virtual Directory(OVD) configured as third party LDAP was integrated with BPEL human worklist and corresponding tasks were assigned to a particular group using the human task editor. When the members in the group as present in OVD logged i
-
my i pad has stopped at ''connect to i tunes'' screen and it is not going further what to next. please help me. Rajasekhar
-
Today suddenly our one UNIX server containing the one node of Oracle 10g database cluster Got reboot, after that hard reboot when the server started and I try to start that node it is showing the following error SQL> startup ORA-29702: error occurred
-
Hi All, I want to use GMAP or any sort of map in webi report. Is this possible to make webi report interactive?? I dont want to use Xcelsius 2008. Please suggest possible solution. Environment is BO XI 3.1 SP3