File Encryption: New to Java encryption plz help
ive been looking at some code i got from a friends java book about how to encode/decode stuff. It seems to me that the key that is generated would be a one time thing and you would get a new one the next time you tried. If that happened i would think at least you would not decode the text correctly that had previosly been encoded by a different key. Plz point out another example for what im trying to do if this one is doing something else which it seems to me it must be. Or if not plz explain how it works. Thanks for youre time.
heres the code ive been looking at to learn how to encode/decode files for a game ive been working on:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.awt.*;
import java.util.*;
public class TestCipher{
public static void main(String args[]) throws Exception {
Set set = new HashSet();
System.out.println("Enter password\nMust contain at least 8 characters");
BufferedReader first = new BufferedReader(new
InputStreamReader(System.in));
//password must be at leaste 8 charaacters
//private static final
String password = "uuuuuuuu";
password = first.readLine();
Random random = new Random();
for (int i=0; i<10; i++){
Point point = new Point(random.nextInt(1000), random.nextInt(2000));
set.add(point);
int last = random.nextInt(5000);
//create key
byte key[] = password.getBytes();
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
//create Cipher
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
//create Stream
FileOutputStream fos = new FileOutputStream("out.des");
BufferedOutputStream bos = new BufferedOutputStream(fos);
CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
ObjectOutputStream oos = new ObjectOutputStream(cos);
//write objects
oos.writeObject(set);
oos.writeInt(last);
oos.flush();
oos.close();
//change Cipher Mode
desCipher.init(Cipher.DECRYPT_MODE, secretKey);
//Create Stream
FileInputStream fis = new FileInputStream("out.des");
BufferedInputStream bis = new BufferedInputStream(fis);
CipherInputStream cis = new CipherInputStream(bis, desCipher);
ObjectInputStream ois = new ObjectInputStream(cis);
//read objects
Set set2 = (Set)ois.readObject();
int last2 = ois.readInt();
ois.close();
//compare original with what is read back
int count = 0;
if (set.equals(set2)){
System.out.println("Set1:" + set);
System.out.println("Set2:" + set2);
System.out.println("Sets are okay.");
count++;
if (last == last2){
System.out.println("int1:" + last);
System.out.println("int2:" + last2);
System.out.println("ints are okay.");
count++;
if (count != 2){
System.out.println("Problem during encryption/decryption");
You can use EnvelopedDataGenerator from BC library.
FileInputStream src = new FileInputStream(inputFile); // File to encrypt
byte[] data = new byte[src.available()];
src.read(data);
src.close();
CMSEnvelopedDataGenerator dataGenerator =new CMSEnvelopedDataGenerator();
dataGenerator.addKeyTransRecipient(getPersonalCertificate()); // add personal certificate
// OPTIONAL add other recipients certificates who can decode
dataGenerator.addKeyTransRecipient(cert1);
CMSProcessableByteArray byteArray =new CMSProcessableByteArray(data);
CMSEnvelopedData envelopedData = dataGenerator.generate(byteArray, CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(envelopedData.getEncoded());
fos.close();
Similar Messages
-
hi when i open my application folder, all the application is shown in trash folder. when i click the application it says this app is in trash first move it out. and when i try to open through finder> go it says this file doesn't exist. can some1 plz help? how can i put all my application through application folder?
Something really odd is going on. In your first screen shot, I noticed that the Applications folder does not have the proper icon displayed in the side bar. Also, in the title bar it lists it as Applications 08-59-29-909.
Not sure where it's picking up that odd name, unless it's because it's still truly within the Trash folder.
Try this. In the Finder > Preferences > General > turn on "Always open folders in a new window". (I have a feeling you have the default setting with this off).
Now, in Finder > Go > move down and open the Applications Folder from there. Now open the folder where you see all your applications that you show in your screen shot, select all, and move them to this true appliactions folder.
This is what you should properly seeing (but with different apps listed):
See how the Applications folder has the icon of the letter A shaped with a pencil, ruler & pen. -
i have apple iphone 4 32gb orange,currently i m india,and unable to use indian sim,and i have updated it to new ios6,can u plz help me out
Select the country in which the iPhone was originally sold:
http://support.apple.com/kb/HT1937
You'll find a link to the carrier on whose pages you can probably find contact information.
As RG said, only the carrier to which the iPhone is locked can authorize unlocking. That is the only "way out". To have an iPhone that was "factory unlocked", you would have had to purchase it that way.
Regards. -
New to java looking for help.
I m using mysql n linux RH 8.my data is like this as shown below
Ticketing(my table name)
=======================
remarks(Field name)
Now what I m looking for is I retrieve the value from remarks and that
value I want to scroll below the web page.I manage to retrieve the value but don't know how to scroll below the web page plz help .
Thanx in advanceYou could use a classic javascript for this. There are lots of javascript forums on the net, they could help you out. The main problem is that you have to put your DB password in the script. This is not a very safe solution.
If your web server supports JSP, use it. It's nice, easy and server side :)
http://java.sun.com/products/jsp/
Maybe writing an applet is the easiest solution. This way you have the best control on what is painted on screen and, more importantly, you don't have to show your passwords.
http://java.sun.com/docs/books/tutorial/applet/index.html -
New to Java and need help with this program..please!
I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
The assignment requirements are:
1. Change a card game application that draws two cards
and the higher card wins, to a Blackjack application
2. Include a new class called Hand
3. The Hand class should record the number of draws
4. The application should prompt for a number of draws
5. The game is played against the Dealer
6. The dealer always draws a card if the dealer's hand total is <= 17
7. Prompt the player after each hand if he wants to quit
8. Display the total games won by the dealer and total and the total games wond by the player after each hand
9. Display all of the dealer's and player's cards at the
end of each hand
10. Player has the option of drawing an additional card after the first two cards
11. The Ace can have a value of 11 or 1
(Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
The following is my code with some comments about a few things that are driving me nuts:
import java.util.*;
import javax.swing.*;
import java.text.*;
public class CardDeck
public CardDeck()
deck = new Card[52];
fill();
shuffle();
public void fill()
int i;
int j;
for (i = 1; i <= 13; i++)
for (j = 1; j <= 4; j++)
deck[4 * (i - 1) + j - 1] = new Card(i, j);
cards = 52;
public void shuffle()
int next;
for (next = 0; next < cards - 1; next++)
int rand = (int)(Math.random()*(next+1));
Card temp = deck[next];
deck[next] = deck[rand];
deck[rand] = temp;
public final Card draw()
if (cards == 0)
return null;
cards--;
return deck[cards];
public int changeValue()
int val = 0;
boolean ace = false;
int cds;
for (int i = 0; i < cards; i++)
if (cardValue > 10)
cardValue = 10;
if (cardValue ==1) {
ace = true;
val = val + cardValue;
if ( ace = true && val + 10 <= 21 )
val = val + 10;
return val;
public static void main(String[] args)
CardDeck d = new CardDeck();
int x = 3;
int i;
int wins = 1;
int playerTotal = 1;
do {
Card dealer = (d.draw());
/**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
System.out.println("Dealer draws: " + dealer);
do {
dealer = (d.draw());
System.out.println(" " + dealer);
}while (dealer.rank() <= 17);
Card mine = d.draw();
System.out.println("\t\t\t\t Player draws: "
+ mine);
mine = d.draw();
System.out.println("\t\t\t\t\t\t" + mine);
do{
String input = JOptionPane.showInputDialog
("Would you like a card? ");
if(input.equalsIgnoreCase("yes"))
mine = d.draw();
System.out.println("\t\t\t\t\t\t" + mine);
playerTotal++;
else if(input.equalsIgnoreCase("no"))
System.out.println("\t\t\t\t Player stands");
else
System.out.println("\t\tInvalid input.
Please try again.");
I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
if ((dealer.rank() > mine.rank())
&& (dealer.rank() <= 21)
|| (mine.rank() > 21)
&& (dealer.rank() < 22)
|| ((dealer.rank() == 21)
&& (mine.rank() == 21))
|| ((mine.rank() > 21)
&& (dealer.rank() <= 21)))
System.out.println("Dealer wins");
wins++;
else
System.out.println("I win!");
break;
} while (playerTotal <= 1);
String stop = JOptionPane.showInputDialog
("Would you like to play again? ");
if (stop.equalsIgnoreCase("no"))
break;
if (rounds == 5)
System.out.println("Player wins " +
(CardDeck.rounds - wins) + "rounds");
} while (rounds <= 5);
private Card[] deck;
private int cards;
public static int rounds = 1;
public int cardValue;
/**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
class Hand()
static int r = 1;
public Hand() { CardDeck.rounds = r; }
public int getRounds() { return r++; }
final class Card
public static final int ACE = 1;
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int CLUBS = 1;
public static final int DIAMONDS = 2;
public static final int HEARTS = 3;
public static final int SPADES = 4;
public Card(int v, int s)
value = v;
suit = s;
public int getValue() { return value; }
public int getSuit() { return suit; }
public int rank()
if (value == 1)
return 4 * 13 + suit;
else
return 4 * (value - 1) + suit;
/**This works, but I'm confused. How is this method called? Does it call itself?**/
public String toString()
String v;
String s;
if (value == ACE)
v = "Ace";
else if (value == JACK)
v = "Jack";
else if (value == QUEEN)
v = "Queen";
else if (value == KING)
v = "King";
else
v = String.valueOf(value);
if (suit == DIAMONDS)
s = "Diamonds";
else if (suit == HEARTS)
s = "Hearts";
else if (suit == SPADES)
s = "Spades";
else
s = "Clubs";
return v + " of " + s;
private int value; //Value is an integer, so how can a
private int suit; //string be assigned to an integer?
}Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
Card dealer = (d.changeValue());
I get an error message saying:
Incompatible types found: int
required: Card
I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated. -
I have use three free apple Id and now when I am creating a fourth time it's saying that it is the maximum. What must I do to create a new apple id. Plz help
Sorry, no way around this limitation on an iOS device. To use a new iCloud account, you need to create such on a computer first, then setup the account on your iOS device.
-
New to Java and need help with error message!
I have just installed the oracle jdbc driver and am now getting the following error message when trying to use the jbdc driver instead of the jdbc:odbc wrap driver...
See com.borland.dx.dataset.DataSetException error code: BASE+47
com.borland.dx.dataset.DataSetException: Chain of 2 or more Exceptions occurred
at com.borland.dx.dataset.DataSetException.a(Unknown Source)
at com.borland.dx.dataset.DataSetException.throwExceptionChain(Unknown Source)
at com.borland.dx.sql.dataset.q.a(Unknown Source)
at com.borland.dx.sql.dataset.Database.openConnection(Unknown Source)
at com.borland.dx.sql.dataset.Database.createPreparedStatement(Unknown Source)
at com.borland.dx.sql.dataset.o.a(Unknown Source)
at com.borland.dx.sql.dataset.o.d(Unknown Source)
at com.borland.dx.sql.dataset.o.f(Unknown Source)
at com.borland.dx.sql.dataset.QueryProvider.e(Unknown Source)
at com.borland.dx.sql.dataset.JdbcProvider.provideData(Unknown Source)
at com.borland.dx.dataset.StorageDataSet.a(Unknown Source)
at com.borland.dx.dataset.DataSet.a(Unknown Source)
at com.borland.dx.dataset.DataSet.open(Unknown Source)
at com.borland.dbswing.JdbTable.bindDataSet(JdbTable.java:2749)
at com.borland.dbswing.JdbTable.setDataSet(JdbTable.java:819)
at myframes.ClaimView.btnSQL_actionPerformed(ClaimView.java:279)
at myframes.ClaimView_btnSQL_actionAdapter.actionPerformed(ClaimView.java:440)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
at java.awt.Component.processMouseEvent(Component.java:5100)
at java.awt.Component.processEvent(Component.java:4897)
at java.awt.Container.processEvent(Container.java:1569)
at java.awt.Component.dispatchEventImpl(Component.java:3615)
at java.awt.Container.dispatchEventImpl(Container.java:1627)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
at java.awt.Container.dispatchEventImpl(Container.java:1613)
at java.awt.Window.dispatchEventImpl(Window.java:1606)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
Chained exception:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:640)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:243)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:280)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at com.borland.dx.sql.dataset.q.a(Unknown Source)
at com.borland.dx.sql.dataset.Database.openConnection(Unknown Source)
at com.borland.dx.sql.dataset.Database.createPreparedStatement(Unknown Source)
at com.borland.dx.sql.dataset.o.a(Unknown Source)
at com.borland.dx.sql.dataset.o.d(Unknown Source)
at com.borland.dx.sql.dataset.o.f(Unknown Source)
at com.borland.dx.sql.dataset.QueryProvider.e(Unknown Source)
at com.borland.dx.sql.dataset.JdbcProvider.provideData(Unknown Source)
at com.borland.dx.dataset.StorageDataSet.a(Unknown Source)
at com.borland.dx.dataset.DataSet.a(Unknown Source)
at com.borland.dx.dataset.DataSet.open(Unknown Source)
at com.borland.dbswing.JdbTable.bindDataSet(JdbTable.java:2749)
at com.borland.dbswing.JdbTable.setDataSet(JdbTable.java:819)
at myframes.ClaimView.btnSQL_actionPerformed(ClaimView.java:279)
at myframes.ClaimView_btnSQL_actionAdapter.actionPerformed(ClaimView.java:440)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
at java.awt.Component.processMouseEvent(Component.java:5100)
at java.awt.Component.processEvent(Component.java:4897)
at java.awt.Container.processEvent(Container.java:1569)
at java.awt.Component.dispatchEventImpl(Component.java:3615)
at java.awt.Container.dispatchEventImpl(Container.java:1627)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
at java.awt.Container.dispatchEventImpl(Container.java:1613)
at java.awt.Window.dispatchEventImpl(Window.java:1606)
at java.awt.Component.dispatchEvent(Component.java:3477)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
Here is the code causeing the error;
void btnSQL_actionPerformed(ActionEvent e)
try
String GET_DATASET = txtSQL.getText().trim();
Display("Executing...");
try
MyDisplayTable.setDataSet(null);
catch (DataSetException ex)
Display("ERROR 1: " + ex.toString());
try
queryDataSet1.close();
catch (DataSetException ex)
Display("ERROR 2: " + ex.toString());
try
queryDataSet1.setQuery(new com.borland.dx.sql.dataset.QueryDescriptor(
database1, GET_DATASET, null, true, Load.ALL));
catch (DataSetException ex)
Display("ERROR 3: " + ex.toString());
try
if (!queryDataSet1.isOpen()) {
queryDataSet1.open();
catch (DataSetException ex) {
Display("ERROR 5: " + ex.toString());
try {
queryDataSet1.refresh();
catch (Exception ex) {
Display("ERROR 5.5: " + ex.toString());
try {
Display("setDataSet");
MyDisplayTable.setDataSet(queryDataSet1);
Display("DONE setDataSet");
catch (DataSetException ex) {
Display("ERROR 6: " + ex.toString());
Display("Query: ' " + GET_DATASET.trim() + " ' was executed successfully");
catch (Exception ex)
Display(ex.toString());
Please let me know if more information is required. I am completely at a loss as to what more I need to do to get this to work using the new driver.
Thank you all in advance,
Malcolm Diaz
Application Developer
[email protected]
PlanVista Solutions Inc.
419 E.Main St.
Middletown NY 10940
845-346-2692this is more of a jdbc question rather than an internationalization. You might be able to get more help if you post it in java programming section.
-
I'm new to java and need help please
I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
item # description price(this line does not appear in the text file)
001 shaving cream 400.00
999 razors 30.00
I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
item# quant price per item total(price per item*quant entered)
also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
I've been working on this for days and it seems like nothing I try works. My major problems are:
1. I have no idea how to read the text file and load those 2 items into their respective arrays
2. I can't seem to create a textfile that looks like text for the output file.
code]
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.Locale;
public class arraySelection
extends JApplet {
//Initialize the applet
private Container getContentPane=null;
public void init() {
String string_item, string_quantity;
String output = "";
String description= "";
int counter= 0;
int itemNumber= 0;
double quantity = 0 ;
double tax_rate=.07;
double total= 0, price= 0;
double tax, subtotal;
double Pretotal= 0;
double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
// create number format for currency in US dollar format
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
//format to have the total with two digits precision
DecimalFormat twoDigits = new DecimalFormat("0.00");
//Jtextarea to display results
JTextArea outputArea = new JTextArea ();
// get applet's content pane
Container container = getContentPane ();
//attach output area to container
container.add(outputArea);
//set the first row of text for the output area
output += "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
do //begin loop structure obtain input from user
// obtain item number from user
string_item = JOptionPane.showInputDialog(
"Please enter an item number 1, 2, 3, 4, or 5:");
//obtain quantity of each item that user enter
string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
// convert numbers from type String to Integer or Double
itemNumber = Integer.parseInt(string_item);
quantity = Double.parseDouble(string_quantity);
switch (itemNumber) {//Determine input from user to assign price and description
case 10: // user input item =10
price = priceArray[0];
description = descriptionArray[0];
break;
case 20: // user input item =20
price = priceArray [1];
description = descriptionArray[1];
break;
case 30: //user input item =30
price=priceArray[2];
description = descriptionArray[2];
break;
case 40: //user input item =40
price=priceArray[3];
description = descriptionArray[3];
break;
case 50: //user input item =50
price=priceArray[4];
description = descriptionArray[4];
break;
default: // user input item is not on the list
output += "Invalid value entered"+ "\n";
price=0;
description= "";
//Calculates the total for each item number and stores it in subtotal
subtotal = price * quantity;
//display input from user
output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
//accumulates the overall subtotal for all items
Pretotal = Pretotal + subtotal;
//verifies that the user wants to stop entering data
string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
itemNumber = Integer.parseInt(string_item);
// loop termination condition if user's input is 0 .It will end the loop
} while ( itemNumber!= 0);
tax = Pretotal * tax_rate; // calculate tax amount
total = Pretotal + tax; //calculate total = subtotal + tax
//appends data regarding the subtotal, tax, and total to the output area
output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
"\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
"\t\t" + moneyFormat.format( total );
//attaches the data in the output variable to the output area
outputArea.setText( output );
} //end init
}// end applet Invoice
Any help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.item # description price(this
line does not appear in the text file)
001 shaving cream 400.00
999 razors 30.00
I need to load the item# and price from the text file
into arrays(I have no clue how to use
multi-dimensional arrays in java and would prefer not
to)That's good, because you shouldn't use multidimensional arrays here. You should have a one-dimensional array (or java.util.List) of objects that encapsulate each line.
I've been working on this for days and it seems like
nothing I try works. My major problems are:
1. I have no idea how to read the text file and load
those 2 items into their respective arrays
2. I can't seem to create a textfile that looks like
text for the output file.The java.io package has file reading/writing classes.
Here's a tutorial:
http://java.sun.com/docs/books/tutorial/essential/io/index.html -
I'm new to java and need help please(repost)
I have an assignment involves modifying a previous assignment. the code for the previous assigment is shown below.(it was required to be done as an applet this assigment can be an application or an applet) I'm trying to modify this code to read a text file (items.txt) that looks like this:
item # description price(this line does not appear in the text file)
001 shaving cream 400.00
999 razors 30.00
I need to load the item# and price from the text file into arrays(I have no clue how to use multi-dimensional arrays in java and would prefer not to)
I need to search the arrays based on the values entered by the user (item # and quantity) calculate the total for that item then create a new text file which has each line item for that order in the form:
item# quant price per item total(price per item*quant entered)
also also I need to be able to display the four items listed above after each loop as well as all the previous item number and quantities they selected until they indicate they don't want to select anymore.
I've been working on this for days and it seems like nothing I try works. My major problems are:
1. I have no idea how to read the text file and load those 2 items into their respective arrays
2. I can't seem to create a textfile that looks like text for the output file.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.Locale;
public class arraySelection
extends JApplet {
//Initialize the applet
private Container getContentPane=null;
public void init() {
String string_item, string_quantity;
String output = "";
String description= "";
int counter= 0;
int itemNumber= 0;
double quantity = 0 ;
double tax_rate=.07;
double total= 0, price= 0;
double tax, subtotal;
double Pretotal= 0;
double priceArray[] = {1, .5, 3.65, 0.02, 0.09};
String descriptionArray[] = {"salt", "pepper", "paprika", "garlic", "thyme"};
// create number format for currency in US dollar format
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US );
//format to have the total with two digits precision
DecimalFormat twoDigits = new DecimalFormat("0.00");
//Jtextarea to display results
JTextArea outputArea = new JTextArea ();
// get applet's content pane
Container container = getContentPane ();
//attach output area to container
container.add(outputArea);
//set the first row of text for the output area
output += "Invoice\nItem#\tDescription\tQuant@Price\t Line Total" + "\n";
do //begin loop structure obtain input from user
// obtain item number from user
string_item = JOptionPane.showInputDialog(
"Please enter an item number 1, 2, 3, 4, or 5:");
//obtain quantity of each item that user enter
string_quantity = JOptionPane.showInputDialog("Enter the quantity:");
// convert numbers from type String to Integer or Double
itemNumber = Integer.parseInt(string_item);
quantity = Double.parseDouble(string_quantity);
switch (itemNumber) {//Determine input from user to assign price and description
case 10: // user input item =10
price = priceArray[0];
description = descriptionArray[0];
break;
case 20: // user input item =20
price = priceArray [1];
description = descriptionArray[1];
break;
case 30: //user input item =30
price=priceArray[2];
description = descriptionArray[2];
break;
case 40: //user input item =40
price=priceArray[3];
description = descriptionArray[3];
break;
case 50: //user input item =50
price=priceArray[4];
description = descriptionArray[4];
break;
default: // user input item is not on the list
output += "Invalid value entered"+ "\n";
price=0;
description= "";
//Calculates the total for each item number and stores it in subtotal
subtotal = price * quantity;
//display input from user
output += itemNumber + "\t" + description + "\t\t"+ quantity + "@" +
moneyFormat.format( price) + "\t" + moneyFormat.format( subtotal) + "\n";
//accumulates the overall subtotal for all items
Pretotal = Pretotal + subtotal;
//verifies that the user wants to stop entering data
string_item = JOptionPane.showInputDialog(" Enter a positive integer to continue or 0 to stop. ");
itemNumber = Integer.parseInt(string_item);
// loop termination condition if user's input is 0 .It will end the loop
} while ( itemNumber!= 0);
tax = Pretotal * tax_rate; // calculate tax amount
total = Pretotal + tax; //calculate total = subtotal + tax
//appends data regarding the subtotal, tax, and total to the output area
output += "\n" + "Order Subtotal" + "\t" + moneyFormat.format( Pretotal) +
"\n" + "Tax" + "\t\t" + twoDigits.format( tax ) + "\n" + "Order Total" +
"\t\t" + moneyFormat.format( total );
//attaches the data in the output variable to the output area
outputArea.setText( output );
} //end init
}// end applet InvoiceAny help or sugestions would be greatly appreaciated. I've been working on this for over a week and everything I try goes nowhere.First answer: You shouldn't ask multiple questions in the same thread. Ask a specific question, with an appropriate subject line (optionally, assign the number of Dukes you are willing to give for the help). When question #1 is answered and question #2 arises, it's time for a new thread (don't forget to give out Dukes before moving on).
Second answer: I think you need a Transfer Object (http://java.sun.com/blueprints/patterns/TransferObject.html). It's whole purpose is to hold/transfer instance data where it is needed. Create a class something like this:
public class ItemTO
private String _number;
private String _description;
private double _price;
public ItemTO( String number, String description, double price )
_number = number;
_description = description;
_price = price
// Getter/Setter methods go here
}then, in the code where you read in the file do something like this:
BufferedReader input = null;
try
input = new BufferedReader( new FileReader( "c:\\a.txt" ) );
List items = new ArrayList();
String line;
String itemNumber;
String itemDescription;
double itemPrice;
while ( (line = input.readLine() ) != null )
System.out.println( line );
itemNumber = // Parse it from line
itemDescription // Parse it from line
itemPrice = // Parse it from line
items.add( new ItemTO( itemNumber, itemDescription, itemPrice ) );
catch ( FileNotFoundException fnfe )
fnfe.printStackTrace();
catch ( IOException ioe )
ioe.printStackTrace();
finally
try
if ( input != null )
input.close();
catch ( Exception e )
e.printStackTrace();
}As for how to parse the line of the file, I'll leave that to you for now. Are the three values delimited with any special characters?
jbisotti -
New macbook pro problem, plz help
hey everyone.i just bought the new macbook pro last week, 15" i7core 2ghz. i am a very serious musician, and im going going to university next year to study music, the whole reason i bought this computer is for recording, all the musicians i know who are serious/professionals use macs. when i first turn on my computer everything is fine, but once i plug my guitar in through my zoom g2.1u pedal, garageband freezes and i have to force quit it, this just started happening within the past 2 days.for the first week i recorded with it fine. it was also happening yesterday without even plugging in my guitar at all. when this happens the internet also shuts down. when i open safari it doesnt say you are not conncted to the internet, it just has a blank white page. when this happens everything else isnt working right either, everything is slow and laggy. i paid alot of friggin money for this thing and i wanted to keep it clean the only things ive done to it were, i took some mp3, pdf and guitar pro files from my old windows xp onto my mac through a usb stick, downloaded a mp3 from online and set a cool backround as my desktop. I thought macs were supposed to be resilient? or do i just have a defective one. these problems are quite specific but if i cant use garageband/record with my mac theres not a rly a point of me having one.
i hope someone can help me out here.Try here:
https://discussions.apple.com/community/ilife/garageband -
Not able to open excel file in new window any one plese help me as early
Hi all,
I have a imag tag in jsp on click on the image i am submitting the form
1. i have used the below code
HSSFWorkbook wb=viewHelper.getExcel();
response.reset();
ServletOutputStream outs = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.addHeader("Pragma", "No-cache");
response.addHeader("Cache-control", "no-cache");
response.addDateHeader("Expires",1 );
wb.write(outs);
outs.flush();
outs.close();
return;
2. I got one dialog box to open ,save,cancel . if i try to open it is openeing in the same window i had made the request. i need it to ask for in which type of application to open. i.e, in excel , notepad,.....
please mail me as soon as possible
[email protected]I had a similar porblem....
I got some help from...http://www.javaworld.com/javaworld/jw-10-2006/jw-1019-xmlexcel.html?page=1...
This is my code in servlet...
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet spreadSheet = wb.createSheet("Users");
spreadSheet.setColumnWidth((short) 0, (short) (256 * 25));
spreadSheet.setColumnWidth((short) 1, (short) (256 * 25));
// Creating Rows
HSSFRow row = spreadSheet.createRow(0);
HSSFCell cell = row.createCell((short) 1);
cell.setCellValue("Year 2005");
cell = row.createCell((short) 2);
cell.setCellValue("Year 2004");
HSSFRow row1 = spreadSheet.createRow(1);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
cell = row1.createCell((short) 0);
cell.setCellValue("Revenue ($)");
cell = row1.createCell((short) 1);
cell.setCellValue("25656");
cell = row1.createCell((short) 2);
cell.setCellValue("15457");
FileOutputStream output = new FileOutputStream(new File("/tmp/Users.xls"));
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=Users.xls");
ServletOutputStream out = response.getOutputStream();
wb.write(output);
output.flush();
output.close();
forward = null;
In firefox i get the download dialog box but not able to open in from there,i need to save it and then open. In IE i dont get the dialog box instead the excell open inside the browser......Please help me to open a excel sheet onclick on a link "Export to excel" in jsp......
Thanks in advance... -
Exceptions in QuickTimes for JAVA examples - plz help!
Hello,
I have a problem with the QuickTime for JAVA Applet Demos.
I set the correct CLASSPATH and the examples with the Frames are working fine. The Compilation of the Applet examples also works.
set CLASSPATH=C:\Programs\Java\j2re1.4.2_02\lib\ext\QTJava.zip;.
javac -classpath C:\Programs\Java\j2re1.4.2_02\lib\ext\QTJava.zip;. QTSimpleApplet.java
But when I want to run and test them with the Internet Explorer or SUNs appletviewer an
Exception is thrown (NoClassDefFoundError) and an error message appears in the appletviewer / browser: "Applet could not be initialized".
java.lang.NoClassDefFoundError: quicktime/QTException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:1610)
at java.lang.Class.getConstructor0(Class.java:1922)
at java.lang.Class.newInstance0(Class.java:278)
at java.lang.Class.newInstance(Class.java:261)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:617)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:546)
at sun.applet.AppletPanel.run(AppletPanel.java:298)
at java.lang.Thread.run(Thread.java:534)
When I copy the extracted QTJava.zip to the directory where the source file and the class file for the example are located an other Exception is thrown (ExceptionInInitializerError). :-( This Except. is caused by the security.
java.lang.ExceptionInInitializerError
at quicktime.jdirect.QTNative.loadQT(QTNative.java:33)
at quicktime.jdirect.QuickTimeLib.<clinit>(QuickTimeLib.java:17)
at quicktime.QTSession.<clinit>(QTSession.java:82)
at QTSimpleApplet.init(QTSimpleApplet.java:34)
at sun.applet.AppletPanel.run(AppletPanel.java:353)
at java.lang.Thread.run(Thread.java:534)
Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.QTJava)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:269)
at java.security.AccessController.checkPermission(AccessController.java:401)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:524)
at java.lang.SecurityManager.checkLink(SecurityManager.java:810)
at java.lang.Runtime.loadLibrary0(Runtime.java:782)
at java.lang.System.loadLibrary(System.java:834)
at quicktime.jdirect.JDirectLinker$1.run(JDirectLinker.java:266)
at java.security.AccessController.doPrivileged(Native Method)
at quicktime.jdirect.JDirectLinker$1$PrivelegedAction.establish(JDirectLinker.java:264)
at quicktime.jdirect.JDirectLinker.<clinit>(JDirectLinker.java:272)
... 6 more
How can I solve these problems? I just want to view some movies in an applet!
Please help me. Thanks in advance!Hi
I also has similar problem using the QuickTime using via Applet.
When I connect QuickTime via Applet, I have the error message
Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.QTJava)
I know that
this error is caused by the Java security "sandbox" for Plug-in.
Plug-in has restrictions for unsigned applets..and
I can use the QuickTime via Applet, if did manual editing of the java.policy file in the JRE.
( grant { permission java.security.AllPermission; } )
But editing of the java.policy file is discouraged...
My question is why loadLibrary.QTJava has restrictions for unsigned applets??
and how can I use QuickTime via Applet without manual editing of the java.policy??
Please give me some advice. -
Itunes/Quicktime new update authorization problems plz help
Ive used Itunes and Quicktime for years with no problems. So a week ago I download the newest Itunes version, and from then on I couldnt open it, I attempted the quicktime update but this message would always appear. "The installer has insufficient privileges to access directory C:/ProgramFiles/Quicktime/PictureViewer.Resources/da.lproj. Installation cannot continue. Log on as admin."
I have checked other posts out and I have tried completely reinstalling itunes and quicktime, then reinstalling together and seperatly, everytime the exact same message pops up. I have tried right clicking on the install links as "run as admin" Ive tried all I know of, I know im admin and the only account on computer.. Ive tried opening the actual files and changing them as the they are stuck as "read only" files, but again you cannot change them. Only thing ive thought of that havent tried is deleting all those quicktime folders in program files, which I dont understand why they are even there still since at the moment quicktime is not even installed?
Would greatly appreciate any help or pointing me in the right direction! Cant listen to music and I even just got a new 16g ipod that I cant even use yet either :X thanks for your time"The installer has insufficient privileges to access directory C:/ProgramFiles/Quicktime/PictureViewer.Resources/da.lproj. Installation cannot continue. Log on as admin."
That one is consistent with disk/file damage, Boarder.
Try running a disk check over your C Drive as per the following document. (Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors.)
[Check your hard disk for errors|http://windows.microsoft.com/en-us/windows-vista/Check-your-hard-disk-fo r-errors]
Does the disk check find/repair any errors? If so, try another QuickTime install. Does it go through properly this time? If it does go through properly, does your iTunes start to launch again? -
I am new to java and need help to
how can i read a class-file
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Capitalizeapplet extends Applet {
private TextField input;
private TextField output;
public void init() {
input = new TextField(40);
output = new TextField(40);
output.setEditable(true);
Button b= new Button("Capitalize");
this.add(input);
this.add(b);
this.add(output);
CapitalizerAction ca=new CapitalizerAction(input,output);
b.addActionListener(ca);
this.input.addActionListener(ca);
class CapitalizerAction implements ActionListener
private TextField in;
private TextField out;
public CapitalizerAction(TextField in,TextField out)
this.in=in;
this.out=out;
public void actionPerformed(ActionEvent ae)
String s=in.getText();
out.setText(s.toUpperCase());
at any time man, we are in service
(it's my first time to answer someone, coz I'm biggener exactly like u!...but I took that lesson ;) -
Please I'm new to java.Can anyone help me?
Whenever i try to execute a java program
at the command line I get the error message " .classfiles not found.I checked in my directory and the classfiles are there.I made sure I'm in the directory when i'm trying to execute the .class files.
when i use EditPlus i get the error message of
---------- java ----------
java.lang.NoClassDefFoundError: Comparison
Exception in thread "main" Normal Termination
Output completed (1 sec consumed).
Can anyone tell what i'm doing wrong or what i'm not doing?From Julesh1
To: DaithiMcGibon and ehsan java
Thank you very much i added the ";." and now i can execute the any code.
Your assistance is greatly appreciated.
I'm using windows 2000 Pro; jdk1.3.1_01; and apache tomcat 4.0.
But whenever i try to start apache tomcat i get a number of errors.
I have copied these errors from the command windows and pasted them below because i don't know where to begin.Does anyone think i should reinstall apache tomcat 4.0
Please take a look, here below are the error messages i'm getting.
A nonfatal internal JIT (3.10.107(x)) error 'Relocation error: NULL relocation target' has occurred in :
'org/apache/crimson/parser/Parser2.maybeComment (Z)Z': Interpreting method.
Please report this error in detail to http://java.sun.com/cgi-bin/bugreport.cgi
Catalina.start: LifecycleException: null.open: java.net.BindException: Address in use: bind
LifecycleException: null.open: java.net.BindException: Address in use: bind
at org.apache.catalina.connector.http.HttpConnector.initialize(HttpConnector.java:1116)
at org.apache.catalina.core.StandardService.initialize(StandardService.java, Compiled Code)
at org.apache.catalina.core.StandardServer.initialize(StandardServer.java, Compiled Code)
at org.apache.catalina.startup.Catalina.start(Catalina.java:775)
at org.apache.catalina.startup.Catalina.execute(Catalina.java:681)
at org.apache.catalina.startup.Catalina.process(Catalina.java:179)
at java.lang.reflect.Method.invoke(Native Method)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java, Compiled Code)
----- Root Cause -----
java.net.BindException: Address in use: bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at org.apache.catalina.net.DefaultServerSocketFactory.createSocket(DefaultServerSocketFactory.java:118)
at org.apache.catalina.connector.http.HttpConnector.open(HttpConnector.java:946)
at org.apache.catalina.connector.http.HttpConnector.initialize(HttpConnector.java:1114)
at org.apache.catalina.core.StandardService.initialize(StandardService.java, Compiled Code)
at org.apache.catalina.core.StandardServer.initialize(StandardServer.java, Compiled Code)
at org.apache.catalina.startup.Catalina.start(Catalina.java:775)
at org.apache.catalina.startup.Catalina.execute(Catalina.java:681)
at org.apache.catalina.startup.Catalina.process(Catalina.java:179)
at java.lang.reflect.Method.invoke(Native Method)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java, Compiled Code)
Maybe you are looking for
-
How to create a invoice with invoice items in SRM?
Hi experts, I am testing my BW custom code for SRM. My question is I have to create a invoice with line item 1 quantiy 20 in SRM - development. After this I have mark line item 1 with a deletion indicator X in SRM and create two more line items and l
-
Hard drive crashed and had to replace drive and logic board on my MacBook pro. After Install tried to sync with my iPhone and a dialog box pops up stating "this iPhone synced with another iTunes library, erase and sync?". I checked the manually man
-
hi friends.. I am very new to ODI. Can any one please tell me how to work with packages and what is its function and how packages work??? soumya.
-
I've got a form application which has typical fields for data entry, ref number, name, address etc.....up to ten items. I have a Main Menu form, four other forms, and can move between them fine. This is a cut down example, with only one text field, o
-
Hi, My Vmserver has crahed. I reinstall the VM Server Copied the img file to OVS/running_pool. What should i do in the Vm manager to up the virtual machine. My serverpool is inactive. Before crashing i have done a proper shutdown of my virtual machin