Stars program problem
Hi, I got Java running about 5 weeks ago to anyone that helped me thanks, but now I got a small problem:-
When a user enters a number for example 6, I am trying to get it to output 6 lines of:
please help I have 3 errors,
public class stars1
public static void main(String[]args);
int counter1 = 1;
int counter2 = 1;
int table;
System.out.print("Please enter an integer: ")
table = EasyIn.getInt();
do
do
System.out.print("*")
counter1++;
} while (counter1 <= table);
System.out.println();
counter1 = 1;
} while (counter1 <= counter2);
errors are:-C:\Java Code\stars1.java:10: <identifier> expected
System.out.print("Please enter an integer: ")
^
C:\Java Code\stars1.java:13: illegal start of type
do
^
C:\Java Code\stars1.java:25: <identifier> expected
} while (counter1 <= counter2);
^
3 errors
Tool completed with exit code 1
Thanks in advance
Hi, I got Java running about 5 weeks ago to anyone
that helped me thanks, but now I got a small
problem:-
When a user enters a number for example 6, I am
trying to get it to output 6 lines of:
please help I have 3 errors,
public class stars1
public static void main(String[]args);
int counter1 = 1;
int counter2 = 1;
int table;
System.out.print("Please enter an integer: ")
table = EasyIn.getInt();
do
do
System.out.print("*")
counter1++;
} while (counter1 <= table);
System.out.println();
counter1 = 1;
} while (counter1 <= counter2);
errors are:-C:\Java Code\stars1.java:10: <identifier>
expected
System.out.print("Please enter an integer: ")
^
C:\Java Code\stars1.java:13: illegal start of type
do
^
C:\Java Code\stars1.java:25: <identifier> expected
} while (counter1 <= counter2);
3 errors
Tool completed with exit code 1
Thanks in advanceI think this would solve your problem,
import java.io.*;
public class program_name
public static void main(String args[]) throws IOException
String input_string;
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));//set up input
System.out.print("Enter the number : ");
input_string = myInput.readLine(); //read in the input
int number = Integer.parseInt(input_string);
for (int i = 1; i <= number; i++)
int counter=1;
while (counter<=number)
System.out.print("*");
counter++;
System.out.println();
}It a simple nested loop that asks for a number from the user, loop for that number and loop again within the outer loop!
Hope it helps!
Similar Messages
-
Hi all,
I was looking for this java programming problem which had to do with a large building and there was some gallons of water involved in it too somehow and we had to figure out the height of the buiding using java. This problem is also in one of the java books and I really need to find out all details about this problem and the solution. NEED HELP!!
Thanks
macYes, it will. The water will drain from the bottom of
the tank until the pressure from the water inside the
tank equals the pressure from the pipe. In other
words, without a pump, the water will drain out until
there is the same amount of water in the tank as in
the pipe The water pressure depends on the depth of the water, not the volume. So once the depth of the water inside the pipe reaches the same depth as the water inside the tank it will stop flowing. This will never be above the height of the tank.
I found this applet which demonstrates our problem. If you run it you can drag the guy up to the top, when water in his hose reaches the level of the water in the tank it will stop flowing out. -
Subject:
programming problem
Date:
Sun, 10 Mar 2002 19:48:34 +0800
From:
LibraryPublicStation <[email protected]>
Organization:
Hong Kong University of Science and Technology
Newsgroups:
hkust.cs.class.201
Hi, I have some problems on the following code:
The code has no compiling error. but
Why I can't get the RGB value of my image since I can get the width and
height of the image.
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import java.awt.color.*;
import com.sun.image.codec.jpeg.*;
import java.awt.geom.*;
public class Sun
public static void main(String args[])
double[][] database_graph=new double[0][900];
// put the image in a row with 900 column
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image1 = new ImageIcon("imges.jpg").getImage();//load the image to
image1
BufferedImage buffer;//Buffer the image to get the RGB value
buffer = new BufferedImage(image1.getWidth(null),image1.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
ColorModel a=buffer.getColorModel();
System.out.println(a);
for(int j=0;j<buffer.getWidth();j++)
for(int k=0;k<buffer.getHeight();k++)
int rgb=buffer.getRGB(j,k);//get the red,green,blue value of the graph
int red = ((rgb&0xff0000)>>16);
int green = ((rgb&0xff00)>>8);
int blue = rgb&0xff;
database_graph[0][buffer.getHeight()*j+k] = (red + green + blue)/3;
System.out.println(database_graph[0][buffer.getHeight()*j+k]+" "+red+"
"+green+" "+blue);
} // change back to gray scaleTry this :
ImageIcon icon = new ImageIcon("imges.jpg");
Image image1 = icon.getImage();
BufferedImage buffer = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
...But I think, in your problem, you want to get the image in a BuffererdImage ?
ImageIcon icon = new ImageIcon("imges.jpg");
BufferedImage buffer= (BufferedImage)icon.getImage();
...Denis -
Field Service - STAR program is completing with Error message
Hi
Synchronize Territory Assignment Rules (STAR) program is getting completed with following error message:
Parameters used were 'Service' with a Run mode as 'Total Refresh'. It errors out with 'No data found' error message. (Log file appended below)
Can someone help to find out root cause?
Regards,
CRM Foundation: Version : 12.0.0
Copyright (c) 1979, 1999, Oracle Corporation. All rights reserved.
JTY_STAR module: Synchronize Territory Assignment Rules
Current system time is 29-APR-2011 15:01:48
**Starts**29-APR-2011 15:01:48
**Ends**29-APR-2011 15:01:55
100 : ORA-01403: no data found
Start of log messages from FND_FILE
End of log messages from FND_FILE
Executing request completion options...
Finished executing request completion options.
Concurrent request completed
Current system time is 29-APR-2011 15:01:55
P.S. Reposting - It looks like I had posted in wrong category earlier. Sorry!. Re-posting again with CRM category for Field service this time.As per the SR we had to laod all the old rates, as this was the beginning of a new fiscal year.
-
Running STAR program in Date Effective mode
Hi All,
How the date effective mode of Synchronize Territory Assignment rule concurrent will work? Will it sync all the active territories in that date range? For example if I run the STAR program from 01-Mar-2010 to 31-Mar-2010, will it sync all the territories which are all active in this date range? Will it pick up the territory which has start date as 01-Feb-2010 and end date as 30-Apr-2010?
Please advice..
Thanks,
Suresh.The only emulator for running Classic apps I know of is SheepShaver, and from what I've read (though not confirmed) it doesn't work under Snow Leopard (not surprising; SheepShaver hasn't been update in over three years, from what I can see). It also requires the ROM image from an older Mac, and if someone had access to an older Mac to get the image, they could just run the app on that older Mac.
So I think that the ability to run Classic apps is now completely dead as of Snow Leopard. -
Coldfusion server problem or programming problem?
Hello experts,
I have been experiencing problems when accessing this website using Mac (and Parallels/WinXP).
http://tinyurl.com/3yh3d8l
Because there is no problem when using Windows PC, the programmer suggested that it might be a CF server problem, but one of my IT said it's programming issue (basically he said the web programmer is wrong). I have very limited access to PC at work but I need the data from that website. I'd like to give input to the webprogrammer but I don't know what to say. Could you please give me some suggestions? Thank you.hi Adam,
Just tested in Mac, the site works in FireFox. But Safari won't load it at all. Progress bar keep spinning but screen doesn't change.
So is this something to do with the programming problem or Safari is being picky? I can use FireFox during presentation but I'd like the option to be able to use Safari (iPad?). -
dear sirs, i work with forms 6i
i have programming problem and i want to solve it
the problem is
i have table contain the following fields
AREA_CODE NOT NULL NUMBER(8)
AREA_NAME NOT NULL VARCHAR2(30)
EAREA_NAME VARCHAR2(30)
UP_AREA_CODE NUMBER(8)
AREA_TYPE NUMBER(1)
AREA_LEVEL NUMBER(15)
transfer_fees number(15,3)
i want to get the value of transfer_fees, depend on the area code which i want, but if transfer_fees is null i should get the other transfer_fees of the up_area_code as the up level of area code, and if also null then get the value of transfer_fees of the up level of area code and so on.
please help me urgently
YasserHi yasser
it's not precise for me , It needs a lot of details but according to the existing information
Now we have 3 options
Option1 : Get the transfer_fees according to AREA_CODE -- i don't know how not clear for me
Option 2 : IF transfer_fees IS NULL then get it's value from up_area_code (then i am assuming that up_area_code has a value currently during the user input so all we have is to think that we can get it's value from a simple assign statement in WHEN-VALIDATE-ITEM trigger of transfer_fees item as ...
IF :transfer_fees IS NULL THEN
:transfer_fees :=:up_area_code;
END IF;and so on...
Hope this helps...
Regards,
Amatu Allah -
I'm new to Ubuntu & Linuz OS. I've started to see a pop-up window that says: System Program Problem Detected- Do you want to report the problem. When I click yes, I'm asked to enter my password to access problem reports of system programs. Should I be asked for my password ???
I am fairly new to Ubuntu, but that does not sound unexpected. Ubuntu tends to have everyone use a limited account that needs to ask for a password before carrying out operations like installing software.
-
Spotify Community Rock Star Program
Hello Spotify lovers!
Have you ever shown a friend how to sync a playlist? Ever explained how Spotify works to a group of people? At Spotify, we know users helping users is something special.
That’s why we’ve created the Spotify Rock Star Program to recognize awesome contributors. Program members have already received:
Premium Codes
Official Spotify Gear
Early Access to New Versions of Spotify
Calls with Spotify Staff for Q&A Sessions
Invitations to visit Spotify Headquarters in Stockholm
And More!!!
The Spotify Community is a place to get help, help others, and talk about music. So if you know answers to your fellow Spotify music lover's questions, why not help out?
We look forward to you joining our band. Check out the PDF below for more info (updated November 2014). If you'd like to join the RSP just let us know in a private message or by posting in this thread.
See you around!
The Spotify Community Team
ktinamk188 wrote:
This is great. I'm constantly telling people that Spotify is the best $10 I spend a month!!
Haha, yes. I relate. My teacher listens to her iTunes radio, but it is ridden with ads now. I told her about Spotify, and I pay for "no ads," plus an unilimited access to music. It's so much better than any iTunes or online radio that I know. I hesitated to tell her how much I pay: $5/month (I'm a poor college student, that's a LOT for me! Haha). She said, "that's all?!" She knew Spotify when it was still only in the UK. Well, it's change a lot since then - and for the better.
I enjoy telling people that it's only $5/month for unlimited access with ZERO ADVERTISEMENTS, and I listen to music via Spotify at work, school and home. Of course, it's $10/month for the extra-extra features, like carrying Spotify with you on an MP3 player, etc. But I am very happy with $5/month for the service I use! And always new music added!!
Anyway, I'll stop rambling. :) Thanks for the great service, Spotify team!! I am speaking, of course, of the software AND the friendly and helpful community!
katsumii -
The Spotify Community Rock Star Program
Hello Spotify lovers!
Have you ever shown a friend how to sync a playlist? Ever explained how Spotify works to a group of people? At Spotify, we know users helping users is something special.
That’s why we’ve created the Spotify Rock Star Program to recognize awesome contributors. Program members may receive:
Premium Codes
Official Spotify Gear
Early Access to New Versions of Spotify
Invites to Spotify Staff Q&A Sessions
And More!!!
The Spotify Community is a place to get help, help others, and talk about music. So if you know answers to your fellow Spotify music lover's questions, why not help out?
We look forward to you joining our band. Check out the attached PDF for more info.
See you around!
The Spotify Community Teamktinamk188 wrote:
This is great. I'm constantly telling people that Spotify is the best $10 I spend a month!!
Haha, yes. I relate. My teacher listens to her iTunes radio, but it is ridden with ads now. I told her about Spotify, and I pay for "no ads," plus an unilimited access to music. It's so much better than any iTunes or online radio that I know. I hesitated to tell her how much I pay: $5/month (I'm a poor college student, that's a LOT for me! Haha). She said, "that's all?!" She knew Spotify when it was still only in the UK. Well, it's change a lot since then - and for the better.
I enjoy telling people that it's only $5/month for unlimited access with ZERO ADVERTISEMENTS, and I listen to music via Spotify at work, school and home. Of course, it's $10/month for the extra-extra features, like carrying Spotify with you on an MP3 player, etc. But I am very happy with $5/month for the service I use! And always new music added!!
Anyway, I'll stop rambling. :) Thanks for the great service, Spotify team!! I am speaking, of course, of the software AND the friendly and helpful community!
katsumii -
Forms Service verification program problem
I have a java verification program that is run from a HPUX server cron job to check
the status of my 9.0.2.12.2 Oracle 9iAS Forms Services running on a
Windows 2000 server. The program determines if the Forms Services
restarted after a cold, off-hours backup by retrieving and reading
base.htm.
I have 3 windows servers with "identical" configurations of 9iAS Forms
Services. The java verification program works when running against the dev and
test Forms servers but not against the production Forms server. It
did work against the production Forms server until I upgraded to
9.0.2.12.2 a few months ago. The only way to reproduce the problem
against the test Forms server is to rename base.htm so the program
can't find it. default.env,forms90.conf,formsweb.cfg all appear to be
identical. Paths and other environmental variables are identical on
the windows Forms servers. The java program fails or succeeds
consistently on 3 different HPUX servers both in cron and from the
command line.
The error message is: java.io.IOException: Server returned HTTP
response code: 500 for URL:
http://productionserver:7778/forms90/f90servlet
Java is 1.3.1 on all environments.
import java.io.*;
import java.net.*;
public class auRLTest
public auRLTest()
try {
System.out.println("Starting...");
URL url = new URL("http://productionserver:7778/forms90/f90servlet");
System.out.println("Opening URL connection ("+url+")");
URLConnection uc = url.openConnection ();
System.out.println("Connecting to URL");
uc.connect();
System.out.println("Opening input stream.");
BufferedReader in = new BufferedReader(
new InputStreamReader( uc.getInputStream() ) );
System.out.println("Reading file...");
System.out.println("==========================================================================");
String inputLine = in.readLine();
while (inputLine != null)
System.out.println(inputLine);
inputLine = in.readLine();
System.out.println("==========================================================================");
System.out.println("Closing file.");
in.close();
System.out.println("Production Form Server is UP");
catch( java.net.ConnectException connectException ) {
System.out.println("***PRODUCTION FORM SERVER IS DOWN***.");
catch( Exception exception ) {
System.out.println(exception);
public static void main(String[] args)
auRLTest uRLTest = new auRLTest();
Accessing "http://productionserver:7778/forms90/f90servlet" from IE works fine.
Any clues or ideas are appreciated.
ThanksI went through the same thing. Look at Appendix II "Case Study" at http://rootshell.be/~yong321/freeware/ckweb.html. Basically, the forms servlet needs some more HTTP headers you didn't pass.
Yong Huang -
When trying to open ITunes, I got an error message of msvcr80.dll can not be found.
Assuming that it was an iTunes file, I reinstalled iTunes.
Trying to open again, I got an error message of an appication is trying to open a library file incorrectly.
How do I resolve this problem.
Neither my PC with Vista nor my my laptop with windows 7 will work?
ThanksHello Msvcr80.dll,
Thanks for using Apple Support Communities.
For more information on this, take a look at:
iTunes 11.1.4 for Windows: Unable to install or open
http://support.apple.com/kb/TS5376
Check for .dll files
Go to C:\Program Files (x86)\iTunes and C:\Program Files\iTunes and look for .dll files.
If you find QTMovie.DLL, or any other .dll files, move them to the desktop.
Reboot your computer.
Note: Depending on your operating system, you may only have one of the listed paths.
Uninstall and reinstall iTunes
Uninstall iTunes and all of its related components.
Reboot your computer. If you can't uninstall a piece of Apple software, try using the Microsoft Program Install and Uninstall Utility.
Re-download and reinstall iTunes 11.1.4.
Best of luck,
Mario -
When i create a payment proposal today with posting date in the future and the items that have to be paid are in foreign currency the payment run program (that executed in the future date) create postings with exchange rate the rate of proposal creation date and not the posting date.
Is there any solution to this problem?
Version 4.6C
Thanks in advance
EliasElias
There are loads of SAP Notes about this. You'll have to search for the specific one for your system.
try http://service.sap.com/notes -
Beginner with a programming problem
I am getting quite frustrated trying to figure out how to proceed with a Java program I've been assigned. I'm hoping that my problem is not too amorphous to warrant assistance.
The program is an exercise in Swing and creating GUI's, and at this stage, I only need to create an array of dice objects which can paint themselves on a JPanel. The instructor has given us two files -- one extending JPanel and containing a main method to test the classes, and another which represents a die.
Some issues are
1) I don't know where to call repaint.
2) When the overridden paintComponent method is called, it wipes out
the background color on my panel, which I set in the constructor.
3) I got null pointer exceptions when I ran the instructor 's main method... I moved the setVisible up in the chain and they went away (Though he stated not to alter the main method, I don't know enough about Java Graphics to know if it's his mistake or mine)
4) I'd just like to see some something appear.
I should add that I rewrote this whole thing in one file (without using an array) and was able to get the graphics to paint.
Sorry for posting copious amounts of code, but hopefully it will clear up what I'm trying to do. If anyone could just give me some pointers in the right direction, I would greatly appreciate it. Thank you for your time.
// File: DicePanel.java
public class DicePanel extends JPanel
private int number_of_dice = 0;
private DiceDrawn [] dice;
/** The x,y coordinates where the first die is drawn */
private int xCoordinate = 5; //default
private int yCoordinate = 5; //default
/** Constructor with default properties */
public DicePanel()
this.setSize(getPreferredSize());
this.setBackground(Color.blue);
// set size and color
/* Set the Dice array */
public void setDice(DiceDrawn[] d)
}// end setDice
/** Return xCoordinate */
public int getXCoordinate()
return xCoordinate;
/** Set a new xCoordinator */
public void setXCoordinate(int x)
xCoordinate = x;
/** Return yCoordinator */
public int getYCoordinate()
return yCoordinate;
/** Set a new yCoordinator */
public void setYCoordinate(int y)
yCoordinate = y;
/** Paint the Dice Panel */
protected void paintComponent(Graphics g)
super.paintComponent(g);
for (int i = 0; i < dice.length; i++ )
dice.drawDie(g, xCoordinate, yCoordinate);
setXCoordinate(getXCoordinate() + 41);
// draw each die using default start coordinates,
// moving right each time
/** Override get method for preferredSize */
public Dimension getPreferredSize()
return new Dimension(200, 50);
// the main method to test DicePanel and DiceDrawn
// do not change this method.
public static void main(String [] args)
JFrame f = new JFrame();
// f.setVisible(true);
f.setTitle("Draw Dice");
f.setSize(500,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = f.getContentPane();
// show 6 dice initially
DiceDrawn [] dice = new DiceDrawn [6];
for(int i = 0; i < dice.length; i++)
dice[i] = new DiceDrawn(i+1);
DicePanel dicePanel = new DicePanel();
dicePanel.setDice(dice);
System.out.println(dice.length);
cp.add(dicePanel, BorderLayout.NORTH);
f.setVisible(true);
// show only one die for the rest of the program
dice = new DiceDrawn [1];
System.out.println("Dice Drawn Class Test");
int i = Io.readInt("Enter an integer between 1 and 6");
while( i > 0 )
dice[0] = new DiceDrawn(i);
dice[0].setSelected( i%2 == 0 ? true : false);
dicePanel.setDice(dice);
i = Io.readInt("Enter an integer between 1 and 6");
System.exit(0);
// File: DiceDrawn.java
public class DiceDrawn
private final int SIZE = 36;
private final int QUARTER = SIZE/4;
private int face; // face value
private boolean selected; // pressed = true
public DiceDrawn( int f)
setFace(f);
setSelected(true);
}// end DiceDrawn
public void setSelected( boolean s )
selected = s;
public boolean isSelected()
return selected;
public void setFace(int i)
face = i;
public int getFace()
return face;
// Draw a die starting at the given coordinates
public void drawDie(Graphics g, int xcoor, int ycoor)
g.setColor(Color.WHITE);
g.fillRect(xcoor,ycoor, SIZE, SIZE);
g.setColor(Color.BLACK);
switch(face)
case 1:
g.fillOval((xcoor-4)+(2*QUARTER), (ycoor-4)+(2*QUARTER), SIZE/8, SIZE/8);
break;
case 2:
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(3*QUARTER), (ycoor-4)+(3*QUARTER), SIZE/8, SIZE/8);
break;
case 3:
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(3*QUARTER), (ycoor-4)+(3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(2*QUARTER), (ycoor-4)+(2*QUARTER), SIZE/8, SIZE/8);
break;
case 4:
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(3*QUARTER), (ycoor-4)+(3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + (3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ (3*QUARTER), (ycoor-4)+ QUARTER, SIZE/8, SIZE/8);
break;
case 5:
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(3*QUARTER), (ycoor-4)+(3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + (3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ (3*QUARTER), (ycoor-4)+ QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(2*QUARTER), (ycoor-4)+(2*QUARTER), SIZE/8, SIZE/8);
break;
case 6:
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + QUARTER, SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+(3*QUARTER), (ycoor-4)+(3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4)+(2*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ (3*QUARTER), (ycoor-4)+(2*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ QUARTER, (ycoor-4) + (3*QUARTER), SIZE/8, SIZE/8);
g.fillOval((xcoor-4)+ (3*QUARTER), (ycoor-4)+ QUARTER, SIZE/8, SIZE/8);
break;
// draw a die using a rectangle of 36 by 36 pixels
// at the coordinates given.
// use a switch statement to draw the appropriate face.
}// end DrawDie
}// end DiceDrawnOnce you get beyond your initial problems, you'll find that there is another problem. When it displays the dice corresponding to the numbers you select, the x coordinate eventually becomes greater than the frame width. You need to make a change to the paintComponent method so it looks like:
/** Paint the Dice Panel */
protected void paintComponent(Graphics g)
super.paintComponent(g);
for (int i = 0; i < dice.length; i++ )
dice.drawDie(g, xCoordinate, yCoordinate);
if(dice.length > 1)
setXCoordinate(getXCoordinate() + 41);
// draw each die using default start coordinates,
// moving right each time
Note that I have added an if above the setXCoordinate so that it will only add to the X coordinate when it is displaying the 6 dice initially. It won't add anything when it is displaying the single dice. -
HTTP Client/Server program problems
Hi all,
I am doing an exercise in which I create a Client and Server program. I send a GET request but nothing seems to happen. There is obviously something I'm missing. Could it be a badly formed request? The code is below. Any help is appreciated.
Client program.....
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class HTTPClient{
String host, path;
int port;
public static void main (String argv[]){
new HTTPClient(argv[0]);
public HTTPClient(String url){
try{
URL myURL = new URL(url);
host = myURL.getHost();
port = myURL.getPort();
System.out.println("Port = " + port);
if (port == -1) port = 30280;;
path = myURL.getPath();
if (path.equals("")) path = "/";
Socket s = new Socket(InetAddress.getByName(host), port);
sendRequest(s.getOutputStream());
printResponse(s.getInputStream());
s.close();
catch(MalformedURLException murl){
System.out.println("Badly formatted URL " + murl.getMessage());
catch(IOException e){
System.out.println("Problem initialising socket " + e.getMessage());
public void sendRequest(OutputStream out){
StringBuffer buf = new StringBuffer();
buf.append("GET /AC095.html HTTP/1.1\r\n");
buf.append("Host: http://students.odl.qmul.ac.uk\r\n\r\n");
try{
out.write(buf.toString().getBytes("US-ASCII"));
catch (IOException e) {System.out.println(e.getMessage());
public void printResponse(InputStream in){
try{
while (in.available() <= 0)
Thread.sleep(500);
while (in.available() > 0)
System.out.print((char) in.read());
System.out.println ("");
catch (IOException e) {
System.out.println(e.getMessage());
catch (InterruptedException ie) {
System.out.println("Error waiting for response " + ie.getMessage());
/* Read in the response from the HTTP server and print it out */
}Server code......
import java.io.*;
import java.net.*;
import java.util.*;
public class HTTPServer{
String version = null;
public String httpVer;
public static void main(String argv[]){
new HTTPServer(Integer.parseInt(argv[0]));
public HTTPServer(int port){
boolean listening = true;
try{
ServerSocket ss = new ServerSocket(port);
System.out.println("HTTP Server running and listening for requests...");
while (listening){
Socket mySocket = ss.accept();
InputStream in = mySocket.getInputStream();
readHeaders(in);
String response = getResponse();
OutputStream out = mySocket.getOutputStream();
out.write(response.getBytes("US-ASCII"));
out.flush();
mySocket.close();
catch(Exception e){System.out.println(e.getMessage());}
private String getResponse(){
StringBuffer responseBuf = new StringBuffer();
responseBuf.append (httpVer + " 200 OK\r\n");
responseBuf.append ("Content-type: text/html\r\n");
responseBuf.append ("Content-length: 119\r\n");
responseBuf.append ("<HTML>\r\n");
responseBuf.append ("<TITLE> My served web document </TITLE>\r\n");
responseBuf.append ("</HEAD>\r\n");
responseBuf.append ("<BODY>\r\n");
responseBuf.append ("<H1> Hello from the server! </H1>\r\n");
responseBuf.append ("</BODY>\r\n");
responseBuf.append ("</HTML>\r\n\r\n");
String responseStr = responseBuf.toString();
responseStr = responseStr.trim();
return "";
private void readHeaders(InputStream in) throws IOException {
StringBuffer sbuf = new StringBuffer();
int ch;
String clientStr;
//This loop reads in all of the input until there is nothing left to read.
//All of the characters are appended to the string buffer.
while ((ch = in.read()) != -1) {
sbuf.append((char) ch);
//clientStr will hold string in string buffer without any leading or
//trailing white space.
clientStr = sbuf.toString();
clientStr = clientStr.trim();
//Split clientStr into substrings and store them in an array.
String [] tokens = clientStr.split(" ");
//Obtains HTTP version
httpVer = tokens [2];
}Cheers,
ChrisI've written out.flush() in the server program. When I attempt to connect to the server it just hangs. I've modified the code locally to request a webpage from elsewhere and it works so it can't be the format of my GET request. I assume that the problem has to be in the Server program. Is it not reading in and understanding the /r/n properly?
Maybe you are looking for
-
Due to plugin problem online games don't open i have played them a lot before
it don't say which plug in. i keep losing the response you send. i am having trouble with knowledge of this stuff.
-
Tables for Assets & Liabilities in Profit Center
Dear All, I want to know the tables for Profit Center wise Assets & Liabilities. Help needed. Regards, Pankaj.
-
I upgraded to Maverick on a previously owned Macbook Pro OSX 10.9.4, and when trying to get updates, the previous owners's Apple Id shows and their password is required. what canI do?
-
Learning either Flex or ajax to create a searchable database
Greetings Flex forum, I've just created a site for my small property rental company and am ready to make it more sophisticated. Currently, I have a form on the site which has about 20 fields of criteria - bedrooms, baths, price range, area, amenities
-
[SOLVED] Windows 8 made all my arch partition unallocated space
Hi, I've been using arch for the past 8 months without any problem. I used to have win 7 and fedora on my laptop also.I used the bootloader from fedora to boot arch. Yesterday I decided to replace win7 with win8. After playing around with it, it was