URL: newbie needs help with simple programming question!
Hi everyone,
Please direct me to a FAQ or other resource, or help me with this problem:
I want to create a text field (or similar container) that contains both ordinary text AND a URL/hyperlink in it. For example, the following text might appear in the text field:
"I have many _pictures_ from my vacation"
where the word "pictures" is actually a hyperlink to a web site, and the other portions of the string are simple text.
All advice and help is appreciated!
-Dennis Reda
[email protected]
Well here is one way you code do it but if you do alittle research on them links above it will explain how this code works.Well it will explain how jeditorpane and hyperlinklistener work
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.net.*;
public class b extends javax.swing.JApplet implements HyperlinkListener {
JEditorPane field = new JEditorPane();
public b() {
Container pane = getContentPane();
FlowLayout flo = new FlowLayout();
pane.setLayout(flo);
field.setPreferredSize(new Dimension(200, 25));
field.setEditable(false);
pane.add(field);
setContentPane(pane);
String gg1 = "<html><body>I have many_<a href='http://www.home.com'>pictures</a>_from my vacation</body></html>";
field.addHyperlinkListener(this);
field.setContentType("text/html");
field.setText(gg1);
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try{
URL url = new URL("http://www.msn.com");
getAppletContext().showDocument(url,"_self");
}catch(Exception r) {};
public void init() {
b c = new b();
ps hope this helped
Similar Messages
-
Hi need help with simple program
1 System.out.println("Input Number of Question: ");
2
3 inputQuestionNum = Integer.parseInt(input.nextLine());
4
5 if(inputQuestionNum>=10) {
6 System.out.println("Error: Please try again"); //how to return to line 1
7 else {
8 System.out.println("ok");
9 }
Hi, i am new to java, how to make the program return back to first line when input is more then 10? I do not know how to describe my problem therefore i can't google for solution. thank you in advance.The usual approach is to use a do-while loop:Scanner input = new Scanner (System.in);
int inputQuestionNum;
do {
System.out.println ("Input Number of Question: ");
inputQuestionNum = Integer.parseInt (input.nextLine ());
if (inputQuestionNum >= 10) {
System.out.println ("Error: Please try again");
} else {
System.out.println ("ok");
} while (inputQuestionNum >= 10);Ask if that's not clear.
db -
I believe that I have everything right except when I get down to the else I want it to return to the while loop. Is there a better way of doing this because it doesn't work for me. Here is the program:
public class ABCInput
public static void main(String[] args) throws Exception
char response;
System.out.println("Please type a A,B,C to receive a message or a Q to quit");
response = (char)System.in.read();System.in.read();System.in.read();
while(response == 'A' || response == 'B' || response == 'C')
System.out.println("\"Good Job\"\n\n");
System.out.println("Please type a A,B,C to receive a message or a Q to quit");
response = (char)System.in.read();System.in.read();System.in.read();
if(response == 'Q')
System.out.println("Thanks for playing");
System.exit(0);
else
System.out.println("You have entered an invalid letter. Please try again");
response = (char)System.in.read();System.in.read();System.in.read();
}mahugl,
Try this out.
public class ABCInput
public static void main(String[] args) throws Exception
char response;
boolean notInvalid = true;
boolean notFinished = true;
System.out.println("Please type a A,B,C to receive a message or a Q to quit");
response = (char)System.in.read();System.in.read();System.in.read();
while(notFinished == true)
while(notInvalid == true)
if(response == 'A' || response == 'B' || response == 'C' || response == 'Q' || response == 'a' || response == 'b' || response == 'c' || response == 'q')
notInvalid = false;
else
System.out.println("You have entered an invalid letter. Please try again");
response = (char)System.in.read();System.in.read();System.in.read();
if(response == 'Q' || response == 'q')
notFinished = false;
else
System.out.println("\"Good Job\"\n\n");
System.out.println("Please type a A,B,C to receive a message or a Q to quit");
response = (char)System.in.read();System.in.read();System.in.read();
notInvalid = true;
System.out.println("Thanks for playing");
System.exit(0);
}jerryrika -
I am currently living in Tunisia but it's not on the Apple Contact Support list. I need help with my security questions which I cannot remember the answers. There is no link to send a reset email. What do I do?
Click here and ask the iTunes Store staff for assistance.
(114040) -
I need help with the security Questions is there some way to get you to remember them by e-mail of other wise
Read the HT5312 page that you posted from, it has instructions for how to reset them i.e. if you have a rescue email address set up on your account then steps 1 to 5 half-way down that page should give you a reset link.
If you don't have a rescue email address then you will need to contact iTunes Support / Apple in your country to get the questions reset.
Contacting Apple about account security : http://support.apple.com/kb/HT5699
When they've been reset (and if you don't already have a rescue email address) you can then use the steps half-way down the HT5312 page that you posted from to add a rescue email address for potential future use -
Need Help with simple array program!
Hi, I have just recently started how to use arrays[] in Java and I'm a bit confused and need help designing a program.
What this program does, it reads in a range of letters specified by the user. The user then enters the letters (a, b or c) and stores these characters into an array, which the array's length is equal to the input range the user would enter at the start of the program. The program is then meant to find how many times (a,b and c) appears in the array and the Index it first appears at, then prints these results.
Here is my Code for the program, hopefully this would make sense of what my program is suppose to do.
import B102.*;
class Letters
static int GetSize()
int size = 0;
boolean err = true;
while(err == true)
Screen.out.println("How Many Letters would you like to read in?");
size = Keybd.in.readInt();
err = Keybd.in.fail();
Keybd.in.clearError();
if(size <= 0)
err = true;
Screen.out.println("Invalid Input");
return(size);
static char[] ReadInput(int size)
char input;
char[] letter = new char[size];
for(int start = 1; start <= size; start++)
System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
input = Keybd.in.readChar();
while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#'))
Screen.out.println("Invalid Input");
System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
input = Keybd.in.readChar();
while(input == '#')
start == size;
break;
for(int i = 0; i < letter.length; i++)
letter[i] = input;
return(letter);
static int CountA(char[] letter)
int acount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'a')
acount++;
return(acount);
static int CountB(char[] letter)
int bcount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'b')
bcount++;
return(bcount);
static int CountC(char[] letter)
int ccount = 0;
for(int i = 0; i < letter.length; i++)
if(letter[i] == 'c')
ccount++;
return(ccount);
static int SearchA(char[] letter)
int ia;
for(ia = 0; ia < letter.length; ia++)
if(letter[ia] == 'a')
return(ia);
return(ia);
static int SearchB(char[] letter)
int ib;
for(ib = 0; ib < letter.length; ib++)
if(letter[ib] == 'b')
return(ib);
return(ib);
static int SearchC(char[] letter)
int ic;
for(ic = 0; ic < letter.length; ic++)
if(letter[ic] == 'c')
return(ic);
return(ic);
static void PrintResult(char[] letter, int acount, int bcount, int ccount, int ia, int ib, int ic)
if(ia <= 1)
System.out.println("There are "+acount+" a's found, first appearing at index "+ia);
else
System.out.println("There are no a's found");
if(ib <= 1)
System.out.println("There are "+bcount+" b's found, first appearing at index "+ib);
else
System.out.println("There are no b's found");
if(ic <= 1)
System.out.println("There are "+ccount+" c's found, first appearing at index "+ic);
else
System.out.println("There are no c's found");
return;
public static void main(String args[])
int size;
char[] letter;
int acount;
int bcount;
int ccount;
int ia;
int ib;
int ic;
size = GetSize();
letter = ReadInput(size);
acount = CountA(letter);
bcount = CountB(letter);
ccount = CountC(letter);
ia = SearchA(letter);
ib = SearchB(letter);
ic = SearchC(letter);
PrintResult(letter, acount, bcount, ccount, ia, ib, ic);
return;
} Some errors i get with my program are:
When reading in the letters to store into the array, I get the last letter I entered placed into the entire array. Also I believe my code to find the Index is incorrect.
Example Testing: How many letters would you like to read? 3
Enter letter (a, b or c) (# to quit): a
Enter letter (a, b or c) (# to quit): b
Enter letter (a, b or c) (# to quit): c
It prints "There are no a's'" (there should be 1 a at index 0)
"There are no b's" (there should be 1 b at index 1)
and "There are 3 c's, first appearing at index 0" ( there should be 1 c at index 2)
The last thing is that my code for when the user enters "#" that the input of letters would stop and the program would then continue over to the counting and searching part for the letters, my I believe is correct but I get the same problem as stated above where the program takes the character "#" and stores it into the entire array.
Example Testing:How many letters would you like to read? 3
Enter letter (a, b or c) (# to quit): a
Enter letter (a, b or c) (# to quit): #
It prints "There are no a's'" (should have been 1 a at index 0)
"There are no b's"
and "There are no c's"
Can someone please help me??? or does anyone have a program simular to this they have done and would'nt mind showing me how it works?
Thanks
lou87.Without thinking too much...something like this
for(int start = 0; start < size; start++) {
System.out.println("Please enter a letter (a, b or c) ("+size+" max), enter # to stop:");
input = Keybd.in.readChar();
while((input != 'a') && (input != 'b') && (input != 'c') && (input != '#')) {
Screen.out.println("Invalid Input");
System.out.println("Please enter a letter (a, b or c) ("+size+" max, enter # to stop:");
input = Keybd.in.readChar();
if(input == '#') {
break;
letter[start] = input;
}you dont even need to do start = size; coz with the break you go out of the for loop. -
Need Help With Simple ABAP Code
Hello,
I'm loading data from a DSO (ZDTBMAJ) to an Infocube (ZCBRAD06). I need help with ABAP code to some of the logic in Start Routine. DSO has 2 fields: ZOCTDLINX & ZOCBRDMAJ.
1. Need to populate ZOCPRODCD & ZOCREFNUM fields in Infocube:
Logic:-
Lookup /BI0/PMATERIAL, if /BIC/ZOCBRDMAJ = /BIC/OIZOCBRDMAJ
then /BIC/ZOCPRODCD = ZOCPRODCD in Infocube
/BIC/ZOCREFNUM = ZOCREFNUM in Infocube
2. Need to populate 0G_CWWTER field in Infocube:
Logic:
Lookup /BIC/PZOCTDLINX, if /BIC/ZOCTDLINX = BIC/OIZOCTDLINX
then G_CWWTER = 0G_CWWTER in Infocube.
I would need to read single row at a time.
Thanks!I resolved it.
-
Hello everyone.
First time posting, i hope someone would be able to help me out. There are 5 classes that i have to do, but i only need help with one of them. I've been stuck on this one pretty long and can't continue without it.
Instructions:
Has boolean data member face, either HEADS or TAILS.
Has a Random data member flipper which is instantiated in the constructor.
Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
Method getFace() returns the face showing on the coin.
void method flip() randomly selects HEADS or TAILS.
package coinflip;
import java.util.Random;
* @author Blank
public class Coin {
boolean face = false;
int flip_coin;
Random flipper = new Random();
int getFace() {
return flip_coin;
Coin() {
if (flip_coin == 0) {
face = true;
} else {
face = false;
public void flip() {
flip_coin = flipper.nextInt(2);
}i really don't know why the random isn't working. I hope someone would be able to find my errors and instruct me on how to fix them. I would be able to continue the rest of the classes as soon as i got this figured out.
Oh and can someone teach me how to import this class into a main one? So i can test it out. This is what i have for it.public class Main {
* @param args the command line arguments
public static void main(String[] args) {
Coin flipCoin = new Coin();
for(int i=0;i<6;i++){
System.out.println(flipCoin.getFace());
}Many Thanks!
Edited by: Java_what on Feb 16, 2009 2:26 PMConstructors are only executed once. What im confused about is:
Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
I thought i would flip() into the constructor. Mind helping me out on the whole class because it seems i am clueless about this whole class.
Edit:
public class Coin {
boolean face = false;
int flip_coin;
Random flipper = new Random();
int getFace() {
flip();
return flip_coin;
Coin() {
//flip();
public void flip() {
flip_coin = flipper.nextInt(2);
}K i reread what you wrote about the constructor and method. So i placed flip() method in getFace(); because its being called in the main(it gives me random numbers). The problem now is following the directions.
I just dont understand this description. Class constructor has no parameters and randomly chooses the result HEADS or TAILS. (See method flip())
What do you think it means.
Edited by: Java_what on Feb 16, 2009 4:14 PM -
Need Help with Simple Chat Program
Hello Guys,
I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Client
extends JPanel {
public static void main(String[] args) throws IOException {
String name = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
final Socket s = new Socket(host, port);
final Client c = new Client(name, s);
JFrame f = new JFrame("Client : " + name);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
c.shutDown();
System.exit(0);
f.setSize(300, 300);
f.setLocation(100, 100);
f.setContentPane(c);
f.setVisible(true);
private String mName;
private JTextArea mOutputArea;
private JTextField mInputField;
private PrintWriter mOut;
public Client(final String name, Socket s)
throws IOException {
mName = name;
createUI();
wireNetwork(s);
wireEvents();
public void shutDown() {
mOut.println("");
mOut.close();
protected void createUI() {
setLayout(new BorderLayout());
mOutputArea = new JTextArea();
mOutputArea.setLineWrap(true);
mOutputArea.setEditable(false);
add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
mInputField = new JTextField(20);
JPanel controls = new JPanel();
controls.add(mInputField);
add(controls, BorderLayout.SOUTH);
mInputField.requestFocus();
protected void wireNetwork(Socket s) throws IOException {
mOut = new PrintWriter(s.getOutputStream(), true);
final String eol = System.getProperty("line.separator");
new Listener(s.getInputStream()) {
public void processLine(String line) {
mOutputArea.append(line + eol);
mOutputArea.setCaretPosition(
mOutputArea.getDocument().getLength());
protected void wireEvents() {
mInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String line = mInputField.getText();
if (line.length() == 0) return;
mOut.println(mName + " : " + line);
mInputField.setText("");Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.
-
I need help with simple problems. im a student.
i'd like to be advanced with my studies so i will post questions.. i need help on how to answer. thank you.
1. create a java program that will evaluate if the value entered is a positive, negative, vowel, consonant and special characters.
im actually done with the positive and negative using if else statements.. i used an integer data type. now my question is how do conjoin the characters when i need to evaluate a vowel and a consonant. i cant use char either. please help. i dont know what to do yet.
2. create java program that will translate the input from numbers to words. e.g. input:123 output: one hundred twenty-three.
i have an idea to use a switch case statement. but i have no idea on how will i be able to do it. so if you guys can help me.. well then thankies..Welcome to the Sun forums. First, please note that you have posted in the wrong forum. This forum is for topics related to Sun's JavaHelp product. You should post your questions in the New to Java forum.
As part of your learning, you will have to develop the ability to select an approach to a problem, create a design that reflects that approach, and then implement the design with code that you create.
So, it's inappropriate for us to take the problem statement that you have been given and short-circuit your learning process by giving you the implemented problem solution. We can comment on the individual questions that you may have, and point out problems and errors that we see in the code that you develop.
As a hint, when you are stuck, forget about Java and programming. Just start with a sheet of paper and a pencil, and figure out how to layout the task on paper. The consider how to translate that to programming.
If you have problems, post short example code that shows the problem, and explain your question clearly. We can't read minds.
Make sure you post code correctly so that it's not mangled by the forum software, and so that formatting is maintained. Select your typed or pasted code block and press the CODE button above the typing area. -
Newbie needs help with browser compatibility
Ok, so I'm new at this, so this may be something really
simple, but browser compatibility? I made a site in DW;html and it
shows up perfect in safari but internet explorer and firefox not so
much. I did a browser compatibility test in DW and it says nothing
is wrong with my pages, but obviously something must be!!
On my home page, the image of a house that I have next to the
company name shows up fine in safari but not any other browsers.
And my page layout, everything is moved over funny in other
browsers. Also there are link boxes around the table I created with
different brands of products. On safari the boxes do not show, but
all the other browsers it does!! I'm new at this and frustrated!!!
Need help!!
The link is holmeshifi.com and I posted code from the home
page!OK thanks Ned sorry to soo dumb I'm on a learning curve here! what
I'm trying to do is go to the URLs of web galleries of images from my
main site
so I would presumably have to rename them on my server? i.e. does that
mean adding the code ", "_blank");
to the files on the server?
At the moment I have to use the back button on my browser window which
takes me back to the main site which then has to reload (tediously!) -
Beginner needs help with simple code.
I just statrted learnind java, and I need some help with this simple program. For some reason everytime I enter my Farenheit value, the Celsius conversion returns as 0.0. Would really appreciate the help. Thanks.
Here's the code:
public class TempConverter
public static void main(String[] args)
double F = Double.parseDouble(args[0]);
System.out.println("Temperature in Farenheit is: " + F);
double C = 5 / 9;
C *= (F - 32);
System.out.println("Temperature in Celsius is: " + C);
}double C = 5 / 9This considers "5" and "9" to be integers and does an integer division, discarding the remainder. The result of that division is 0. Trydouble C = 5.0/9.0;
-
Newbie needs help with Flex app
Hi there. I am very new to Flex and also fairly new to
programming although I do have a little experience.
I am trying to create an app which stores code snippets or
common text I tend to use every day in my documents and emails.
So basically I need help on a design level. I can refer to
the developer's manual for exact instructions for commands, but I
need to know what to code first.
The app will consist of:
-a tree directory structure where I can create groups.
-There will be a basic text editor where I input all my data,
basic text formatting options (font, bullets etc) would be a bonus.
-A search function
-Finally it will ideally allow multiple client apps write to
a central database file over a network
Can anyone suggest how I should approach such a project?
Or are there any tutorials / source files which demonstrate
each bullet point?
thanks.Hey jono,
I'm new too. But I think I might know the right components.
If you google any of these + flex 3 you should get some
decent documentation
tree - advanced dataGrid component
basic text editor - rich text editor component
search function - well, you're gonna need to read up on
arrays, and arraycollection. Once you get that stuff working, you
can write up a function to search for a string in an array.
network functionality - HTTPService, you can dump the
datagrid into a database, and have it load the database when you
open up the application.
Give these things a shot, tutorials / sources will come with
the google searches. -
Need help with inventory program!!! someone please help me!!!
Ok I have to write this inventory program for one of my classes.
For part one i needed to Create a product class that holds the item number, the name of product, the number of units in stock, and the price of each unit.
Then create a java application that displays all of the above info plus the total value of the inventory. I have done this so far with success.
For part two i needed to modify the program so the application can handle multiple items. Use an array to store the items. The output should display the information one product at a time including the item number, the name of the product, the number of units in stock, the price per unit, and the value of the inventory of that product. In addition, the output should display the value of the entire inventory.
so create a method to calculate the value of the entire inventory.(i did this)
and create another method to sort the array items by the name of the product. ( i did this)
The program compiles and runs fine except it is not doing anything from part two. It just does the same thing that it did when i wrote part one.
Does anyone know why or what i need to do to my code.
Here is my code.
import java.util.Scanner; // program uses class Scanner
import java.util.Arrays;
class ProductList
Product[] products = new Product[100]; // an array of 100 pruducts
private void populate() {
products[0] = new Product(0, "Good Luck Chuck" , 25, 4.95);
products[1] = new Product(1, "The Bourne Identity" , 3, 7.95);
products[2] = new Product(2, "The Reaping" , 5, 8.99);
products[3] = new Product(3, "Deja Vu" , 2,12.99);
products[4] = new Product(4, "I Know Who Killed Me" , 3,10.95);
private void sortByTitle() {
private void print() {
for(int i=0; i<products.length; i++) {
System.out.println(products);
private void printTotalInventoryValue() {
System.out.println("Total Inventory Value = "+calculateTotalInventoryValue());
private double calculateTotalInventoryValue() {
double total = 0D;
for(int i=0; i<products.length; i++) {
total += products[i].calculateInventoryValue();
return total;
public static void main( String args[] ) {
ProductList list = new ProductList();
list.populate();
list.sortByTitle();
list.print();
list.printTotalInventoryValue();
} class Product
private int id;
private String title;
private int stock;
private double price;
public Product(int id, String title, int stock, double price) {
setId(id);
setTitle(title);
setStock(stock);
setPrice(price);
public int getId() { return this.id; }
public void setId(int id) { this.id = id; }
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
public int getStock() { return this.stock; }
public void setStock(int stock) { this.stock = stock; }
public double getPrice() { return this.price; }
public void setPrice(double price) { this.price = price; }
public double calculateInventoryValue() {
return getStock() * getPrice();
public class Inventorypt2
private String ProductInfo; // call class product info
public static void main(String args[])
//create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int num; // product's item number
int stock; // number of items in stock
double price; // price each of item
ProductInfo product; // product information instance
System.out.println(); // blank line
String name = "go";
// loop until sentinel value read from user
while ( !name.equalsIgnoreCase ("stop") )
System.out.print( "Enter DVD title, or STOP to quit: "); // prompt
name = input.nextLine(); // read item name from user or quit
System.out.print( "Enter the item number: "); // prompt
num = input.nextInt(); // read item number from user
while ( num <=0 ) //loop until item number is positive
System.out.println ("Item number must be positive. Please re-enter item number: ");//prompt user to re-enter item number
num = input.nextInt(); // read item number
} //end while
System.out.print( "Enter the quantity in stock: "); // prompt
stock = input.nextInt(); // read stock quantity from user
while ( stock <0 ) //loop until stock is positive
System.out.println ("Quantity in stock can not be less than zero. Please re-enter the quantity in stock: ");//prompt user to re-enter quantity in stock
stock = input.nextInt(); // read stock quantity from user
} //end while
System.out.print( "Enter the price of DVD: "); // prompt
price = input.nextDouble(); // read item price from user
while ( price <=0 ) //loop until price is positive
System.out.println ("Product price must be positive. Please re-enter the price of the product: ");//prompt user to re-enter product price
price = input.nextDouble(); // read item price from user
} //end while
product = new ProductInfo( num, name, stock, price); // initialize ProductInfo variables
System.out.println(); // blank line
System.out.printf( "Item Name: %S\n", product.getName());
System.out.printf( "Item Number: %s\n", product.getNum());
System.out.printf( "Qty. in Stock: %s\n", product.getStock());
System.out.printf( "Price Each: $%.2f\n", product.getPrice());
System.out.printf( "Total Value in Stock: $%.2f\n", product.getInventoryTotal());
System.out.println(); // blank line
System.out.print( "Enter DVD title, or STOP to quit: "); // prompt
name = "";
while ( name.equals("") )
name = input.nextLine(); // read new product name from user or quit
} //end while
System.out.println(); // blank line
System.out.println("Good Bye!"); // exit message
Edited by: jay1981 on Mar 16, 2008 2:07 PMYou will get more help if your code is formatted better:
* Only post code that is already formatted correctly including indentations.
* Get rid of all those comments cluttering up your code.
* Make sure your posted code compiles without need for any changes. Yours doesn't at present. Where is the ProductInfo class?
Again, you want it easy for a volunteer here to read your post, otherwise he/she simply won't do it. Good luck. -
Need help with basic program.....!
I've to write a program that generates a random number, which the user has to try and guess, after each guess they're told whether it's too high or too low etc., I've gotten this far, however, the user has only 10 guesses.... In my program I've used a while loop and the user gets an infinite number of guesses, I know I'm supposed to use a for loop, but can't seem to get it to work properly. Also, when the user guesses the number, the program then has to print out how many guesses it took, and I have no idea how to get it to do this AT ALL!!! I'd really appreciate some help with this, thanks v. much!!!!
I've to write a program that generates a random
number, which the user has to try and guess, after
each guess they're told whether it's too high or too
low etc., I've gotten this far, however, the user has
only 10 guesses.... In my program I've used a while
loop and the user gets an infinite number of guesses,
I know I'm supposed to use a for loop, but can't seem
to get it to work properly. Also, when the user
guesses the number, the program then has to print out
how many guesses it took, and I have no idea how to
get it to do this AT ALL!!! I'd really appreciate some
help with this, thanks v. much!!!!Hey not every book covers every aspect of Java (if you haven't got a book and don't want to buy 1 i recommend an online tutorial) If u want the user to have an infinate number of guesses, use an infinate while loop. Put this in a file called app.java:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class app extends Applet implements ActionListener
JLabel lbl=new JLabel("Guess a number between 0 and 10:");
JTextField txtfield=new JTextField(20);
JButton button=new JButton("Guess...");
JLabel lbl2=new JLabel();
int randomnumber=Math.round((float)Math.random()*10);
public void init()
add(lbl);
add(txtfield);
add(button);
button.addActionListener(this);
public void actionPerformed (ActionEvent e)
String s=new String("");
s+=randomnumber;
if (e.getSource().equals(button) && txtfield.getText().equals(s))
setBackground(Color.white);
setForeground(Color.black);
lbl2.setText("Got it!");
add(lbl2);
validate();
else
setBackground(Color.white);
setForeground(Color.black);
if (Integer.parseInt(txtfield.getText())>randomnumber)
lbl2.setText("Too High!");
else
lbl2.setText("Too Low!");
add(lbl2);
validate();
Then create a HTML document in the classes folder:
<HTML>
<HEAD>
<TITLE>APPLET</TITLE>
</HEAD>
<BODY>
<HR>
<CENTER>
<APPLET
CODE=app.class
WIDTH=400
HEIGHT=200 >
</APPLET>
</CENTER>
<HR>
</BODY>
</HTML>
It will do what you wish. If you want to have more then 10 numbers to guess, for example 100, do this:
int randomnumber=Math.round((float)Math.random()*100);
Does that answer your question?
Maybe you are looking for
-
Does anyone know how to get the vendor ID and product ID for a USB device in NI-Visa? TIA
Does anyone know how to get the vendor ID and product ID for a USB device in NI-Visa? TIA
-
Dear All, I'm trying to create new groups of the CMC, but I don't manage to give these groups an access to the following area (I am the administrator and belong to the Aministrators group) : - Licence Keys - Authentication - Settings - Queries result
-
Why Are Reader Patches Not Combined?
It is so very inconvenient to have to patch Adobe Reader multiple times, especially when first installing. Additionally, it takes great effort to determine which patches are already applied so that the correct one(s) can be added. Patches should be
-
The caption on an annotation is off the plot area. Even if I cahnge the x and y scaling I still can't see the annotation caption. How can I change it so that I can see it?
-
JDWP fatal error from thread.stop()
I get this message FATAL ERROR in native method: JDWP "util.c" (Jan 20 2004), line 1209: Unexpected error, error code = 113 (JVMDI_ERROR_INTERNAL) from the target VM when I do thread.stop() on the debugger side. The debugger isn't bothered by the fat