cgeier 187 Junior Poster

Convert string to char array, then check each character to see if it is a digit using Character.isDigit(char c)

See isDigit Documentation

OR

Use regex, with the split function.

See Java regex Documentation

See an Example Here

cgeier 187 Junior Poster
cgeier 187 Junior Poster
  1. Use a timer. For an example, Click Here

  2. Create 3 sorting functions.

  3. Use a counter.

  4. There is no substitution for practice.

cgeier 187 Junior Poster

For your program, pseudo-code might look like:

Get diameter from user
Get velocity from user

radius = diameter / 2.0
PI = 3.14
area = PI * radius * radius
volume = area * velocity

Print volume of water flow

In pseudo-code, you don't worry about how to properly write the syntax,
such as

    if (x == 1)
    {
       return;
    }//

you can just write

if x = 1, then return
cgeier 187 Junior Poster

Updated code:
added int permutationCount = 1;, permutationCount += 1;, and printf ("%d", permutationCount);

    #define AsciiArraySize 52

    int i,j = 0;
    int permutationCount = 1; //keeps track of # of permutations
    char asciiArray[AsciiArraySize]; 

    int arrCount = 0;

    // insert upper case letters
    // i = ascii character code
    for (i=65; i <= 90; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for

    // insert lower case letters
    // i = ascii character code
    for (i=97; i <= 122; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for


    //permutations of length 1
    for (i=0; i < AsciiArraySize; i++)
    {
        printf("%c \n", asciiArray[i]);
        permutationCount += 1;
    }//for

    //permutations of length 2
    for (i=0; i < AsciiArraySize; i++)
    {
        //print contents of array
        for (j=0; j < AsciiArraySize; j++)
        {
            printf("%c%c \n", asciiArray[i],asciiArray[j]);
            permutationCount += 1;
        }//for
    }//for

    printf ("%d", permutationCount);

Now add the code for passwords that are 3-characters long, and then passwords that are 4-characters long.

cgeier 187 Junior Poster

I would use a character array to hold the valid characters.

    #define AsciiArraySize 52

    int i,j = 0;
    char asciiArray[AsciiArraySize];

    int arrCount = 0;

    // insert upper case letters
    // i = ascii character code
    for (i=65; i <= 90; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for

    // insert lower case letters
    // i = ascii character code
    for (i=97; i <= 122; i++)
    {
        asciiArray[arrCount] = i;
        arrCount += 1; //increment counter
    }//for


    //passwords that are 1 character
    for (i=0; i < AsciiArraySize; i++)
    {
        printf("%c \n", asciiArray[i]);
    }//for


    //passwords that are 2 characters
   for (i=0; i < AsciiArraySize; i++)
   {
       //print contents of array
       for (j=0; j < AsciiArraySize; j++)
       {
           printf("%c%c \n", asciiArray[i],asciiArray[j]);
           permutationCount += 1;
       }//for
   }//for

You were on the right track using nested for loops. So now add the code for passwords that are 3-characters long, and then passwords that are 4-characters long.

cgeier 187 Junior Poster

However, if your password is case-sensitive, then you have, in essence, 52 letters--not 26 (26 lower case letters + 26 upper case letters)

4-letter permutations:
52*52*52*52

3-letter permutations:
52*52*52

2-letter permutations:
52*52

1-letter permutations:
52
cgeier 187 Junior Poster

Please look at the ascii table again. You will see the following:

A-Z is 65-90
a-z is 97-122

and 91-96 are other characters.
cgeier 187 Junior Poster

I believe the number of permutations are as follows (for English alphabet):

4-letter permutations:
26*26*26*26

3-letter permutations:
26*26*26

2-letter permutations:
26*26

1-letter permutations:
26

Here is an article that explains it:
http://www.mathsisfun.com/combinatorics/combinations-permutations.html

cgeier 187 Junior Poster

It may not be an NTFS or FAT/FAT32 partition. Open a cmd window and type the following:

diskpart
DISKPART> list disk

by looking at the size figure out which disk # you are interested in.
Example: (I've decided I'm interested in disk 1)

DISKPART> select disk 1
DISKPART> detail disk
DISKPART> list partition

For each partition do the following:
DISKPART> select partition <partition #> where <partition #> is "0", "1", "2", ...etc

Example:

DISKPART> select partition 0
DISKPART> detail partition

Then if there is a partition 1:

DISKPART> select partition 1
DISKPART> detail partition

...and continue for each partition. Make note of the "type" for each partition.

DISKPART> exit
cgeier 187 Junior Poster

Clear the CMOS. Remove the CMOS battery for 30 - 60 seconds and replace. Reboot the computer.

cgeier 187 Junior Poster

Have you checked the "Power Options"?

cgeier 187 Junior Poster

What do you mean by "calling C++ from C#"? Are you wanting to use a dll?

cgeier 187 Junior Poster

The issue of displaying the data in the textfields.

Inventory

actionPerformed
You haven't called 'displayDVD' -- it is commented out. Uncomment it.

// button pushes...
    // // Sets the void for the next-button click
    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == firstButton) {
            position = 0;
        } else if (event.getSource() == lastButton) {
            position = movieArray.length - 1;
        } else if (event.getSource() == previousButton) {
            if (position != 0) {
                position--;
            } else {
                position = movieArray.length - 1;
            }
        } else if (event.getSource() == nextButton) {
            if (position != (movieArray.length - 1)) {
                position++;
            } else {
                position = 0;
            }
        } else if (event.getSource() == modifyButton) {
            modifyItem();
        } else if (event.getSource() == addButton) {
            addItem();
            position = movieArray.length - 1;
        } else if (event.getSource() == deleteButton) {
            deleteItem();
        } else if (event.getSource() == searchButton) {
            searchProduct();
        } else if (event.getSource() == saveButton) {
            writeToFile();
        }

       //-------------------------------------------
       // Needs to be uncommented to display the DVD
       //-------------------------------------------
       displayDVD(); 
    }

Also, you really should use parameters when possible, instead of global variables.

Use this:

public void displayDVD(int position) {
    DVDMovie DVD = movieArray[position];

                 ...
}

Instead of:

public void displayDVD() {
    DVDMovie DVD = movieArray[position];

                 ...
}
cgeier 187 Junior Poster

Inventory

In **searchProduct **
you ask for the itemNumber, but in the following code:

for (int i = 0; i < movieArray.length; i++) {
            if (searchDVDTitle == movieArray[i].getDVDTitle()) {

you are comparing the title not itemNumber. Also, in the above statement:

`searchDVDTitle`

should be changed to

`DVDTitle`

because "DVDTitle" contains the user input.

Be careful with using the same variable name in different methods and assigning it a different type, because it may lead to confusion. In deleteItem, 'searchDVDTitle' is of type int. While in displayDVD, it is of type String.

Also, I recommend that you adopt a way for distinguishing between global variables and local variables. It can help to eliminate runtime errors.

cgeier 187 Junior Poster

Inventory
I noticed the "Cancel" button doesn't work on your JOptionPane.showInputDialog. Try something like the following:

getDVDTitle

  private String getDVDTitle() {

        //--------------------------------------
        // Changed from:
        //--------------------------------------


        /*
        String title = JOptionPane.showInputDialog("Enter DVD Title: ");

        while (title == null || title.trim().equals("")) {
            JOptionPane
                    .showMessageDialog(null, "Please enter DVD title.");
            title = JOptionPane.showInputDialog("Enter DVD Title: ");
        }
        */


        //--------------------------------------
        // Note: value is null if user clicked cancel
        //
        // Changed To:
        //--------------------------------------

        String title = "";

        while (title.equalsIgnoreCase("")) { //OK pressed without input
            title = JOptionPane.showInputDialog("Enter DVD Title: ");

            if (title == null) //cancel was clicked
            {
                return null;
            }
            else if (title.equalsIgnoreCase("")) { //OK pressed without input

                JOptionPane
                    .showMessageDialog(null, "Please enter DVD title.");
            }//else if
            else //valid data
            {
               // do nothing, it will exit, and return below
            }//else

        }//while


        return title;
    }

Then in AddItem

  /**
     * This method is used to add the DVD
     */
    public void addItem() {

        // number should be greater then previous
        int lastElementIndex = movieArray.length - 1;
        int lastItemNumber = movieArray[lastElementIndex].getItemNumber();
        int newItemNumber = lastItemNumber + 1;

        String title = getDVDTitle();

        //--------------------------------------
        // value is null if user clicked cancel
        //--------------------------------------

        if (title == null){
            return; //user canceled, so return
        }

        //--------------------------------------
        // TO DO: Make cancel button work for 
        //        the other ones
        //--------------------------------------

        int numberOfUnits = getNumberOfItems();
        double unitPrice = getUnitPrice();
        String genre = getgenre();

        //--------------------------------------

        System.out.println();
        System.out.println("lastElementIndex: " + lastElementIndex);
        System.out.println("lastItemNumber: " + lastItemNumber);        
        System.out.println("item #: " + newItemNumber + "  title: " + title); …
cgeier 187 Junior Poster

I've added some println statements to the following code, to help you with runtime debugging:

Inventory:

sortProducts

   /**
     * This method is used to sort the products by DVD Title
     *
     * @param movieArray
     */
    private static void sortProducts(DVDMovie[] movieArray) {
        int length = movieArray.length;
        DVDMovie obj1 = null;
        DVDMovie obj2 = null;
        DVDMovie temp = null;

        //------------------------------------
        //add println statements for debugging
        //------------------------------------
        System.out.println("Before:");
        for (int p=0; p < length; p++)
        {
            System.out.println("itemNum: " +  movieArray[p].getItemNumber() + " Title: " + movieArray[p].getDVDTitle() );
        }//for

        //------------------------------------

        for (int i = 1; i < length; i++) {
            for (int j = 0; j < length - i; j++) {
                obj1 = movieArray[j];
                obj2 = movieArray[j + 1];
                if (obj1.getDVDTitle().compareTo(obj2.getDVDTitle()) > 0) {
                    temp = obj1;
                    movieArray[j] = movieArray[j + 1];
                    movieArray[j + 1] = temp;
                }
            }
        }


        //------------ ------------------------
        //add println statements for debugging
        //-------------------------------------
        System.out.println();
        System.out.println("After:");
        for (int q=0; q < length; q++)
        {
            System.out.println("itemNum: " +  movieArray[q].getItemNumber() + " Title: " + movieArray[q].getDVDTitle() );
        }//for

        //------------------------------------
    }

AddItem

    /**
     * This method is used to add the DVD
     */
    public void addItem() {
        // number should be greater then previous
        int lastElementIndex = movieArray.length - 1;
        int lastItemNumber = movieArray[lastElementIndex].getItemNumber();
        int newItemNumber = lastItemNumber + 1;
        String title = getDVDTitle();
        int numberOfUnits = getNumberOfItems();
        double unitPrice = getUnitPrice();
        String genre = getgenre();

        //------------ ------------------------
        //add println statements for debugging
        //-------------------------------------
        System.out.println();
        System.out.println("lastElementIndex: " + lastElementIndex);
        System.out.println("lastItemNumber: " + lastItemNumber);        
        System.out.println("item #: " + …
cgeier 187 Junior Poster

Inventory,

Alternatively,
In addItem,

instead of copying the array yourself:

for (int i = 0; i < movieArray.length; i++) {
            existingArray[i] = movieArray[i];
        }
        int newSize = existingArray.length + 1;
        movieArray = new DVDMovie[newSize];
        for (int i = 0; i < existingArray.length; i++) {
            movieArray[i] = existingArray[i];
        }
        movieArray[newSize - 1] = product;

you could do the following:

//System.arraycopy(copyFrom, 0, copyTo, 0, copyFrom.length);
        System.arraycopy(movieArray,0,existingArray,0,movieArray.length); //copy to a temp array
        movieArray = new DVDMovie[movieArray.length + 1]; //resize movieArray
        System.arraycopy(existingArray,0,movieArray,0,existingArray.length); //copy back to movieArray
        movieArray[movieArray.length - 1] = product;
cgeier 187 Junior Poster

In Inventory,

change line 306,

// Change from:
// unitPriceText.setText(DVD.getUnitPrice());

// To:
unitPriceText.setText(Double.toString(DVD.getUnitPrice()));

change line 307,
from:

// Change from:
//invValueText.setText(DVDMovie.getInventoryValue());`

// To:
invValueText.setText(Double.toString(DVDMovie.getInventoryValue()));

change line 312,

// Change from:
// restockingFeeText.setText(DVDMovie.getRestockingFee());

// To:
restockingFeeText.setText(Double.toString(DVDMovie.getRestockingFee()));

In addItem (line 217-218), you do the following:

// number should be greater then previous
        int lastElementIndex = movieArray.length - 1;
        int lastItemNumber = movieArray[lastElementIndex].getItemNumber();

However, you've previously sorted the array by "DVDTitle", in "sortProducts". Therefore, movieArray[movieArray.length - 1].itemNumber is not necessarily the DVD with the highest item number any more.

In DVDMovie,
lines 16-20 are hard-coded. You need to put your parameter values.

// Change from:
// this.itemNumber = 0;
//this.DVDTitle = "unknown";
//DVDMovie.unitsInStock = 0;
//DVDMovie.unitPrice = 0;
//this.setGenre("unknown");

this.itemNumber = itemNumber;
this.DVDTitle = dvdTitle;
DVDMovie.unitsInStock = unitsInStock;
DVDMovie.unitPrice = unitPrice;
this.setGenre(genre);

There may be more issues, but this should help.

cgeier 187 Junior Poster

I am trying to automate a login to a website and then navigate to a webpage and retrieve the html from the page. I found some examples of how to login, but am having difficulty figuring out how to navigate to another page once logged in. I've read some information about using cookies, but I haven't done much website programming and am not sure how to implement cookies into the code I've found. Any guidance would be appreciated

import java.net.*;
import java.io.*;



public class WebsiteLogin {

	 private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
	    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "username";
	    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "password";

	    private static final String LOGIN_USER_NAME = "myusername";
	    private static final String LOGIN_PASSWORD = "mypass";

	    private static final String TARGET_URL = "http://<mysite>.com/cgi-bin/member.cgi";

	public static void main(String[] args)
	{
        System.out.println("Running the program...\n");
        WebsiteLogin httpUrlBasicAuthentication = new WebsiteLogin();
        httpUrlBasicAuthentication.httpPostLogin();

	}

	   /**
     * The single public method of this class that
     * 1. Prepares a login message
     * 2. Makes the HTTP POST to the target URL
     * 3. Reads and returns the response
     *
     * @throws IOException
     * Any problems while doing the above.
     *
     */
    public void httpPostLogin ()
    {
        try
        {
            // Prepare the content to be written
            // throws UnsupportedEncodingException
            String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);

            System.out.println(urlEncodedContent);
            HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);

            String response = readResponse(urlConnection);

            System.out.println("Successfully made the HTPP POST.");
            System.out.println("Recevied response is: '/n" + response + "'");

        }
        catch(IOException ioException)
        {
            System.out.println("Problems encounterd.");
        }
    }

    /**
     * Using the given username …
cgeier 187 Junior Poster

You are missing a return statement. Also, to make it more effecient, use "else if" statements.

public static int[] negativePositive(int[] arr)   {
        int[] ret = new int[3];
        int i = 0, e = arr.length;
        while (i < e)
        {
            if (arr[i] < 0)
            {
                ret[0]++;
                i++;
            }
            else if (arr[i] == 0)
            {
                ret[1]++;
                i++;
            }
            else if (arr[i] > 0)
            {
                ret[2]++;
                i++;
            }
            return ret;
        }
cgeier 187 Junior Poster

You have to decide if you want it to be graphical or a console application. If you want to have a console app, use Scanner to allow the user to hit the enter key until they specify that he/she wants to quit (ex: by entering "q").

Use "java.util.Random" to generate random numbers < 100. Check if the product < 100. If not, re-generate either the 2nd number or both numbers (do this until the product is < 100). Print out the product. Repeat until the user specifies that he/she wants to quit the program.


Here's something to get you started:

do{
    ....
}while(product > 100);

*Hint: Use more than 1 do-while loop.

cgeier 187 Junior Poster

Remove the CMOS battery for 30-60 seconds.

cgeier 187 Junior Poster

To be honest with you, your code gives the appearance that you combined your code with someone else's code. Check your variable names. I would recommend to choose a variable naming standard for yourself. You used "hourlyRate" in one place and "hourly_rate" in other places. This gives the appearance that you copied someone else's code and it creates confusion for someone trying to read your code. Also, it means that you have undefined variables.

When doing String comparisons use ".equals", not "==".

Unless you change the Scanner delimiter, you are going to have to use "nextLine" to read (and discard) the "\n" (newline) of each line.

Scanner input = new Scanner( System.in );
input.useDelimiter("\n");
cgeier 187 Junior Poster

I think that your formulas are not correct.
http://math.about.com/od/formulas/ss/surfaceareavol_3.htm

Check the documentation for "Math.pow". You are raising radius to the power of radius.

To get data do something like the following:

Scanner scan  = new Scanner (System.in);

//change the delimiter from space to newline
in.useDelimiter("\n");

System.out.println ("Enter Radius:");

if (in.hasNextDouble()){
     //read in value from user
     radius = in.nextDouble();
}//if

Rather than passing the arguments "(0.0,0.0)", you should be passing the values for radius and height that you read from the user.

cgeier 187 Junior Poster

You probably didn't let it finish. Not sure about Sony's recovery process, but I recovered my computer with recovery disks from another manufacturer and it took 4-6 hrs. It may reboot multiple times during this process and it may appear to be finished, but it won't be finished until it either says it's finished or you get a message saying welcome to Windows.

cgeier 187 Junior Poster

How did you "try reformatting"? What exactly have you done? I suppose that it is possible that a power spike occured and if you weren't using a surge protector that it caused damage to your computer. But let's check out some other things first.

cgeier 187 Junior Poster

You'll probably need to download a Vista recovery DVD.
See http://blogs.techrepublic.com.com/window-on-windows/?p=622

Look under the heading "Getting the ISO".

Burn it to a DVD using "ISO Recorder". Boot from it, then do the following:

-Click "Next"
-Click "Repair your computer"
Microsoft Windows Vista should show up. If not, let me know.
-Click "Next"
-Click "Command Prompt"

type the following:

>chkdsk c: /f /r

when that finishes type:

>bootrec /FixMBR
>bootrec /FixBoot

>exit

Eject your dvd and click "Restart".

cgeier 187 Junior Poster

Press the "esc" key during booting and you should be able to see additional information.

cgeier 187 Junior Poster

Which "Java" did you install? The JRE or the JDK? I think that the JDK includes the JRE, but I'm not sure. You can also try to install the JRE.
http://java.sun.com/javase/downloads/index.jsp

Look for "Java SE Development Kit (JDK)".
It looks like the current one is "JDK 6 Update 16".

Make sure to choose "Platform: Windows x64".

After installing Java JDK and JRE, reboot and then re-install TextPad.

Something else you might check is to make sure that the "Java JDK" is in your Windows path.

cgeier 187 Junior Poster

Did you install the Java JDK before installing textpad? I would recommend using NetBeans, it's a free download and can save a lot of programming time.

cgeier 187 Junior Poster

Use "RandomAccessFile".
http://java.sun.com/j2se/1.4.2/docs/api/java/io/RandomAccessFile.html

private String readFirstLineOfFile(String fn){
        String lineData = "";

        try{
            RandomAccessFile inFile = new RandomAccessFile(fn,"rw");
            lineData = inFile.readLine();
            inFile.close();
        }//try
        catch(IOException ex){
            System.err.println(ex.getMessage());
        }//catch

        return lineData;

    }
cgeier 187 Junior Poster

It's undersirable (in my opinion) to make the user re-enter all five scores just because ONE of them was wrong. Ask for each score individually using a for (or while) loop. You can also use "switch-case" statements in place of "if/else if" statements.

Some considerations when writing a program include: execution time (not so important when first learning to program; more important later)--fewer lines of code do not necessarily mean less execution time, user experience --how easy is the program to use, what are it's limitations (what user input could cause it to crash), what are it's features, readability and maintainability--how easy is it for someone else to read, understand, and modify your code (ex: use descriptive variable names: score1,score2, score3 instead of: a,b,c). I'm sure you can come up with more, but these are a few to get you started.

You might consider making all your variables of type "double" to allow for non-integer values. ex: 94.5

cgeier 187 Junior Poster

I was able to find a solution on another site.

http://www.velocityreviews.com/FORUMS/t367758-unescaping-unicode-code-points-in-a-java-string.html

Here is the solution:

private static String unescape(String s) {
int i=0,len=s.length(); char c; StringBuffer sb = new StringBuffer(len);
while (i<len) {
     c = s.charAt(i++);
     if (c=='\\') {
          if (i<len) {
               c = s.charAt(i++);
               if (c=='u') {
                    c = (char) Integer.parseInt(s.substring(i,i+4),16);
                    i += 4;
               } // add other cases here as desired...
          }
     } // fall through: \ escapes itself, quotes any character but u
sb.append(c);
}
return sb.toString();
}
cgeier 187 Junior Poster

Check out the documentation for the scanner class.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

It will throw "NoSuchElementException" if no line was found. If you don't haven't learned about exception handling yet, I would use "hasNext".

int myInt = 0;
String myString = "";

Scanner in = new Scanner(System.in);
in.useDelimiter("\n");

if (in.hasNextInt()){
     //read in int value
     myInt = in.nextInt();
}//if
else if (in.hasNext()){
     //read in String value
     myString = in.next();
}//else if
cgeier 187 Junior Poster

Thanks for the reply. I'm trying to convert from a String (user entered value in a TextField) to a unicode character. I'm having trouble seeing how to get it from a String to a unicode character.

cgeier 187 Junior Poster

Just change the delimiter.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
cgeier 187 Junior Poster

Here's a possible solution. Not sure what you are trying to accomplish, but this sounds like it should do it. There are probably better options.

int i;
String myNumberAsString;
myNumberAsString = Integer.toString(i);

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#toString(int)

Then you can use the String function "charAt".

int indexNumber;
char desiredDigit;
String myDigitStr;
int myDigitInt;

desiredDigit = myNumberAsString.charAt(indexNumber);
//optional: convert back to an int
//convert back to String first
myDigitStr = Character.toString(desiredNumber);
//then, convert String back to int
myDigitInt = Integer.parseInt(myDigitStr);

System.out.println(desiredDigit);
jen140 commented: Thanks =) +1
cgeier 187 Junior Poster

The documentation for BufferedReader states the following ..."Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached." When you reach the end of the file, the value is "null".

http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine()

As Agni said, tmp is null which is why you are getting the NullPointerException. It happens because you try to do the following when tmp = null:

int letters = tmp.length();

You can use an "if" statement as Agni mentioned or just combine lines 31 and 32 as follows:

while ((tmp=br.readLine()) != null){
cgeier 187 Junior Poster

I am trying to write a program to display the unicode character when a user enters a unicode character code.

ex: If the user enters: "\u00C3" in the textfield, I want to display a capital "A" with a tilda (~) over the top of it. Here's my code so far:

Main.java

import javax.swing.*;
import java.awt.event.*;

public class Main {

    private static JTextField inputTextBox;
    private static JLabel displayLbl;

    public static void main(String s[]) {

        //create new frame
        JFrame frame = new JFrame("Unicode Characters");
       

        //add window listener
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });

        //create new JPanel
        JPanel contentPane = new JPanel();

        frame.setContentPane(contentPane);

        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        contentPane.setBorder(BorderFactory.createEmptyBorder(100,100,100,100));

        inputTextBox = new JTextField(JTextField.CENTER);
        displayLbl = new JLabel();

        //this sets the text to what the user would enter
        inputTextBox.setText("\\u00C3");
        JButton showBtn = new JButton();

        showBtn.setText("Show");
        displayLbl.setText(" ");


        //add objects to JPanel
        contentPane.add(inputTextBox);
        contentPane.add(displayLbl);
        contentPane.add(showBtn);

        frame.pack();
        frame.setVisible(true);


        //add listener for button
        showBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                //do something, in this case we call method
                //showBtnActionPerformed
                showBtnActionPerformed(evt);
            }
        });


    } //main

 
  private static void showBtnActionPerformed (java.awt.event.ActionEvent evt){
        String userText;
        char myUnicodeChar;

        //get user inputed unicode character ex: \u00C3
        userText = inputTextBox.getText();

        //display character for unicode code
        displayLbl.setText("" + userText);

        //the line below displays what I want to display
        //but I want the user to be able to enter "\u00C3"
        //and then I want to display the character that is
        //represented by it.
        //displayLbl.setText("\u00C3");


    } //showBtnActionPerformed

}
cgeier 187 Junior Poster

Use a for loop in you "vowelCount". Also, you can't print an array like that, use a for loop for that too. Look over the usage of "substring" again.

cgeier 187 Junior Poster

Check out "ArrayList", it resizes itself as necessary. If you choose to use it, you would create an "ArrayList" of your class (ex: "Employee").

cgeier 187 Junior Poster

When using scanner if you use "next()", the data is in String format and needs to be converted. If you use, "nextInt" or "nextDouble", it converts the data for you automatically--consider using "hasNextInt()" or "hasNextDouble()" as well. Here's something to get you started. Create a new scanner.

Scanner in = new Scanner(System.in);

If you read data using, "next()", to convert to an Integer, use "Integer.parseInt(myStringData)".

cgeier 187 Junior Poster

See the post #7 in the following article:
http://www.daniweb.com/forums/post999241.html#post999241 . The "isInteger" method, basically does this, but rather than exiting the program, it returns false. You could use it as is (call the "isInteger" method), and then if it returns false, you have encountered a non-integer and can exit your program.

cgeier 187 Junior Poster

When you are reading these integers in from your file, you can either insert them into an array, or just add them together as you read the line. When you read a line in from file, if you read it as text do the following to convert it to an integer:

String lineData;
int numberOfRolls;
int total = 0;

//while not end of file
//the line below is pseudo-code--meaning a combination
//of Java and plain English, it is up to you to write it properly in Java
while (!eof){ 
     //To Do: read line from file and put it in variable "lineData"

     //Optional: see if data contains only numeric values
     //(hint: use "isInteger")

     //convert String to int
     numberOfRolls = Integer.parseInt(lineData);

     //add numbers together as they are read in
     total = total + numberOfRolls;
}

The only thing, is that "Integer.parseInt(lineData)" will throw an error if lineData contains data that can't be converted to an integer. To prevent this you can check the data before trying it. There are two versions of a method called "isInteger" in the following post that will check the data:
http://www.daniweb.com/forums/post999241.html#post999241 . But you wrote the data to the file and you know that it only contains integers, so checking to see if the data is an integer may be unnecessary.

cgeier 187 Junior Poster

Change the following line from:

Scanner number = new Scanner ( System.in );

To:

static Scanner number = new Scanner ( System.in );

OR better yet, just move it inside of the main method:

public static void main(String[] args)
{
     Scanner number = new Scanner ( System.in ); 
     int firstValue;

     System.out.print( "Please enter time in hours:" );
     firstValue = number.nextInt();
}

See my some of my posts in the following article on how to do error checking with scanner:
http://www.daniweb.com/forums/post998852.html#post998852

Also see the following article about using "static":
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Teethous commented: Super helper. +1
cgeier 187 Junior Poster

Post what you tried, and so we can see why it didn't work.

cgeier 187 Junior Poster

I'm having trouble seeing how to do it with a for loop. Maybe you can provide an example. In my example, "trialCount++" would actually be inserted on line #13, since the trial is only complete when random number = winning number.

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));
int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               outFile.println(rollCounter);
               //winning number is found, this trial is complete
               trialCounter++;
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();

Ok, I guess I made a mistake in this posting, you could place "trialCounter++" where VernonDozier said to place it, or you could place it where I placed it--either place should work.

cgeier 187 Junior Poster

In my post earlier about using scanner, you can change the token delimiter as follows:

Scanner in;  
in = new Scanner(System.in);
in.useDelimiter("\n");

This changes the delimiter from the default of using white space, to using the newline character. To see the difference, when running my previous example and prompted for data enter "a b c". Do this without the line: in.useDelimiter("\n") and then with it and see the difference.

cgeier 187 Junior Poster

You can also add some debugging information.

int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

//change debugProgram to "true" if you want to see additional info
boolean debugProgram = false;

do{
     //re-initialize roll counter
     rollCounter = 0;
     if (debugProgram == true){
          outFile.println("Trial: " + trialCounter);
     }//if

     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               //print information to help in debugging
               if (debugProgram == true){
                    outFile.println("Roll Number: " + rollCounter + " Total Rolls: " + rollCounter + " Random Number: " + randomNumber);
                    outFile.println("");
               }//if
               else{
                    //used during normal operation
                    //when debugProgram = false;
                    outFile.println(rollCounter);
               }//else

               //winning number is found, this trial is complete
               trialCounter++;
          }//if
          else{
               //print information to help in debugging
               if (debugProgram == true){
                    outFile.println("       Roll Number: " + rollCounter + " Random Number: " + randomNumber );
               }//if
          }//else
 
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();