Comparing char in a string to strings in a txt file

Hi guys, i am dveloping a scrabble application for a project in jvava. Currently, i am trying to work on coding a computer player to play against a human, ive finished all the game logic nd 2 human players can successfully play on the same system.
My problem is when coming up with the AI logic, i am faced with the problem of how to compare the computer player's letters to the dictionary txt file in order to find the possible words he can play.
For example, the PC player has the letters A,B,E,G,T,F in his rack, it searches the dictionary and finds words that also contain these characters, so it would return words like AT, BAT, GATE, etc. I have already looke up the Jumble algorithm, but i dont really understand it(im still quite new to java).
I already have a ditionary class which i put the code below.
What i want to do now is just to come up with a simple method that takes a string, and compares the chars, and find words that match the char and return them but i dont knw hw to come about it.
import java.util.Scanner;      
import java.io.IOException;  
import java.util.ArrayList;   
import java.io.*;             
public class Dictionary
    ArrayList<String> dictionary;
    public Dictionary() throws IOException
        dictionary = new ArrayList<String>();
    public void readInDictionaryWords() throws IOException
        File dictionaryFile = new File("c:/data/dict.txt");    // declare the file
        if( ! dictionaryFile.exists()) {
            System.out.println("*** Error *** \n" +
                               "Your dictionary file has the wrong name or is " +
                               "in the wrong directory.  \n" +
                               "Aborting program...\n\n");
            System.exit( -1);    // Terminate the program
        Scanner inputFile = new Scanner( dictionaryFile);
        while( inputFile.hasNext()) {
            dictionary.add( inputFile.nextLine().toUpperCase() );
    public boolean wordExists( String wordToLookup)
        if( dictionary.contains( wordToLookup)) {
            return true;    // words was found in dictionary
        else {
            return false;   // word was not found in dictionary
    return"";
}

Loops...
You take the first
then second
then third
and etc
You take the first 2
the next 2
the next 2
etc
all the way through n characters
once you have gone through this, then you have to do all possible combinations of characters of 2 through n.
Here is an implementation of N choose k for k up to 7:
public class Junk {
  public Junk(){
  public void choose1(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      System.out.println("("+s.charAt(i)+")");
      lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose2(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
          System.out.println("("+s.charAt(i)+", "+s.charAt(j)+")");
          lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose3(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
        for(int k=j+1; k<s.length(); k++){
          System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+")");
          lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose4(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
        for(int k=j+1; k<s.length(); k++){
          for(int l=k+1; l<s.length(); l++){
            System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+")");
            lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose5(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
        for(int k=j+1; k<s.length(); k++){
          for(int l=k+1; l<s.length(); l++){
            for(int m=l+1; m<s.length(); m++){
              System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+")");
              lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose6(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
        for(int k=j+1; k<s.length(); k++){
          for(int l=k+1; l<s.length(); l++){
            for(int m=l+1; m<s.length(); m++){
              for(int n=m+1;n<s.length(); n++){
                System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+")");
                lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public void choose7(String s){
    int lCount=0;
    for(int i=0; i<s.length(); i++){
      for(int j=i+1; j<s.length(); j++){
        for(int k=j+1; k<s.length(); k++){
          for(int l=k+1; l<s.length(); l++){
            for(int m=l+1; m<s.length(); m++){
              for(int n=m+1; n<s.length(); n++){
                for(int o=n+1; o<s.length(); o++){
                  System.out.println("("+s.charAt(i)+", "+s.charAt(j)+", "+s.charAt(k)+", "+s.charAt(l)+", "+s.charAt(m)+", "+s.charAt(n)+", "+s.charAt(o)+")");
                  lCount++;
    System.out.println("Distinct Combinations: "+lCount);
  public static void main(String[] args) {
    Junk j = new Junk();
    j.choose7("1234567");
}I'll leave it to you to integerate the algos into your app appropriately.

Similar Messages

  • How to read in text string pairs from an external txt file?

    I have an external txt file containing 26000 pairs of strings in the format
    string1a   string1b
    string2a   string2b
    string26000a string26000b
    all strings are always 4 characters in length.  For example,
    a123   jkdh
    b456   uusp
    How can use TestStand 2013 to input this data into local string array varaibles?  I also have legacy testers running TestStand 3.5, so I need a TestStand 3.5 solution as well.  Thanks in advance for any ideas.  Hopefully this can be done in TestStand without the use of LabView or LabWindows/CVI.

    Daniel E., thanks for the reply. 
         It is very frustrating to have to implement workarounds in order to access text in an external file when using TestStand.  TestStand already reads in text ini files, so it would probably take a TestStand software developer all of 1/2 day to write the code and 1/2 day to debug it.  Here I will restate the obvious.  Engineers have to deal with data, sometimes data generated from other applications.  Sharing data in a text file is one of the most basic functions (and one of the easiest to implement).  When I think of all the effort needed to support ActiveX, but NI did not see it fit to give TestStand users simple text file read/write functionality, it does not make sense to me.  Maybe it was too simple or mundane a task so it did not get developed?  Whatever the reason, I think users of TestStand deserve this basic functionality.
         Even if TestStand cannot read the data directly into array variables, it should provide some mechanism to read the text from the file, either line by line or all file text into a string, so the data could then be parsed into the array variables I need.
         I will pursue a CVI or LabView solution.  Please also know that I am not directing these comments at you, I do appreciate your reply.
    Regards,
    Ron

  • Update string table from continious reading "*.txt" file

    Hello community ,
    I read a txt file continiously and try to catch the next data written each time the txt file is modified. My problem is that I can't use an event structure inside the while loop to catch the new data written.
    So the process write new data in the txt file line per line without erasing previous data like this:
    data1
    data2
    data3
    etc....
    I just want to catch the new data writen when it's written.
    Thank for any inputs......
    Attachments:
    zip.zip ‏11 KB

    What you are doing is basically what you have to do, you must poll the file somehow.  If you have an event structure you can always use the timeout event to time the polling.
    The only other workaround would depend on the producer of the data file.  If it is a LabVIEW program you cna make it send the consumer VI an event telling it to read.  Although at that point I would just have it send the data.

  • Anyone know how to add a string to a 1d array with file info, then be able to read back, display string, and sort data array.

    I need to store a data array and include text that describes what the data is. (using for various configuration files.) Anyway, I would like to be able to save the string as part of the txt file, and somehow read it back, remove the (various length string), and display it in an indicator. All the while, not causing too much problem with the initial data array.
    Thanks in advance!!

    There are several ways to do what you require. A simple method would be to use an ASCII text file. When writing one of those, you just need to basically build a gaint string starting with the description text you want. We like to call that a header. Once you've got the header, make some sort of delimiter like a bunch of "-" or two sets of ( EOL = End of Line = CRLF = \r\n ). After your delimiter, concatenate your array in string form or flatten your array from its native form into a string and tack it on the file (append).
    See the (very quick) example attached.
    Dan Press
    www.primetest.com
    Attachments:
    fileheader.vi ‏41 KB

  • URGENT! I need to compare a String with a line in a .txt file

    I'm a college student and I have a very simple question i guess. I need to write an if procedure which compares if a line of a .txt file is equal to something, but I just don't know how to do it. HELP!

    What specifically are you asking for? How to compare two strings?
    String s = "cat";
    String t = "Cat";
    if (s.equals(t))
       System.out.println('They are equal');    // does not print out
    if (s.equalsIgnoreCase(t))
       System.out.println('They are equal');    // prints out

  • Comparing a String with another one from a file

    I read a line from a .txt file using in.readLine();
    How do i make comparesson to see if the word in the file is "zoo" ?
    String read;
    read = in.readLine();
    System.out.println(read) --- > prints "zoo"
    if (read == "zoo")
    System.out.println("it works");
    else
    System.out.println("doesn't work");
    and this code prints out "doesn't work" even tho zoo is same as zoo... how do i fix this?

    Change if (read == "zoo") to:
    if(read.equals("zoo"))You want to compare the String's content, not the reference.

  • How do I compare chars?

    Hi!
    I've got a problem comparing chars. Is there a way to check that a char is "earlier" than another one?
    By "earlier" i mean that for example A is earlier than B, B is earlier than C etc.
    Thanks in advance!

    DrClap wrote:
    BigDaddyLoveHandles wrote:
    The javadoc for compareToIgnoreCase states:
    This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character. Why use both toUpperCase and toLowerCase?Probably something to do with either the Turkish i's problem or the &szlig; character.I see now. For example: upper case versus lower case versus title case -- it's not either/or.
    [http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isTitleCase(int)]

  • Comparing char to a value

    How do you compare a value of a character to another value...I don't really know how to explain here is my code
          int x=1;
          int[] answer;
          String newString="";
          String result=enter.getText();
          int size=result.length();
          char theCharacter;
          for(x=1; x<=size; x++)
            theCharacter = result.charAt(x);
            while(theCharacter != " " && x <= size)
              newString=newString+result.charAt(x);
            answer[x]=Integer.parseInt(newString);
            enter.setText("");
          }I am trying to take input from a textbox and read the input until I get to a space basically.

    You could try.
    String newString = "";
    int iSpace = result.indexOf(" ");
    if (iSpace >=0)
    newString = result.substring(0,iSpace);
    else
    newString = result;

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • Replace the text numbers string in a txt file using C++.. Help Me..

    Read a Document and replace the text numbers in a txt file using c++..
    For ex: 
    Before Document: 
    hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
    twenty-five. 
    After Document: 
    hai hello my daily salary is # and your salary is #. my age is #. 
    All the text numbers and i put the # symbol.. 
    I am trying this code: 
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    ifstream myfile_in ("input.txt");
    ofstream myfile_out ("output.txt");
    string line;
    void find_and_replace( string &source, string find, string replace ) {
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; ) {
    source.replace( j, find.length(), replace );
    myfile_out << source <<endl;
    cout << source << endl;
    int main () {
    if (myfile_in.is_open())
    int i = 0,j;
    //string strcomma ;
    // string strspace ;
    while (! myfile_in.eof() )
    getline (myfile_in,line);
    string strcomma= "two";
    string strspace = "#";
    find_and_replace( line , strcomma , strspace );
    i++;
    myfile_in.close();
    else cout << "Unable to open file(s) ";
    system("PAUSE");
    return 0;
    Please help me.. Give me the correct code..

    Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
    Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
    Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
    When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

  • ORA-31495 error in synchronous change table on "string"."string"

    IN ORACLE 9I
    TABLE COLUMN DATA TYPE VARCHAR2 16
    WHEN UPDATE COLUMN VALUE WITH 11 CHARACTERS IT GIVES ERROR
    ORA-31495 error in synchronous change table on "string"."string"
    ORA-01401 value too large for column
    IF I UPDATE COLUMN VALUE UPTO 10 CHARACTERS IT COMMITS AND GIVES NO ERROR

    What is the characterset of your database base
    how you create table as
    create table table1 (col1  varchar2(16 char)) or
    create table table1 (col1  varchar2(16 byte))Try to create table with create table table1 (col1  varchar2(16 char)) then try insert
    Regards
    Singh
    Edited by: Singh on Sep 2, 2008 1:00 PM

  • Exact Difference and Usage between .toString / String.valueOf() / (String)

    Hi
    What are the differences in .toString / String.valueOf() / (String) ?
    I have tried the following :
    String a = "a";
             Object o = "o";
             int i = 1;
             System.out.println("String Value of " + String.valueOf(i));
             System.out.println("(String) " + (String)o);
             System.out.println(".toString() " + i.toString()); // does not work
             System.out.println(".toString() " + String(i)); // does not workThanks in Advance !!

    x.toString() calls the object's toString() method. It cannot be used for primitives, and it will give NullPointerException if x is null.
    String.valueOf(x) will call the object's toString() method if x is a non-null reference. If x is a null reference, it will return the string "null". If x is a primitive, it will return a String representation of that primitive, probably by calling toString on an appropriate wrapper object, or a static String.valueOf method on the appropriate wrapper class. You can look at the source code in src.zip if you're curious.
    Both toString() and String.valueOf are just methods. There's nothing special about them. You can look at their docs and/or source code to see what they do.
    (String)x will attempt to cast the reference x to a String. I doesn't change the object in any way. If x is not a reference to one of String's supertypes--Object, Comparable, etc.--then it will be a compile-time error. If x is a reference to one of String's supertypes, but points to an object at runtime that is not a String, it will be a ClassCastException.
    This is just casting, an there's nothing special about casting with Strings vs. any other class.
    Edited by: jverd on Apr 27, 2010 4:07 PM

  • How to convert Octect string to String

    HI All,
    I need to convert Octect string like "54:68:65:20:46:52:55:20:50:6f:77"
    to the String, can anybody please help me to write the code
    Thanks in advance

    Hi
    the actual string is
    "54:68:65:20:46:52:55:20:50:6f:77:65:72:20:4c:65:76:65
    :6c:20:69:73:20:31:20:43:6f:6e:73:75:6d:69:6e:67:20:31
    :20:57:61:74:74:73:20:0a"
    The string format of the above octect string is
    "The FRU Power Level is 1 Consuming 1 Watts"Oh, I see ...
    /* use JDK 1.5 */
    public class Hex2CharDemo{
      public static void main(String[] args){
        String result;
        StringBuffer sb = new StringBuffer();
        String hexs =
    "54:68:65:20:46:52:55:20:50:6f:77:65:72:20:4c:65:76:65:6c:20:69:73:20:31:20:43:6f:6e:73:75:6d:69:6e:67:20:31:20:57:61:74:74:73:20:0a";
        String[] sa = hexs.split(":");
        for (String s : sa){
          char c = (char)(Integer.parseInt(s, 16));
          sb.append(c);
        result = new String(sb);
        System.out.print(result);
    }

  • How to converts this string[ ][ ] to string[ ]

    I have String a[ ][ ]= {{"D",":","/","S","o","n","g","s","/","J","u","d","a","s"}};
    and I want to convet to
    String a[ ] = {D:/Songs/Judas};
    how can I do it? :((

    I have String a[ ][ ]= {{"D",":","/","S","o","n","g","s","/","J","u","d","a","s"}};Why do you store it as a String[][] array ?
    It would be better to use a char[]
    char[] a=  {'D',':','/','S','o','n','g','s','/','J','u','d','a','s'};
    String string = new String(a);
    // or
    Object[][] b = {{'D',':','/','S','o','n','g','s','/','J','u','d','a','s'}};
    // I don't know why you store it in a String array but if one likes it
    String[] c = new String[]{new String((char[])b[0])};To convert String[] to String one would write
    String[] d={"D",":","/","S","o","n","g","s","/","J","u","d","a","s"};
    StringBuffer buffer = new StringBuffer(d.length);
    String e;
    for ( int idx = 0; idx < d.length; ++idx) {
       buffer.append(d[idx]);
    e=buffer.toString();

  • A better way to search a string in a 3GB txt file

    I am looking for a string(12 characters) in a 3GB txt file. I use the file reader to go though each line and use the startwith() (that 12 characters are from the beginning of each line) to check if that line contain the string I am searching for. Is there a faster way to do it? Thank's.

    I would avoid using java to parse/search a 3 GB text file at all costs. Any java solution is going to have terrible performance and you may run into memory problems. I would recomend that you either a) develop a native method for resolving this search and just invoke it from your current java class or b) use Runtime.exec to invoke a native OS command for searching the file (like grep or find) and parse the results. ....
    I'm not even sure how I would complete that task with java exclusivly ... maybe break the file into smaller parts, then iterate through each smaller, temporary file ... I would really recomend storing your data in a different format if possible. A 3 GB text file just isn't very partical or secure.
    ... oh, to answer your original question (which I'm not sure if I all ready did), the fatest way to load the file is to wrap it into some BufferedReader. The fatest way to perform String searches is through the java.util.regex package if you have access to the 1.4 API. Other wise, just use basic String searches, as you all ready are.

Maybe you are looking for

  • JVM 1.4.2.17 incompatible w/ SPML 2.0 ?

    Hi All, (apologies for any redundancy, this same inquiry is posted with a slightly different title under {color:#0000ff}Sun Java System Identity Manager{color}) We are experiencing severe problems with an online portal application as we attempt to up

  • Webcat Auditing

    Hi, Could anyone give some direction on how to capture the audit information for webcat? The requirement is to identify who is editing an existing report, who is adding new users to a group etc. Thanks, Santosh Mahapatra

  • Problems with Help menu in photoshop CS2

    When I try and access the help menu and then "photoshop help" (or press the F1 Button) in photoshop cs2 I get the following error. "the operation could not be completed" I then press ok on this and the following pops up. "The instruction at "0x00864a

  • Survey, Do you rename files before bringing them into Aperture.

    I'm curious the percentage of us that rename the original files (so we don't have a bunch of images named something like _ACH0001) before final import into Aperture. This includes either editing them then renaming them outside of Aperture and bringin

  • RD Connection Broker 2012 - needed documentation to implement a plugin

    Hello I am trying to implement a plugin for RD Connection Broker (by using of realization of the IWTSSBPlugin interface, https://msdn.microsoft.com/en-us/library/cc644955%28v=vs.85%29.aspx) In documentation (https://msdn.microsoft.com/en-us/library/c