Comparing an Item in a List to...

Hello. I'm new to these forums, and this is my first post here. I'm working on a hangman game just for fun, and I've run into a snag. When it checks to see if the key pressed is equal to (or the same as) the letter in position x. Every time, even if the letter is in the word, it returns false and does nothing. I hope this is clear. Below is my entire code (just to give you an idea of how this works) of my main class. There is another class that contains methods, but it does not affect this problem.
Also note that I am fairly new to Java, but have been programming in Python for about half a year now (taking a programming class at my High School). I also so PHP, but even with a good programming background, I still seem to run into snags while programming in Java.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Hangman extends JFrame implements ActionListener, KeyListener {
    // Initiate some global variables
    int num_guesses;
    String word;
    String end_round = "yes";
    String[] blanks;
    String[] letters;
    // Get the word list
    String location = "C:/Documents and Settings/AMT/My Documents/My Programs/Java/Hangman/build/classes/hangman_words.txt";
    Vector words = hmFunctions.getWords(location);
    Vector backUpWords = words;
    // Create the main buttons
    JButton hint = new JButton("Hint");
    JButton giveup = new JButton("I Give Up");
    JButton help = new JButton("Help");
    JButton about = new JButton("About");
    JButton quit = new JButton("Quit");
    // Create the main window and add componants
    public Hangman() {
        super("Hangman v1.0");
        setSize(631, 510);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Create the main pane
        Container hm_pane = getContentPane();
        hm_pane.setLayout(null);
        hm_pane.setFocusable(true);
        hm_pane.addKeyListener(this);
        // Set the button properties
        hint.setBounds(new Rectangle(2, 444, 100, 30));
        hint.addActionListener(this);
        giveup.setBounds(new Rectangle(130, 444, 100, 30));
        giveup.addActionListener(this);
        help.setBounds(new Rectangle(260, 444, 100, 30));
        help.addActionListener(this);
        about.setBounds(new Rectangle(390, 444, 100, 30));
        about.addActionListener(this);
        quit.setBounds(new Rectangle(520, 444, 100, 30));
        quit.addActionListener(this);
        // Add Componants to interface pane
        hm_pane.add(hint);
        hm_pane.add(giveup);
        hm_pane.add(help);
        hm_pane.add(about);
        hm_pane.add(quit);
        setContentPane(hm_pane);
        setVisible(true);
    // Check to see if they clicked anything
    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == hint) {
        } else if (source == giveup) {
        } else if (source == help) {
            JOptionPane.showMessageDialog(null, "JHangman v1.0 Help...");
        } else if (source == about) {
            JOptionPane.showMessageDialog(null, "JHangman v1.0\nProgrammed by...");
        } else if (source == quit) {
            System.exit(0);
    // Check if user pressed any keys
    public void keyTyped(KeyEvent key_event) {
        if (end_round == "yes") {
            mainGame("start");        
        } else if (end_round == "no") {
            Character key = key_event.getKeyChar();
            String let = key.toString();
            System.out.println("Letter Pressed: " + let);
            mainGame(let);
    public void keyPressed(KeyEvent key_event) {  
    public void keyReleased(KeyEvent key_event) {
    // The check letter method
    public void mainGame(String funct) {
        if (funct == "start") {
            num_guesses = 0;
            // Check if words empty
            if (words.size() == 0) {
                words = backUpWords;
            // Get word needed for the game and back up
            word = hmFunctions.getRndWord(words);
            words.remove(word);
            // Create the blanks and letters vector
            letters = new String[word.length()];
            blanks = new String[word.length()];
            // Make the blanks and letters and draw interface
            for (int a = 0; a < word.length(); a++) {
                blanks[a] = "_";
                letters[a] = word.substring(a, a + 1);
            System.out.println("Game Started!");
            System.out.println("Blanks and letters added successfuly!");
            end_round = "no";
        // If no other instruction given, then check to see if key pressed is in the word
        } else {
            for (int x = 0; x < word.length(); x++) {
                if (funct == letters[x]) {
                    blanks[x] = funct;
                System.out.println(blanks[x] + " ");
            num_guesses += 1;
            if (num_guesses == 8) {
                end_round = "yes";
    // Main Program
    public static void main(String[] arguments) {
        hmFunctions hm_fct = new hmFunctions();
        // Draw the main interface
        Hangman HM_Window = new Hangman();
}Any help would be greatly appriciated!

Of course, looking more closely, you do seem to be assigning the literal reference into the String object reference. In String s = "a string literal";
if ( s == "a string literal" )
  // process
} you may actually get into the if block. I would have to test to be sure. However, in general practice, if you want to check to see if two String objects have the same contents, use equals(). If you want to see if two object references point to the same location in memory, use ==. Primitives, of course, are compared with ==.
Your keyTyped() method checks for two values of end_round. Have you checked for neither the if nor the else conditions being true?
Do you know if you are getting into your mainGame() method? Try putting a println() in as soon as you enter, so you know you got there and you know the actual parameter value.
� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How to create new subsite while adding new item to the list by using javascript?

    hi,
    I hav a task ie, when I add item to the list then subsite will create with that list item title and description . So By using javascript, I have to create subsite while adding new item to the list.
    Help me to solve this.
    Thank you, 

    Is your item getting added through Javascript client object model ? If yes, you can write in the success delegate of your list creation method the logic to create the subsite.
    function CreateListItem()
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('List Name');
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.set_item('Title', 'My New Item!');
    oListItem.set_item('Body', 'Hello World!');
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.CreateListItemOnSuccess), Function.createDelegate(this, this.onQueryFailed));
    function CreateListItemOnSuccess() {
    var subsiteTitle = oListItem.get_item('Title');
    //Logic to create a subsite
    function onQueryFailed(sender, args) {
    I have added a sample flow for the above scenario. Have a look at the following lnk for how you can craete a subsite using ecmascript.
    http://ravisoftltd.wordpress.com/2013/03/06/sharepoint-2010-create-site-with-ecma-script-with/
    Geetanjali Arora | My blogs |

  • Report on delivery data in item level for list of po

    Dear all
             How to take Report on delivery data in item level for list of po
    regards
    M.Chandra mohan

    You can check any of the standard reports like ME2M with the selection variant as "PO where GR exists"

  • How to move items from one list to other

    hi all,
    in jsp page i have twolist boxes. i want to move item from one list to other list on click of add or move button. can u plz suggest me an answer for the above. thank u
    Regards sangeet

    This link should help. Remove from one list and add to the other using Javascript.
    http://www.mredkj.com/tutorials/tutorial006.html

  • How can i get more than 1000 items in Custom List Displaying Items?

    http://.....sites/_vti_bin/listdata.svc/AddressBook(List) allows 1000 items Only my AddressBook List, but i have more than 1000 items in my AddressBook list. I want to get items
    from AddressBook list and bind in another place using Autocomplete method like this.
    =======>>>>listurl=http://.....sites/_vti_bin/listdata.svc/AddressBook.
    and my coding in camel like below
    protected void btnpopulatedetails_Click(object sender, EventArgs e)
    SPSite objSite = SPContext.Current.Site;
    SPWeb objWeb = objSite.OpenWeb();
    objWeb.AllowUnsafeUpdates = true;
    SPList list = objWeb.Lists["Address Book"];
    SPQuery query = new SPQuery();
    query.QueryThrottleMode = SPQueryThrottleOption.Override;
    query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + txtcustomer.Value + "</Value></Eq></Where>";
    query.RowLimit = 500;
    SPListItemCollection items = list.GetItems(query);
    function fnCustomerSearchBind() {
    if ($("input[id$='txtcustomer']").length != 0) {
    var collcustomer = searchCustomers('', urlTo, fieldto);
    $("input[id$='txtcustomer']").autocomplete({
    source: collcustomer,
    //maxLength:10,
    select: function (event, ui) {
    //debugger;
    event.preventDefault();
    $("input[id$='txtcustomer']").val(ui.item.value);
    $("input[id$='btnpopulatedetails']").click();
    return false;
    minLength: 0,
    function searchCustomers(value, listurl, fieldto) {
    var collcus = new Array();
    var custresults;
    var url =listurl + "?$filter=startswith('" + fieldto + "','" + value + "')";
    //debugger;
    $.ajax({
    cache: true,
    type: "GET",
    async:false,
    dataType: "json",
    url: url,
    success: function (data) {
    custresults = data.d.results;
    //alert(listurl);
    // alert(data.d.results);
    for (var x = 0; x < custresults.length; x++) {
    //alert(custresults[x]['To']);
    collcustList.push(custresults[x]['To']);
    //debugger;
    //debugger;
    return collcustList;
    In my research listurl=http://.....sites/_vti_bin/listdata.svc/AddressBook has 1000 items in 1st Page by default, So how to change 1st Page by default to All Pages through
    code. I think you understand my environment by look above coding, if you don't I am using office 365 sandbox solution. One more thing i know through my research Pages can be change by using Ado.Net Data Service, i tried this one but this one support windows
    server 2008 r2 only but i am using Windows Server 2012 r2. Please help me if you know the answer.

    Hi,
    Here is a blog would be helpful:
    ADO.NET Data Services returns 1000 items
    https://gilleslauwers.wordpress.com/2010/12/08/ado-net-data-services-returns-1000-items/
    Best Regards,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • How to create a background image for each item in a List object

    Hello.
    I am trying to create a background image that displays whenever a user posts something to a list.  For example when a user posts text it would appear in a list.  The new item in the list would contain a specific background image with the users text appearing on top of the background image.  I do not want a background image for the entire list, rather each item within the list.
    I am not sure how clear this is so I added an image below.  When a user enters text in and clicks the "post-it" button their text would appear below with the sticky note background. 
    I am not sure which list type would be best for this problem or how to create insert the image, so I am open to suggestions. 
    Thank you for your help.  Any advice or guidance will be greatly appreciated!

    Hi
    the easiest way would be with itemRenderer.
    You have to do two things:
    1. In your list declaration use a item renderer: <mx:List itemRenderer="myRenderer"/>
    2. create a flex component myRenderer that will be the single item. This can be a canvas with a background image and a text field on it.
    When you add a new item to the list, a new myRenderer item will be created and the data property will be passed to it. So you have to put "data" in your textField.
    If you need more help try looking at Tour de Flex samples, they're pretty easy.
    Andrei

  • How to limit the number of items that a list control can hold?

    Hi,
    I am using a Flex3 List control for one of my projects.
    I add drag & drop functionality to it, so that i can drag & drop elements from one control to another.
    How to limit the number of items that a list control can hold / can be dropped in a list control ?
    - Sen.

    1. Listen for the dragdrop event on the control you are dragging onto.
    2. check the length of the items in the dataprovider - if it exceeds your maximum override the default drop action with e.preventDefault(); (assuming you used e for the event on the handler).
    Regards,
    Mark.

  • How: can i get a specificated item from a list with more than 100.000 items

    Hi,
    i have a very large list and i got always an exception that the list has more than 5000 items and cant query!! But in the default list view i can see, order and filter all items. So how can i do this by c#?

    Hi,
    According to your description, my understanding is that you want to get a specific list item form a list which with more than 100000 items using C#.
    I suggest you can use CAML Query with some condition and set Row Limit to specify the number of items to return.
    Here is a detailed code demo for your reference:
    Client Object Model Access Large Lists/Overcome ListView Threshold while accessing large list
    Thanks
    Best Regards
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • How can I select an item from a list component with a seperate button

    This is a repost, I decided it'd probably be better here than
    in the general discussion board. I will try to delete the other
    one.
    Hello Everyone,
    This is my first post here. I am trying to figure out how to
    select an item within a list component with a button. This button
    is calling a function. I have searched for the past 3 hours online
    and I can't find anything about it. I thought perhaps I could set
    the selectedItem parameter, but that is read only, and I believe it
    returns an object reference rather than something like a number so
    even if i could set it, it would be pointless. I also found a get
    focus button, thought that may lead me somewhere, but I think that
    is for setting which component has focus currently as far as typing
    in and things like that. I am lost.
    Basically I am looking for a way to type this
    myList.setSelected(5); where 5 is the 5th item in the list.
    Any help would be much appreciated.

    Never mind found it. It is the property called selectedIndex
    and it is writable

  • The drop-down list that appears when typing in the Google search bar doesn't work. Clicking on an item on that list does nothing. This very useful feature is broken.

    I just installed FireFox 4. In previous versions typing in the Google search box automatically created a drop-down list of items. One could click on an item on the list and proceed to a Google results page. In FireFox 4, the list appears but clicking on an item on the drop-down menu does nothing. It's broken and it was a very useful feature in previous versions.

    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]

  • How to get items from a list that has more items than the List View Threshold?

    I'm using SharePoints object model and I'm trying to get all or a subset of the items from a SharePoint 2010 list which has many more items than the list view threshold (20,000+) using the SPList.GetItems() method. However no matter what I do the SPQueryThrottledException
    always seems to be thrown and I get no items back.
    I'm sorting based on the ID field, so it is indexed. I've tried setting the RowLimit property on the SPQuery object(had no effect). I tried specifying the RowLimit in the SPQuerys ViewXml property, but that still throws a throttle exception. I tried using the
    ContentIterator as defined here:http://msdn.microsoft.com/en-us/library/microsoft.office.server.utilities.contentiterator.aspx,
    but that still throws the query throttle exception. I tried specifying the RowLimit parameter in the ProcessListItems functions, as suggested by the first comment here:http://tomvangaever.be/blogv2/2011/05/contentiterator-very-large-lists/,
    but it still throws the query throttle exception. I tried using GetDataTable instead, still throws query throttle exception. I can't run this as admin, I can't raise the threshold limit, I can't raise the threshold limit temporarily, I can't override the lists
    throttling(i.e. list.EnableThrottling = false;), and I can't override the SPQuery(query.QueryThrottleMode = SPQueryThrottleOption.Override;). Does anyone know how to get items back in this situation or has anyone succesfully beaten the query throttle exception?
    Thanks.
    My Query:
    <OrderBy>
        <FieldRef Name='ID' Ascending='TRUE' />
    </OrderBy>
    <Where>
        <Geq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Geq>
    </Where>
    My ViewXml:
    <View>
        <Query>
            <OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy>
            <Where>
                <Geq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Geq>
            </Where>
        </Query>
        <RowLimit>2000</RowLimit>
    </View>
    Thanks again.

    I was using code below to work with 700000+ items in the list.
    SPWeb oWebsite = SPContext.Current.Web;
    SPList oList = oWebsite.Lists["MyList"];
    SPQuery oQuery = new SPQuery();
    oQuery.RowLimit = 2000;
    int intIndex = 1;
    do
    SPListItemCollection collListItems = oList.GetItems(oQuery);
    foreach (SPListItem oListItem in collListItems)
    //do something oListItem["Title"].ToString()
    oQuery.ListItemCollectionPosition = collListItems.ListItemCollectionPosition;
    intIndex++;
    } while (oQuery.ListItemCollectionPosition != null);
    Oleg
    Hi Oleg, thanks for replying.
    The problem with the code you have is that your SPQuery object's QueryThrottleMode is set to default. If you run that code as a local admin no throttle limits will be applied, but if you're not admin you will still have the normal throttle limits. In my
    situation it won't be run as a local admin so the code you provided won't work. You can simulate my dilemma by setting the QuerryThrottleMode  property to SPQueryThrottleOption.Strict, and I'm sure you'll start to get SPQueryThrottledException's
    as well on that list of 700000+ items.
    Thanks anyway though

  • Hide "more" button in a list view, only works for first item in the list

    I have the following code in a list view that outputs several dozen items in a web app.  The code only works for the first item, how can I make it loop through and execute the test for each item in the list view?  The {tag_hide more button} is a checkmark field that yields a numeric 1" if checked otherwise yields a numeric "0".
    <div id="more-option">
            <p class="right"><a href="{tag_itemurl_nolink}" class="btn btn-small btn-very-subtle">More &rarr;</a></p>
          </div>
          <div class="more-selection" style="display: none;">{tag_hide more button}</div>
          <script>
    if ($(".more-selection").text() == "1") {
        $("#more-option").hide();
    </script>

    What's the URL for the site where you are using this?  Offhand, it looks like it should work with your first example so you are either placing the script before those elements are loaded or you might try wrapping your current javascript inside the:
    $(document).ready(function() {
    --- your existing javascript here
    This make sure the code runs once all the html is loaded on the page.  Without seeing a URL and debugging with the js console in Chrome I can't give you a solid answer.
    But, I do know that you can probably do this with a lot less markup.  Once we figure out what the actual problem is I have a better solution mocked up for you on jsfiddle.
    When looking at my HTML code on jsfiddle, please realize I setup some dummy HTML and removed your tags and added actual values which would be output by your tags.  The main thing I did was remove the whole div.more-selection and instead, added a "data-is-selected" attribute on your div.more-option element.  Then, in my javascript for each div.my-option element on the page, we loop through them, find the value of that data attribute and hide that div if it's less than 1 (or 0).
    Here's the fiddle for you to look at:  http://jsfiddle.net/thetrickster/Mfmdu/
    You'll see in the end result that only two divs show up, both of those divs have data-is-selected="1".
    You can try pasting the javascript code near the closing </body> tag on your page and make sure to wrap my js inside a <script> tag, obviously.  My way is neater on the markup side.  If you can't get it to work it's likely a jquery conflict issue.  My version is using the $(document).ready() method to make sure all the code is loaded before it runs.
    Best,
    Chris

  • Open references of other list items from a list item in the same window or tab

    Hi there,
    We have migrated from lotus notes to sharepoint. We have converted the lotus notes forms to sharepoint forms. Basically the list items are pages and there are links of other pages in a page.
    My problem is I want to open the other pages in the same tab or window and not in a separate window.(currently the links open in a separate window which is not the requirement.)
    In terms of sharepoint I would say,
    I have references(links)  to other list items of the list in a single list item. I want to open the other list items in the same window (tab).
    How can we achieve this?? If possible without much codes??
    Please suggest.
    Any help will be highly appreciated.
    Thanks in advance

    See:
    *http://kb.mozillazine.org/browser.link.open_newwindow
    *1: current tab; 2:new window; 3:new tab;
    For links opened via JavaScript you can look at this pref:
    *http://kb.mozillazine.org/browser.link.open_newwindow.restriction
    You can open the <b>about:config</b> page via the location/address bar.
    You can accept the warning and click "I'll be careful" to continue.
    *http://kb.mozillazine.org/about:config

  • I accidentally deleted items from a list in reminders.  how can i retrieve them?

    i accidentally deleted items from a list in reminders.  how can i retreive them from icloud?

    From your backup.

  • Removing specific items from a list

    Hi all,
    i have the following problem:
    I have a list component on stage.
    I have 10 Items in the list , selected index is 5.
    Now i want to delete all the items above 5 (6-10).
    I think an array would be a solution but im not so kind with
    this so i need your help.
    Thank you
    Simon

    if the instance name of your list is myList, then the
    following code will remove all items after the currently selected
    item:

Maybe you are looking for

  • Error when Trying to Upgrade from 8.1.7.4 to 10.2.0.3

    Hello - I am getting this error, when attempting to run the ultu102i script in preparation for an upgrade to 10g: SQL> @utlu102i DECLARE ERROR at line 1: ORA-01403: no data found ORA-06512: at line 1560 I have upgraded many databases to 10g from 8i,

  • ITunes 9 has lost my music

    "Upgraded" to Itunes 9 and subsequently all the music I have uploaded from my CD collection over the years has been lost. Itunes cannot locate original files. Tried reimporting library but to no avail. Help!

  • Call selection screen on screen.

    hi experts, how can i call a selection screen as a subscreen in a normal screen. thanks.

  • Use iPhoto album for screensaver

    Using Yosemite 10.10.2 and iPhoto 9.6.1.  I want to use an iPhoto Album as the Screensaver; I have been doing this for years with all previous OS and iPhoto versions.  Now, the "Source" in the System Preferences: Screensaver Pane: My Pictures has a l

  • ORACLE Migration Tool Download is dead

    http://download.oracle.com/otn/nt/omwb/101020/Omwb.zip can't download, tried it the whole day :(