Help with a simple program (asap please!)
I'm writing a program that assumes a user will input 4 positive integers, and outputs them in order from smallest to largest. For example... when inputting 3,5,2,6 - the program will output 2,3,5,6. I've gotten the smallest and largest figured out, but I am having trouble getting the middle two. Oh, there's a catch, only if, switch, else. Here is what I've written so far:
package chapter4homework;
import javax.swing.JOptionPane;
public class C4E8 {
public static void main(String[] args) {
String response = null;
int response1 = 0;
int response2 = 0;
int response3 = 0;
int response4 = 0;
int tempdigit1 = 0;
int tempdigit2 = 0;
int digit1 = 0;
int digit2 = 0;
int digit3 = 0;
int digit4 = 0;
response = JOptionPane.showInputDialog("Enter a positive integer:");
response1 = Integer.parseInt(response);
response = JOptionPane.showInputDialog("Enter a second positive integer:");
response2 = Integer.parseInt(response);
response = JOptionPane.showInputDialog("Enter a third positive integer:");
response3 = Integer.parseInt(response);
response = JOptionPane.showInputDialog("Enter a third positive integer:");
response4 = Integer.parseInt(response);
//Beginning of finding the highest positive integer
if (response1>response2 & response1>response3 & response1>response4)
digit4 = response1;
if (response2>response1 & response2>response3 & response2>response4)
digit4 = response2;
if (response3>response1 & response3>response2 & response3>response4)
digit4 = response3;
if (response4>response1 & response4>response2 & response4>response3)
digit4 = response4;
//End of finding the highest positive integer
//Beginning of finding the lowest positive integer
if (response1<response2 & response1<response3 & response1<response4)
digit1 = response1;
if (response2<response1 & response2<response3 & response2<response4)
digit1 = response2;
if (response3<response1 & response3<response2 & response3<response4)
digit1 = response3;
if (response4<response1 & response4<response2 & response4<response3)
digit1 = response4;
//End of finding the lowest positive integer
//Beginning of finding the second highest positive integer (no idea if this is right)
if (response1>digit1 & response1<digit4)
tempdigit1=response1;
if (response2>digit1 & response2<digit4)
tempdigit1=response2;
if (response3>digit1 & response3<digit4)
tempdigit1=response3;
if (response4>digit1 & response4<digit4)
tempdigit1=response4;
if (response1>digit1 & response1<digit4)
tempdigit2=response1;
if (response2>digit1 & response2<digit4)
tempdigit2=response2;
if (response3>digit1 & response3<digit4)
tempdigit2=response3;
if (response4>digit1 & response4<digit4)
tempdigit2=response4;
if (tempdigit1<tempdigit2){
digit2=tempdigit1;
System.out.println(digit1);
System.out.println(digit2);
System.out.println(digit3);
System.out.println(digit4);
}
DeLorean wrote:
Thank you for replying, unfortunately, I am in the second week of a basic programming class, and I have no idea what you mean by recursion, or how to apply it using these simple statements.Hmm, then maybe they're trying to get you to do it the simplistic but hard way, in order to show you the advantages of doing it the proper way...
Regarding the bubble sort, think of it this way: You have four numbers, and you can sort them in three "passes"
First pass: Starting from the fourth number, keep comparing to the previous number and swapping if it is smaller. By the end of this pass, the smallest number will have bubbled to the bottom. This will take three comparison/swap operations.
Second pass: Again, starting from the fourth number, keep comparing to the previous number and swapping if it is smaller. You will stop after comparing the second and third number, because the first number will already hold the smallest number. This will take two comparison/swaps.
Third pass: Same as before, just one less comparison/swap.
And you're done.
Similar Messages
-
Help with a simple program.
I need some help writing a simple program. Can anybody help??
thanks to all.
2. HTML Java Source Code Reserved Word Highlighter
Write a program that inputs a Java source code file and outputs a copy of that file with Java keywords surrounded with HTML tags for bold type. For example this input:
public class JavaSource
public static void main ( String[] args )
if ( args.length == 3 )
new BigObject();
else
System.out.println("Too few arguments.");
will be transformed into:
<B>public</B> <B>class</B> JavaSource
<B>public</B> <B>static</B> <B>void</B> main ( String[] args )
<B>if</B> ( args.length == 3 )
<B>new</B> BigObject();
<B>else</B>
System.out.println("Too few arguments.");
In a browser the code will look like this:
public class JavaSource
public static void main ( String[] args )
if ( args.length == 3 )
new BigObject();
else
System.out.println("Too few arguments.");Here is something that may get you started...
import java.io.*;
import java.util.*;
public class HtmlJava{
public static void main(String arg[]){
if(arg.length!=1){
System.out.println("Usage java HtmlJava sourceFile");
else
new HtmlJava(arg[0]);
HtmlJava(String source){
try{
BufferedReader sourceReader=new BufferedReader(new InputStreamReader(new FileInputStream(source)));
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source+"Html.txt")));
Vector keywords=new Vector();
addKeywords(keywords);
String line;
StringTokenizer tokenizer=null;
String word;
while((line=sourceReader.readLine () )!=null){
tokenizer=new StringTokenizer(line);
while(tokenizer.hasMoreTokens()){
word=tokenizer.nextToken();
if(keywords.contains(word)){
writer.write(""+word+" ");
else{
writer.write(word+" ");
writer.write("\r\n");
writer.close();
sourceReader.close();
System.out.println("Output File written to "+source+"Html.txt");
catch(Exception ex){
ex.printStackTrace();
private void addKeywords(Vector keywords){
keywords.addElement ( "abstract");
keywords.addElement( "boolean");
keywords.addElement( "break");
keywords.addElement( "byte");
keywords.addElement( "byvalue");
keywords.addElement( "case");
keywords.addElement( "cast");
keywords.addElement( "catch");
keywords.addElement( "char");
keywords.addElement( "class");
keywords.addElement( "const");
keywords.addElement( "continue");
keywords.addElement( "default");
keywords.addElement( "do");
keywords.addElement( "double");
keywords.addElement( "else");
keywords.addElement( "extends");
keywords.addElement( "false");
keywords.addElement( "final");
keywords.addElement( "finally");
keywords.addElement( "float");
keywords.addElement( "for");
keywords.addElement( "future");
keywords.addElement( "generic");
keywords.addElement( "goto");
keywords.addElement( "if");
keywords.addElement( "implements");
keywords.addElement( "import");
keywords.addElement( "inner");
keywords.addElement( "instanceof");
keywords.addElement( "int");
keywords.addElement( "interface");
keywords.addElement( "long");
keywords.addElement( "native");
keywords.addElement( "new");
keywords.addElement( "null");
keywords.addElement( "operator");
keywords.addElement( "outer");
keywords.addElement( "package");
keywords.addElement( "private");
keywords.addElement( "protected");
keywords.addElement( "public");
keywords.addElement( "rest");
keywords.addElement( "return");
keywords.addElement( "short");
keywords.addElement( "static");
keywords.addElement( "super");
keywords.addElement( "switch");
keywords.addElement( "synchronized");
keywords.addElement( "this");
keywords.addElement( "throw");
keywords.addElement( "throws");
keywords.addElement( "transient");
keywords.addElement( "true");
keywords.addElement( "try");
keywords.addElement( "var");
keywords.addElement( "void");
keywords.addElement( "volatile");
keywords.addElement( "while");
}Hope it helped -
Need help with a simple program (should be simple anyway)
I'm (starting to begin) writing a nice simple program that should be easy however I'm stuck on how to make the "New" button in the file menu clear all the fields. Any help? I'll attach the code below.
====================================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Message extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent evt) {
text1.setText(" ");
text2.setText("RE: ");
text3.setText(" ");
public Message() {
super("Write a Message - by Kieran Hannigan");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(370,270);
FlowLayout flo = new FlowLayout(FlowLayout.RIGHT);
setLayout(flo);
//Make the bar
JMenuBar bar = new JMenuBar();
//Make "File" on Menu
JMenu File = new JMenu("File");
JMenuItem f1 = new JMenuItem("New");f1.addActionListener(this);
JMenuItem f2 = new JMenuItem("Open");
JMenuItem f3 = new JMenuItem("Save");
JMenuItem f4 = new JMenuItem("Save As");
JMenuItem f5 = new JMenuItem("Exit");
File.add(f1);
File.add(f2);
File.add(f3);
File.add(f4);
File.add(f5);
bar.add(File);
//Make "Edit" on menu
JMenu Edit = new JMenu("Edit");
JMenuItem e1 = new JMenuItem("Cut");
JMenuItem e2 = new JMenuItem("Paste");
JMenuItem e3 = new JMenuItem("Copy");
JMenuItem e4 = new JMenuItem("Repeat");
JMenuItem e5 = new JMenuItem("Undo");
Edit.add(e5);
Edit.add(e4);
Edit.add(e1);
Edit.add(e3);
Edit.add(e2);
bar.add(Edit);
//Make "View" on menu
JMenu View = new JMenu("View");
JMenuItem v1 = new JMenuItem("Bold");
JMenuItem v2 = new JMenuItem("Italic");
JMenuItem v3 = new JMenuItem("Normal");
JMenuItem v4 = new JMenuItem("Bold-Italic");
View.add(v1);
View.add(v2);
View.add(v3);
View.addSeparator();
View.add(v4);
bar.add(View);
//Make "Help" on menu
JMenu Help = new JMenu("Help");
JMenuItem h1 = new JMenuItem("Help Online");
JMenuItem h2 = new JMenuItem("E-mail Programmer");
Help.add(h1);
Help.add(h2);
bar.add(Help);
setJMenuBar(bar);
//Make Contents of window.
//Make "Subject" text field
JPanel row2 = new JPanel();
JLabel sublabel = new JLabel("Subject:");
row2.add(sublabel);
JTextField text2 = new JTextField("RE:",24);
row2.add(text2);
//Make "To" text field
JPanel row1 = new JPanel();
JLabel tolabel = new JLabel("To:");
row1.add(tolabel);
JTextField text1 = new JTextField(24);
row1.add(text1);
//Make "Message" text area
JPanel row3 = new JPanel();
JLabel Meslabel = new JLabel("Message:");
row3.add(Meslabel);
JTextArea text3 = new JTextArea(6,22);
messagearea.setLineWrap(true);
messagearea.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(text3,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//SpaceLine
JPanel spaceline = new JPanel();
JLabel spacer = new JLabel(" ");
spaceline.add(spacer);
row3.add(scroll);
add(row1);
add(row2);
add(spaceline);
add(spaceline);
add(row3);
setVisible(true);
public static void main(String[] arguments) {
Message Message = new Message();
}persiandude wrote:
Topic: Need help with if, else, and which statements and loops.
How would I display 60 < temp. <= 85 in java
System.out.println("60 < temp. <= 85 in java");
another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
[http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]. -
Need some help with security sandbox stuff asap please
hey guys... so im trying to do a swfLoader call to a swf on a server from my actionscript on my local machine, when i do that i get the security sandbox violation error.... i tried adding a crossdomain.xml file to the server that has the following code in it
<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="SOAPAction"/>
</cross-domain-policy>
and in my actionscript on application initialize i do
initialize="init(); Security.loadPolicyFile('http://myServer.com/crossdomain.xml')"
i also do
Security.allowDomain("http://myServer.com");
any ideas???? oh and i also went to this website http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.ht ml and set the always allow trust locations to "/"
any ideas on how i could possible fix this problem?? ive been trying to get around this problem for the last 2 days!!
please help!!!!Hi,
Please use policy file logging to check the exact error. This should shed some light on the problem.The procedure is detailed here.
http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security_05.html
Nishad -
Help with a simple program please
Hello, I am trying to create a java program that will request a password from the user (just input no gui fancy stuff) and give the user 5 tries to get it right. After the 4th guess, it needs to go from "You have # trials left." to "You have 1 trial left." It needs to become singular.
I have successfully created a program that does this, but it uses 5 if statements and 1 while. I was curious as to if there was a way to make this more "pretty" to look at. Perhaps eliminate some of the ifs. I'm not sure, but some help would be great. Thanks!Sorry, this is lessakilla. It seems I have two accounts here. I'll look into fixing that. But here is my dilemma still.
Well, I'm looking for a cleaner look. My program works fine and does what I want it to do, but i was wondering if I could somehow eliminate some of the if statements. There is a skeleton of the program below. Thanks in advance!
while count < 3
if guess.equals(password)
print (correct. welcome)
print (incorrect, you have (4 - count) trials left.)
++count;
}Then I have this
if count == 3
if guess.equals(password)
print (correct. welcome)
print (incorrect, you have (4 - count) trial left.)
++count;
}Finally I have this
if count == 4
if guess.equals(password)
print (correct. welcome)
print (incorrect, you lose.)
}Edited by: vegunks on Oct 9, 2007 7:35 PM -
I need help with some simple code! Please read!
hi everyone.
I'm having problems with a piece of code, and i'd be extremely greatful if somebody could give me a hand with it. I'm totally new to java and have to make a program for my university degree, but i'm finding it extremely difficult, mainly due to my total lack of apptitude for this type of thing. I know this is easy stuff, but the books I have are no use so any help would be greatly appreciated.
I have to write a program which uses two class files. I want one with the code to produce a simple button, and one to invoke it several times at different locations. I decided to write the program as one class file at first, and thought i'd be able to split it up at later. The program works fine when it is one class file. My book said that to split the two classes up, all i needed to do was change the second class to public, although this seems to not work at all. I'm at my wits end on this, and if anyone could correct my code I'd be eternally greatful.
Here is the first class... (sorry about the lack of indentation)
>>>>>>>>>>
import java.awt.*;
import java.applet.Applet;
public class Phone extends Applet {
private Image image;
public void init() {
setLayout(null);
image = getImage(getDocumentBase(), "phone.jpg");}
public void paint (Graphics g) {
g.drawImage(image, 0, 0, 700, 530, this);
PhoneButton myButton;
myButton = new PhoneButton(20,20);
>>>>>>>
This is the second class....
>>>>>>>
public class PhoneButton {
private Button butt;
public PhoneButton(int a, int b, int c){
setLayout(null);
butt = new Button();
butt.setBounds(a,b,20,20);
add(butt);
>>>>>>>>
My compiler generates errors relating to Button, but i can't do anything to please it.
Also, could anyone give me some pointers on how to add a different number or symbol to each button. That is what I added int c for, but i couldn't get it to work.
Cheers in advance.
Michael MorganI found that there are 5 error in your code.
1. You should import the "java.awt" package to the PhoneButton.java
2. The PhoneButton is not a kind of Component. You cannot not add it to the Phone class
3. the myButton = new PhoneButton(20, 20) does not provide enough parameters to create PhoneButton
4. You cannot add a Button to a PhoneButton. Becaue the PhoneButton is not a kind of Container
Fixed code:
import java.awt.*;
public class PhoneButton extends Button {
public PhoneButton(int a, int b, int c){
setBounds(a, b, 20, 20);
setLabel(String.valueOf(c));
===========================================
import java.awt.*;
import java.applet.Applet;
public class Phone extends Applet {
private Image image;
public void init() {
setLayout(null);
image = getImage(getDocumentBase(), "phone.jpg");}
public void paint (Graphics g) {
g.drawImage(image, 0, 0, 700, 530, this);
PhoneButton myButton;
myButton = new PhoneButton(20,20, 1);
======================
Visual Paradigm for UML - Full Features UML CASE tool
http://www.visual-paradigm.com/ -
Help with Adobe.premiere.elements12. Please
It would appear under the organizer tab that the photos are organised in the lowest folder in the folder structure within Windows Explorer. How can I use the Windows Explorer structure to organise the photos within Elements.In a situation such as yours, I tend to consolidate items into folders so I have folders of nice workable numbers of images, somewhere between 20 and 200 images. Now, whatever, once you've imported, do your moving within LR, not the OS! I will select all in a folder and drag into a folder a level or two or three above, and then delete the newly empty subfolders. I hope this helps a bit!
Once you've reached just new Imports of camera output, you'll be flying along. -
Hello
I am very new to Java and am currently studying a course in the language.
I am working through a tutorial at the moment and a question has been asked and I am struggling a bit
I have been given the code to a program that creates a window with a ball bouncing around inside the window.
There are 2 classes (code below) - Call class - this contains all the code need to create the ball and BallWorld Class (the main Class) this create the window and moves the ball, it also detects if the ball hits the edge of the window, whne this happens it redirects the ball. I understand how all this code works
I have been asked the following:-
Rather than testing whether or not the ball has hit the wall in the nmain program, we could use inhertitance to provide a specialized forom of Ball. Create a class BoundedBall that inherits from the class Ball. The constructor for this class should provide the height and width of the window, which should be maintained as data fields in the class, rewrite the move method so that the ball moves outside the bound, it automatically reflects its direction. Finally rewrite the BallWorld class to use an instance of BoundedBall rather than ordianary Ball, and elimiante the bounds test in the main program.
I am having trouble with this and I can not get my code to work, I think I may be going in completly the wrong direction with the code can sombody please provide me with a simple working code for both the BoundedBall and ammended BallWorld class, as this will help me understand whare I am going wrong
Ball class
//a generic round colored object that moves
import java.awt.*;
public class Ball {
public Ball (Point lc, int r) { //constructor for new ball
//ball centre at point loc, radius rad
loc = lc;
rad = r;
protected Point loc; //position in window
protected int rad; //radius of ball
protected double changeInX = 0.0; //horizontal change in ball position in one cycle
protected double changeInY = 0.0; //vertical change in ball position in one cycle
protected Color color = Color.blue; //colour of ball
//methods that set attributes of ball
public void setColor(Color newColor) {color = newColor;}
public void setMotion(double dx,double dy)
{changeInX = dx; changeInY = dy;}
//methods that access attributes of ball
public int radius() {return rad;}
public Point location() {return loc;}
//methods to reverse motion of the ball
public void reflectVert(){ changeInY = -changeInY; }
public void reflectHorz(){ changeInX = -changeInX; }
//methods to move the ball
public void moveTo(int x, int y) {loc.move(x,y);}
public void move(){loc.translate((int)changeInX, (int)changeInY);}
//method to display ball
public void paint (Graphics g) {
g.setColor(color);
g.fillOval(loc.x-rad, loc.y-rad, 2*rad, 2*rad);
BallWorld class
//A bouncing ball animation
import java.awt.*; //import the awt package
import javax.swing.JFrame; //import the JFrame class from the swing package
public class BallWorld extends JFrame{
public static void main (String [] args){
BallWorld world = new BallWorld(Color.red);
world.show();
for(int i = 0; i < 1000; i++) world.run();
System.exit(0);
public static final int FrameWidth = 600;
public static final int FrameHeight = 400;
private Ball aBall = new Ball(new Point (50,50),20);
private BallWorld(Color ballColor) { //constructor for new window
//resize frame, initialize title
setSize(FrameWidth, FrameHeight);
setTitle("Ball World");
//set colour and motion of ball
aBall.setColor(ballColor);
aBall.setMotion(3.0, 6.0);
public void paint (Graphics g) {
//first draw the ball
super.paint(g);
aBall.paint(g);
public void run(){
//move ball slightly
aBall.move();
Point pos =aBall.location();
if ((pos.x < aBall.radius()) ||
(pos.x > FrameWidth - aBall.radius()))
aBall.reflectHorz();
if ((pos.y < aBall.radius()) ||
(pos.y > FrameHeight - aBall.radius()))
aBall.reflectVert();
repaint();
try{
Thread.sleep(50);
} catch(InterruptedException e) {System.exit(0);}Here - you can study this :0))import java.awt.*;
import javax.swing.*;
public class MovingBall extends JFrame {
mapPanel map = new mapPanel();
public MovingBall() {
setBounds(10,10,400,300);
setContentPane(map);
public class mapPanel extends JPanel {
Ball ball = new Ball(this);
public void paintComponent(Graphics g) {
super.paintComponent(g);
ball.paint(g);
public class Ball extends Thread {
mapPanel map;
int x = 200, y = 20, xi = 1, yi = 1;
public Ball(mapPanel m) {
map = m;
start();
public synchronized void run(){
while (true) {
try{
sleep(10);
catch(InterruptedException i){
System.out.print("Interrupted: ");
move();
public void move() {
map.repaint(x-1,y-1,22,22);
if (x > map.getWidth()-20 || x < 0) xi = xi*-1;
if (y > map.getHeight()-20 || y < 0) yi = yi*-1;
x = x + xi;
y = y + yi;
map.repaint(x-1,y-1,22,22);
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.red);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.fillOval(x,y,20,20);
g2.dispose();
public static void main(String[] args) {
new MovingBall().show();
} -
Need help with a simple process with FTP Adapter and File Adapter
I am trying out a simple BPEL process that gets a file in opaque mode from a FTP server using a FTP adapter and writes it to the local file system using a File Adapter. However, the file written is always empty (zero bytes). I then tried out the FTPDebatching sample using the same FTP server JNDI name and this work fine surprisingly. I also verified by looking at the FTP server logs that my process actually does hit the FTP server and seems to list the files based on the filtering condition - but it does not issue any GET or RETR commands to actually get the files. I am suspecting that the problem could be in the Receive, Assign or Invoke activities, but I am not able identify what it is.
I can provide additional info such as the contents of my bpel and wsdl files if needed.
Would appreciate if someone can help me with this at the earliest.
Thanks
Jaypersiandude wrote:
Topic: Need help with if, else, and which statements and loops.
How would I display 60 < temp. <= 85 in java
System.out.println("60 < temp. <= 85 in java");
another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
[http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]. -
Need help with a rudimentary program
I'm sort of new at this so i need help with a few things... I'm making a program to compile wages and i need answers with three things: a.) what are the error messages im getting meaning? b.) How can i calculate the state tax as 2% of my gross pay with the first $200 excluded and c.) how can i calculate the local tax as a flat $10 with $2 deducted for each dependant. any help is appreciated
Here is what i have so far:
public class WagesAsign1
public static void main(String[] args)
int depend=4;
double hrsWork=40;
double payRate=15;
double grossPay;
grossPay=payRate*hrsWork;
double statePaid;
double stateTax=2.0;
statePaid=grossPay*(stateTax/100);
double localPaid;
double localTax=10.0;
localPaid=grossPay*(localTax/100);
double fedPaid;
double fedTax=10.0;
double taxIncome;
fedPaid=taxIncome*(fedTax/100);
taxIncome=grossPay-(statePaid+localPaid);
double takeHome;
System.out.println("Assignment 1 Matt Foraker\n");
System.out.println("Hours worked="+hrsWork+" Pay rate $"+payRate+" per/hour dependants: "+depend);
System.out.println("Gross Pay $"+grossPay+"\nState tax paid $"+statePaid+"\nLocal tax paid $"+localPaid+"\nFederal tax paid $"+fedPaid);
System.out.println("You take home a total of $"+takeHome);
and these are the error messages so far:
WagesAsign1.java:23: variable taxIncome might not have been initialized
fedPaid=taxIncome*(fedTax/100);
^
WagesAsign1.java:29: variable takeHome might not have been initialized
System.out.println("You take home a total of $"+takeHome);
^edit: figured it out... please delete post
Message was edited by:
afroryan58 -
Hi, I'm not sure if I'm allowed to post questions on this forum but I can't find anywhere to talk to helpful people about programming.
I'm making a dnd interface for JComponents. So far I've made a simple program that has a Component that can be lifted from a container and braught to the glass pane then later moved to anywhere on the screen and dropped into the container below it. Here's where my problems come:
1) Rite now my 'Movable Component' is a JPanel which is just colored in. I want to either take a Graphic2d from a JComponent/Component and draw it on the JPanel or change the JPanel to the component I want to paint and disable the component.
The problem with getting the Graphics2d is that if the component isn't on the screen it doesn't make a graphic object. I tried messing with the ui delicate and overriding parental methods for paintComponent, repaint, and that repaintChildren(forget name) but I haven't had luck getting a good graphics object. I was thinking of, at the beginning of running the program, putting 1 of each component onto the screen for a second then removing it but I'd rather not. I'd also like to change the graphics dynamicly if someone stretches the component there dropping and what not.
The problem with disabling is that it changes some of the visual features of Components. I want to be able to update the Component myself to change how it looks and I don't want disabling to gray out components.
I mainly just dont want the components to do any of there normal fuctions. This is for a page builder, by the way.
Another problem I'm having is that mouseMotionListener is allowing me to select 2 components that are on top of one another when there edges are near each other. I don't know if theres a fix to this other than changing the Java Class.
My next problem is a drop layout manager, but I'm doing pretty good with that rite now. It'll problem just move components out of the way of the falling component.
One last thing I need help with is that I don't want the object that's being carried to go across the menu bar and certain areas. When I'm having the object being carried I have it braught up to the glass pane which allows it to move anywhere. Does anyone have any idea how I could prevent the component from being over the menu bars and other objects? I might have to make 1 panel is the movable area that can then be broken down into the 'component bank', 'building page' and whatever else I'm gonna need.
This is all just test code to get together for when I make the real program but I need to make sure it'll be possible without a lot of hacking of code.
Sorry for the length. Thanks for any help you can give.The trick to making viewable components that have no behaviour, is to render them onto an image of some sort (eg a BufferedImage). You can then display the Image on a JLabel that can be dragged around the desktop.
Here is a piece of code that does the component rendering for you. This particular example uses a fixed component size, but you can modify that as you choose of course...public class JComponentImage
private static GraphicsConfiguration gConfig;
private static Dimension compSize = new Dimension(80, 22);
private static Image image = null;
public static Image getImage(Class objectClass)
if (gConfig == null)
GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gDevice = gEnv.getDefaultScreenDevice();
gConfig = gDevice.getDefaultConfiguration();
image = gConfig.createCompatibleImage(compSize.width, compSize.height);
JComponent jc = (JComponent) ObjectFactory.instantiate(objectClass);
jc.setSize(compSize);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, compSize.width, compSize.height);
g.setColor(Color.BLACK);
jc.paint(g);
return image;
}And here is the class that makes the dragable JLabel using the class above...public class Dragable extends JLabel
private static DragSource dragSource = DragSource.getDefaultDragSource();
private static DragGestureListener dgl = new DragMoveGestureListener();
private static TransferHandler th = new ObjectTransferHandler();
private Class compClass;
private Image image;
Dragable(Class compClass)
this.compClass = compClass;
image = JComponentImage.getImage(compClass);
setIcon(new ImageIcon(image));
setTransferHandler(th);
dragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY,
dgl);
public Class getCompClass()
return compClass;
}Oh and here is ObjectFactory which simply instantiates Objects of a given class and sets their text to their classname (very crudely)...public class ObjectFactory
public static Object instantiate(Class objectClass)
Object o = null;
try
o = objectClass.newInstance();
catch (Exception e)
System.out.println("ObjectFactory#instantiate: " + e);
String name = objectClass.getName();
int lastDot = name.lastIndexOf('.');
name = name.substring(lastDot + 1);
if (o instanceof JLabel)
((JLabel)o).setText(name);
if (o instanceof JButton)
((JButton)o).setText(name);
if (o instanceof JTextComponent)
((JTextComponent)o).setText(name);
return o;
}Two more classes required by this codepublic class ObjectTransferHandler extends TransferHandler {
private static DataFlavor df;
* Constructor for ObjectTransferHandler.
public ObjectTransferHandler() {
super();
try {
df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
} catch (ClassNotFoundException e) {
Debug.trace(e.toString());
public Transferable createTransferable(JComponent jC) {
Transferable t = null;
try {
t = new ObjectTransferable(((Dragable) jC).getCompClass());
} catch (Exception e) {
Debug.trace(e.toString());
return t;
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_MOVE;
public boolean canImport(JComponent comp, DataFlavor[] flavors) {
if (!(comp instanceof Dragable) && flavors[0].equals(df))
return true;
return false;
public boolean importData(JComponent comp, Transferable t) {
JComponent c = null;
try {
c = (JComponent) t.getTransferData(df);
} catch (Exception e) {
Debug.trace(e.toString());
comp.add(c);
comp.validate();
return true;
public class ObjectTransferable implements Transferable {
private static DataFlavor df = null;
private Class objectClass;
ObjectTransferable(Class objectClass) {
try {
df = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
} catch (ClassNotFoundException e) {
System.out.println("ObjectTransferable: " + e);
this.objectClass = objectClass;
* @see java.awt.datatransfer.Transferable#getTransferDataFlavors()
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { df };
* @see java.awt.datatransfer.Transferable#isDataFlavorSupported(DataFlavor)
public boolean isDataFlavorSupported(DataFlavor testDF) {
return testDF.equals(df);
* @see java.awt.datatransfer.Transferable#getTransferData(DataFlavor)
public Object getTransferData(DataFlavor arg0)
throws UnsupportedFlavorException, IOException {
return ObjectFactory.instantiate(objectClass);
}And of course the test class:public class DragAndDropTest extends JFrame
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
Container contentPane = getContentPane();
Dragable dragableJLabel;
Dragable dragableJButton;
Dragable dragableJTextField;
Dragable dragableJTextArea;
* Constructor DragAndDropTest.
* @param title
public DragAndDropTest(String title)
super(title);
dragableJLabel = new Dragable(JLabel.class);
dragableJButton = new Dragable(JButton.class);
dragableJTextField = new Dragable(JTextField.class);
dragableJTextArea = new Dragable(JTextArea.class);
leftPanel.setBorder(new EtchedBorder());
BoxLayout boxLay = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
leftPanel.setLayout(boxLay);
leftPanel.add(dragableJLabel);
leftPanel.add(dragableJButton);
leftPanel.add(dragableJTextField);
leftPanel.add(dragableJTextArea);
rightPanel.setPreferredSize(new Dimension(500,500));
rightPanel.setBorder(new EtchedBorder());
rightPanel.setTransferHandler(new ObjectTransferHandler());
contentPane.setLayout(new BorderLayout());
contentPane.add(leftPanel, "West");
contentPane.add(rightPanel, "Center");
public static void main(String[] args)
JFrame frame = new DragAndDropTest("Drag and Drop Test");
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}I wrote this code some time ago, so it won't be perfect but hopefully will give you some good ideas.
Regards,
Tim -
Help With Crash Code In PRE8 Please
In an interest to turn some of my recent discussions in a more positive direction and in keeping with the primary function of this forum (seeking advice and solutions) and in a further effort to not continually ***** about PRE8, can someone please help with and interpret the following crash codes recently generated by PRE8?
Thanks in advance for any help.
Glenn
Description
A problem caused this program to stop interacting with Windows.
Problem signature
Problem Event Name: AppHangXProcB1
Application Name: Adobe Premiere Elements.exe
Application Version: 8.0.0.0
Application Timestamp: 4aa5c87c
Hang Signature: ba8e
Hang Type: 32
Waiting on Application Name: ElementsOrganizerSyncAgent.exe
Waiting on Application Version: 8.0.0.0
OS Version: 6.0.6001.2.1.0.256.1
Locale ID: 1033
Additional Hang Signature 1: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 2: 84f3
Additional Hang Signature 3: f0a90877ec38c16fd285cc410c83433d
Additional Hang Signature 4: ba8e
Additional Hang Signature 5: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 6: 84f3
Additional Hang Signature 7: f0a90877ec38c16fd285cc410c83433d
Extra information about the problem
Bucket ID: 749899167
Description
A problem caused this program to stop interacting with Windows.
Problem signature
Problem Event Name: AppHangXProcB1
Application Name: Adobe Premiere Elements.exe
Application Version: 8.0.0.0
Application Timestamp: 4aa5c87c
Hang Signature: ba8e
Hang Type: 32
Waiting on Application Name: ElementsOrganizerSyncAgent.exe
Waiting on Application Version: 8.0.0.0
OS Version: 6.0.6001.2.1.0.256.1
Locale ID: 1033
Additional Hang Signature 1: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 2: 84f3
Additional Hang Signature 3: f0a90877ec38c16fd285cc410c83433d
Additional Hang Signature 4: ba8e
Additional Hang Signature 5: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 6: 84f3
Additional Hang Signature 7: f0a90877ec38c16fd285cc410c83433d
Extra information about the problem
Bucket ID: 749899167
Description
A problem caused this program to stop interacting with Windows.
Problem signature
Problem Event Name: AppHangXProcB1
Application Name: Adobe Premiere Elements.exe
Application Version: 8.0.0.0
Application Timestamp: 4aa5c87c
Hang Signature: ba8e
Hang Type: 32
Waiting on Application Name: ElementsOrganizerSyncAgent.exe
Waiting on Application Version: 8.0.0.0
OS Version: 6.0.6001.2.1.0.256.1
Locale ID: 1033
Additional Hang Signature 1: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 2: 84f3
Additional Hang Signature 3: f0a90877ec38c16fd285cc410c83433d
Additional Hang Signature 4: ba8e
Additional Hang Signature 5: cb0b340a390054264815ceb8e3574d53
Additional Hang Signature 6: 84f3
Additional Hang Signature 7: f0a90877ec38c16fd285cc410c83433d
Extra information about the problem
Bucket ID: 749899167
Description
A problem caused this program to stop interacting with Windows.
Problem signature
Problem Event Name: AppHangB1
Application Name: Adobe Premiere Elements.exe
Application Version: 8.0.0.0
Application Timestamp: 4aa5c87c
Hang Signature: af71
Hang Type: 0
OS Version: 6.0.6001.2.1.0.256.1
Locale ID: 1033
Additional Hang Signature 1: 37a5e7ba79ac8a533571e7d8f2e8acd0
Additional Hang Signature 2: d900
Additional Hang Signature 3: 431be4795d1c061aba02734aa57c4950
Additional Hang Signature 4: af71
Additional Hang Signature 5: 37a5e7ba79ac8a533571e7d8f2e8acd0
Additional Hang Signature 6: d900
Additional Hang Signature 7: 431be4795d1c061aba02734aa57c4950
Extra information about the problem
Bucket ID: 811067413
Description
A problem caused this program to stop interacting with Windows.
Problem signature
Problem Event Name: AppHangB1
Application Name: Adobe Premiere Elements.exe
Application Version: 8.0.0.0
Application Timestamp: 4aa5c87c
Hang Signature: 7008
Hang Type: 0
OS Version: 6.0.6001.2.1.0.256.1
Locale ID: 1033
Additional Hang Signature 1: f0af3d01fb74f43241231d4e61778ffa
Additional Hang Signature 2: 0fb3
Additional Hang Signature 3: a5f1d311bc7bfa26f067b42cbdeac6af
Additional Hang Signature 4: 7008
Additional Hang Signature 5: f0af3d01fb74f43241231d4e61778ffa
Additional Hang Signature 6: 0fb3
Additional Hang Signature 7: a5f1d311bc7bfa26f067b42cbdeac6af
Extra information about the problem
Bucket ID: 781893170Here are my system specs. Let me know if you need anything else.
Thanks
Glenn
Operating System
MS Windows Vista Ultimate SP2
Installation Date: 06 March 2009, 02:58
Intel Mobile Core 2 Duo T9550
Cores 2
Threads 2
Name Intel Mobile Core 2 Duo T9550
Code Name Penryn
Package Socket P (478)
Technology 45nm
Specification Intel Core2 Duo CPU T9550 @ 2.66GHz
Family 6
Extended family 6
Model 7
Extended model 17
Stepping A
Revision E0
Instructions MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, EM64T
Bus speed 266.0 MHz
Rated Bus speed 1064.0 MHz
Stock core speed 2666 MHz
Stock bus speed 266 MHz
Average Temperature 36 °C
Cache
L1 data cache size 2 x 32 KBytes
L1 instructions cache size 2 x 32 KBytes
L2 unified cache size 6144 KBytes
Core 1
Core speed 1596.0 MHz
Multiplier x 6.0
Bus speed 266.0 MHz
Rated Bus speed 1064.0 MHz
Temperature 37 °C
Thread 1
APIC ID 0
Core 2
Core speed 2660.0 MHz
Multiplier x 6.0
Bus speed 266.0 MHz
Rated Bus speed 1064.0 MHz
Temperature 36 °C
Thread 1
APIC ID 1
Memory
Type DDR2
Size 4096 MBytes
Channels # Dual
DRAM frequency 399.0 MHz
CAS# Latency (CL) 6.0 clocks
RAS# to CAS# delay (tRCD) 6 clocks
RAS# precharge (tRP) 6 clocks
Cycle time (tRAS) 18 clocks
SPD
Number of SPD modules 2
Slot #1
Type DDR2
Size 2048 MBytes
Manufacturer Hyundai Electronics
Max bandwidth PC2-6400 (400 MHz)
Part number HYMP125S64CP8-S6
Serial number 00007112
Week/year 52 / 08
SPD Ext. EPP
JEDEC #3
Frequency 400.000000 MHz
CAS# latency 6.0
RAS# to CAS# 6
RAS# Precharge 6
tRAS 18
tRC 24
Voltage 1.8 V
JEDEC #2
Frequency 333.333344 MHz
CAS# latency 5.0
RAS# to CAS# 6
RAS# Precharge 6
tRAS 16
tRC 21
Voltage 1.8 V
JEDEC #1
Frequency 266.666656 MHz
CAS# latency 4.0
RAS# to CAS# 4
RAS# Precharge 4
tRAS 12
tRC 16
Voltage 1.8 V
Slot #2
Type DDR2
Size 2048 MBytes
Manufacturer Hyundai Electronics
Max bandwidth PC2-6400 (400 MHz)
Part number HYMP125S64CP8-S6
Serial number 02008065
Week/year 52 / 08
SPD Ext. EPP
JEDEC #3
Frequency 400.000000 MHz
CAS# latency 6.0
RAS# to CAS# 6
RAS# Precharge 6
tRAS 18
tRC 24
Voltage 1.8 V
JEDEC #2
Frequency 333.333344 MHz
CAS# latency 5.0
RAS# to CAS# 6
RAS# Precharge 6
tRAS 16
tRC 21
Voltage 1.8 V
JEDEC #1
Frequency 266.666656 MHz
CAS# latency 4.0
RAS# to CAS# 4
RAS# Precharge 4
tRAS 12
tRC 16
Voltage 1.8 V
Mother Board
Manufacturer Dell, Inc.
Model 0P786H
Version A04
Chipset vendor Intel
Chipset model PM45
Chipset revision 07
Southbridge vendor Intel
Southbridge model 82801IM (ICH9-M)
Southbridge revision 03
BIOS
Brand Dell Inc.
Version A04
Date 11/26/2008
Monitor
Name Generic PnP Monitor on ATI Mobility Radeon HD 3650
State enable
State primary
Monitor Width 1920
Monitor Height 1200
Monitor Bit 32
Monitor Frequency 60
Device: \\.\DISPLAY1\Monitor0
Name Default Monitor on ATI Mobility Radeon HD 3650
State disabled
State removable
Monitor Width 800
Monitor Height 600
Monitor Bit 32
Monitor Frequency 60
Device: \\.\DISPLAY2
ATI Mobility Radeon HD 3650
GPU M86
Device ID 1002-9591
Subvendor Dell (1028)
-
JMS: simple program (urgent please)
I am quite new with the JMS. I am trying to have a simple program running in order to start from it towards the application I want to build.
I tried to run the sample program below:
package chat;
import javax.jms.*;
import javax.naming.*;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Properties;
public class Chat implements javax.jms.MessageListener {
private TopicSession pubSession;
private TopicSession subSession;
private TopicPublisher publisher;
private TopicConnection connection;
/* Constructor. Establish JMS publisher and subscriber */
public Chat() throws Exception {
// Obtain a JNDI connection
Properties env = new Properties();
// ... specify the JNDI properties specific to the vendor
InitialContext jndi = new InitialContext(env);
// Look up a JMS connection factory
TopicConnectionFactory conFactory =
(TopicConnectionFactory) jndi.lookup("TopicConnectionFactory");
// Create a JMS connection
TopicConnection connection =
conFactory.createTopicConnection();
// Create two JMS session objects
TopicSession pubSession =
connection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
TopicSession subSession =
connection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
// Look up a JMS topic
Topic chatTopic = (Topic) jndi.lookup("anytopic");
// Create a JMS publisher and subscriber
TopicPublisher publisher =
pubSession.createPublisher(chatTopic);
TopicSubscriber subscriber =
subSession.createSubscriber(chatTopic);
// Set a JMS message listener
subscriber.setMessageListener(this);
// Intialize the Chat application
set(connection, pubSession, subSession, publisher);
// Start the JMS connection; allows messages to be delivered
connection.start();
/* Initialize the instance variables */
public void set(TopicConnection con, TopicSession pubSess,
TopicSession subSess, TopicPublisher pub) {
this.connection = con;
this.pubSession = pubSess;
this.subSession = subSess;
this.publisher = pub;
/* Receive message from topic subscriber */
public void onMessage(Message message) {
try {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println(text);
} catch (JMSException jmse) {
jmse.printStackTrace();
/* Create and send message using topic publisher */
protected void writeMessage(String text) throws JMSException {
TextMessage message = pubSession.createTextMessage();
publisher.publish(message);
/* Close the JMS connection */
public void close() throws JMSException {
connection.close();
/* Run the Chat client */
public static void main(String[] args) {
try {
Chat chat = new Chat();
// Read from command line
BufferedReader commandLine = new
java.io.BufferedReader(new
InputStreamReader(System.in));
// Loop until the word "exit" is typed
while (true) {
String s = commandLine.readLine();
if (s.equalsIgnoreCase("exit")) {
chat.close(); // close down connection
System.exit(0); // exit program
} else {
chat.writeMessage(s);
} catch (Exception e) {
e.printStackTrace();
But at the line
�TopicConnectionFactory conFactory =
(TopicConnectionFactory) jndi.lookup("TopicConnectionFactory");�
I got this 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 chat.Chat.<init>(Chat.java:24)
at chat.Chat.main(Chat.java:94)
I realize that the problem is in the jndi setup. But, the problem is that I do not know where to go now and what should I do. I do not know how can I get the jndi.properties file and where and how to put it.
Please, kindly advise from your experience. I would appreciate clear steps to have this program running properly. Otherwise, if you do have a sample program that is already running, please provide it to me.Thank you for your prompt reply.
I tried another example.
package test;
javax.jms.*;
import javax.naming.*;
public class SimpleTopicPublisher { /** * Main method. * * @param args the topic used by the example and, * optionally, the number of messages to send */
public static void main(String[] args) {
String topicName = null;
Context jndiContext = null;
TopicConnectionFactory topicConnectionFactory = null;
TopicConnection topicConnection = null;
TopicSession topicSession = null;
Topic topic = null;
TopicPublisher topicPublisher = null;
TextMessage message = null;
final int NUM_MSGS;
// if ((args.length < 1) || (args.length > 2)) {
// System.out.println("Usage: java " + "SimpleTopicPublisher " + "[]");
// System.exit(1);
topicName = new String("MyTopic");
System.out.println("Topic name is " + topicName);
if (args.length == 2) {
NUM_MSGS = (new Integer(args[1])).intValue();
} else {
NUM_MSGS = 1;
/* * Create a JNDI API InitialContext object if none exists * yet. */
try {
jndiContext = new InitialContext
} catch (NamingException e) {
System.out.println("Could not create JNDI API " + "context: " +
e.toString());
e.printStackTrace();
System.exit(1);
/* * Look up connection factory and topic. If either does * not exist, exit. */
try {
topicConnectionFactory = (TopicConnectionFactory) jndiContext.
lookup("TopicConnectionFactory");
topic = (Topic) jndiContext.lookup(topicName);
} catch (NamingException e) {
System.out.println("JNDI API lookup failed: " + e.toString());
e.printStackTrace();
System.exit(1);
/* * Create connection. * Create session from connection; false means session is * not transacted. * Create publisher and text message. * Send messages, varying text slightly. * Finally, close connection. */
try {
topicConnection = topicConnectionFactory.createTopicConnection();
topicSession = topicConnection.createTopicSession(false,
Session.AUTO_ACKNOWLEDGE);
topicPublisher = topicSession.createPublisher(topic);
message = topicSession.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++) {
message
.setText("This is message " + (i + 1));
System.out.println("Publishing message: " + message.getText());
topicPublisher.publish(message);
} catch (JMSException e) {
System.out.println("Exception occurred: " + e.toString());
} finally {
if (topicConnection != null) {
try {
topicConnection.close();
} catch (JMSException e) {}
It is mentioned in SUN JMS tutorial that "When you use the J2EE SDK 1.3.1, your JMS provider is the SDK. " So I am using that and I did the follwoing:
--start the J2EE server as follows:
j2ee -verbose
Then I created the adminstrated object:
j2eeadmin -addJmsDestination MyTopic topic
But still getting this error:
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
So now where is the error?
Thank you in advance -
Can someone help with this simple application
I am taking my first java class and there are limited resourses for the class as far as getting help with coding.
Any hoo if any one can point me in the correct direction from the following information listed below I would be greatfull. I am trying to use the set and get methods on the instance veriables and then I am goign to post the results once I get them workign to a JOption pane window.
examples are most welcome thanks
// Invoice.java
// Homework assignment 3.13
// Student Arthur Clark
public class Invoice // public class
String partNumber;// instance veriable quantity
String partDescription;// instance verialbe partDescription
//constructors
public void setpartNumber( String number, String description )
partNumber = number; //initalize quantity
partDescription = description; // initalize partDescription
}// end constructors
//method getpartNumber
public String getpartNumber()
return partNumber;
}//end method getpartNumber
public String getpartDescription()
return partDescription;
}// end method getpartDescription
public void displayMessage()
//this is the statement that calls getpartNumber
System.out.printf(" part number # \n%s!\n the description", getpartNumber(), getpartDescription() );
} // method displaMessage
}// end method main
// Fig. 3.14 InvoiceTest.java
// Careate and manipulate an account object
import java.util.Scanner;
import javax.swing.JOptionPane;//import JOptionPane
public class InvoiceTest{
// main method begins the exciution of the program
public static void main ( String args [] )
// create Scanner to obtain input from mommand window
Scanner input = new Scanner ( System.in );
// create a Invoice object and assig it to mymethod
Invoice myMethod = new Invoice();
Invoice myMethod2 = new Invoice();
// display inital value of partName, partDescriptoin
System.out.printf( "inital partname is %s\n\n", myMethod.getpartNumber() );
// prompt for and read part name, partDescription
System.out.println( "please enter the Part Number:" );
String theNumber = input.nextLine(); // read a line of text
myMethod.setpartNumber( theNumber ); // set the part name with in the parens
System.out.println();// outputs blank line
myMethod.displayMessage();
System.out.println( "please enter the Part Description" );
String theDescription = input.nextLine(); // read a line of text
myMethod2.setpartDescription( theDescription );// set the part description
System.out.println();// outputs blank line
myMethod2.displayMessage();
}// end main mehtod
}// end class//constructors
public void setpartNumber( String number, String description )
partNumber = number; //initalize quantity
partDescription = description; // initalize partDescription
}// end constructorsThe above code is not a constructor. You do not include a return type, void or anything else. Also, the constructor should be called the same as your class.
public Invoice( String number, String description )
partNumber = number;
partDescription = description;
} Another thing, comments should only be used when it isn't bleedingly obvious what your code is doing.
P.S. is your middle initial C? -
Help with a simple 1811 configuration
I have a very basic level of understanding with Cisco products and I need help with what should be simple and even doable by me.
I have a Cisco 1811 integrated router and am simply trying to use it on my home network. I can configure the router with an enable secret password, password encryption, VTY, aux, and cons logins with no issues. The router has 2 Ethernet interfaces, 0 and 1 and 8 switch ports.
The idea is to bring Comcast ISP service into one of the Ethernet ports and then have three machines on the switch ports able to access the Internet. Also I have an off-the shelf wireless router that I thought I would just plug that into an available switch port and allow a wireless AP as well.
This is so simply, that I can't believe I can't figure it out, but I can't.
I set int F1 to DHCP, performed a 'no shut', and connected the ISP's router and have an up and up indication. I have setup a static network with my three machines on the switch ports and enabled all applicable ports and have up and up indications - however, no traffic flow, even amongst my static Layer 2 switched LAN - not even a 'ping'. By my understanding of Layer 2, this should work right now, whether the ISP service is working or not - WHAT AM I DOING WRONG?
The addressing scheme I have ended up on is 172.16.1.0/28
Obviously without the first hurdle cleared, of why the switched LAN doesn’t work, I haven't got any deeper. Do I need to configure NAT? I don't think I would need to in the scenario right?
All of my experience, and none at the CCNA level, has been with larger Cisco equipment. One thing I noticed on the 1811 was that when trying to create a new VLAN, it appears to work yet does not do anything and the 'sh vlans' output returns nothing, not even the VLAN1 I can see with 'sh ip int brief".
Anyway, if anyone has time to help a newbie out I would appreciate it; I’m lost.
Thanks,
JoshThanks for the help Andrew! You know, I think if this was two separate devices (switch and router) I think I would be up and running, but this integrated stuff is throwing me off, not to mention that the IOS is a much older version (I guess) than what I'm used to.
They were throwing this 1811 in the trash can at work, so I just emptied the trash can. I have no documentation at all but I have since found the 1800 series documentation on Cisco.com and have tried to implement the basic configurations cited; with what seems like success, but still no joy. I did have to recover the password and did so with 0x2142, I bypassed the setup and compared the default configuration with what is listed in the documentation and they DO NOT match; I also tried to go through setup mode with the same indications. Additionally I've also learned that the 1800 series is pre-configured on certain options (DHCP, VLAN), which is new to me - I thought Cisco routers were not configured by default - isn't that kind of the point? (By the way, the below port status may not be correct since I now have all the ports unplugged)
Anyway, here is the 'show run' command, the 'sh ip int brief' command, followed by the 'sh version' command:
Show Run
Casino#sh run
Building configuration...
Current configuration : 2006 bytes
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
hostname Casino
boot-start-marker
boot-end-marker
enable secret 5 $1$meWw$nsMTp6US7axi/uE0MWULK.
enable password 7 06535E741C1B584C55
no aaa new-model
ip cef
no ip dhcp use vrf connected
ip dhcp excluded-address 172.16.1.1
ip dhcp pool Casino
import all
network 172.16.1.0 255.255.255.240
default-router 67.165.208.1
dns-server 68.87.89.150
domain-name hsd1.co.comcast.net
no ip domain lookup
ip domain name GinRummy.localhost
ip name-server 68.87.85.102
ip name-server 68.87.69.150
ip auth-proxy max-nodata-conns 3
ip admission max-nodata-conns 3
multilink bundle-name authenticated
archive
log config
hidekeys
interface Loopback0
ip address 172.16.1.1 255.255.255.240
interface FastEthernet0
no ip address
shutdown
duplex auto
speed auto
interface FastEthernet1
ip address dhcp
ip nat outside
ip virtual-reassembly
duplex auto
speed auto
pppoe enable
pppoe-client dial-pool-number 1
interface BRI0
no ip address
encapsulation hdlc
shutdown
interface FastEthernet2
interface FastEthernet3
interface FastEthernet4
interface FastEthernet5
interface FastEthernet6
interface FastEthernet7
interface FastEthernet8
interface FastEthernet9
interface Vlan1
no ip address
ip nat inside
ip virtual-reassembly
interface Dialer0
ip address negotiated
ip mtu 1492
encapsulation ppp
dialer pool 1
ppp authentication chap
ip forward-protocol nd
no ip http server
no ip http secure-server
ip nat pool Casino 172.16.1.2 172.16.1.14 netmask 255.255.255.240
ip nat inside source list 1 interface Dialer0 overload
access-list 1 permit 172.16.1.0 0.0.0.15
dialer-list 1 protocol ip permit
control-plane
line con 0
password 7 080E5916584B4442435E5C
login
line aux 0
password 7 013C135C0A59475A70191E
login
line vty 0 4
password 7 09635B51485756475A5954
login
end
Show IP Interface Brief
Casino#sh ip int brief
Interface IP-Address OK? Method Status Prl
FastEthernet0 unassigned YES NVRAM administratively down do
FastEthernet1 unassigned YES DHCP up do
BRI0 unassigned YES NVRAM administratively down do
BRI0:1 unassigned YES unset administratively down do
BRI0:2 unassigned YES unset administratively down do
FastEthernet2 unassigned YES unset up do
FastEthernet3 unassigned YES unset up do
FastEthernet4 unassigned YES unset up do
FastEthernet5 unassigned YES unset up do
FastEthernet6 unassigned YES unset up do
FastEthernet7 unassigned YES unset up do
FastEthernet8 unassigned YES unset up do
FastEthernet9 unassigned YES unset up up
Vlan1 unassigned YES NVRAM up up
Loopback0 172.16.1.1 YES manual up up
Dialer0 unassigned YES manual up up
NVI0
'show version'
Casino#sh ver
Cisco IOS Software, C181X Software (C181X-ADVIPSERVICESK9-M), Version 12.4(15))
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2008 by Cisco Systems, Inc.
Compiled Thu 24-Jan-08 13:05 by prod_rel_team
ROM: System Bootstrap, Version 12.3(8r)YH12, RELEASE SOFTWARE (fc1)
Casino uptime is 52 minutes
System returned to ROM by reload at 17:09:25 UTC Fri Jul 1 2011
System image file is "flash:c181x-advipservicesk9-mz.124-15.T3.bin"
This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.
A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html
If you require further assistance please contact us by sending email to
[email protected].
Cisco 1812 (MPC8500) processor (revision 0x400) with 118784K/12288K bytes of m.
Processor board ID FHK120622J3, with hardware revision 0000
10 FastEthernet interfaces
1 ISDN Basic Rate interface
31488K bytes of ATA CompactFlash (Read/Write)
Configuration register is 0x2102
Thanks again for your help,
Josh
Maybe you are looking for
-
Ipod touch 6.1.6 to 7.1?
Hi, I have an iPod touch (I believe 4th generation) which is on IOS 6.1.6, but more and more apps can't be downloaded because they need IOS 7.1. Am I correct in saying that I can't update my iPod to IOS 7.1? If that's true, do we know why not? Is it
-
Fetching Data... while querying composites in EM
Hi, I installed SOA Suite 11.1.1.4 on windows and database XE. The installation is successful, but when I go to EM --> SOA --> soa-infra --> default, I get only Fetching Data... but doesn't result in anything. I even deployed a composite but I can't
-
Why can't I delete mp3 files from my Trash? They are not locked.
Why can't I delete mp3 files from my Trash? They are not locked. I compressed them into a zip file and then couldn't delete that file either. I've restored them and tried deleting again but no luck. Can anybody please help? iOS 10.8.5
-
Donde descargo la version antigua?
-
Pick and Pack Grouping Functionality
If you overwrite a ship to address in the sales order screen, and then attempt a pick and pack, pick and pack does not create different delivery notes for each different address. This is because pick and pack groups all the delivery notes with the s