Help with string.valueof

I have the following code which is meant to read in a file into text boxes and let me scroll through all the items in the file.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.*;
public class ReadSequentialFile extends JFrame {
   private ObjectInputStream input;
   private BankUI userInterface;
   private JButton nextButton, openButton, nextRecordButton ;
   private Store store = new Store(50);
     private Employee employeeList[] = new Employee[50];
     private int count = 0, next = 0;
   // Constructor -- initialize the Frame
   public ReadSequentialFile()
      super( "View Data" );
      // create instance of reusable user interface
      userInterface = new BankUI( 8 );  // eight textfields
      getContentPane().add( userInterface, BorderLayout.CENTER );
      // get reference to generic task button doTask1 from BankUI
      openButton = userInterface.getDoTask1Button();
      openButton.setText( "Open File" );
      // register listener to call openFile when button pressed
      openButton.addActionListener(
         // anonymous inner class to handle openButton event
         new ActionListener() {
            // close file and terminate application
            public void actionPerformed( ActionEvent event )
               openFile();
         } // end anonymous inner class
      ); // end call to addActionListener
      // register window listener for window closing event
      addWindowListener(
         // anonymous inner class to handle windowClosing event
         new WindowAdapter() {
            // close file and terminate application
            public void windowClosing( WindowEvent event )
               if ( input != null )
                         closeFile();
               System.exit( 0 );
         } // end anonymous inner class
      ); // end call to addWindowListener
      // get reference to generic task button doTask2 from BankUI
      nextButton = userInterface.getDoTask2Button();
      nextButton.setText( "Next Record" );
      nextButton.setEnabled( false );
      // register listener to call readRecord when button pressed
      nextButton.addActionListener(
         // anonymous inner class to handle nextRecord event
         new ActionListener() {
            // call readRecord when user clicks nextRecord
            public void actionPerformed( ActionEvent event )
               readRecord();
         } // end anonymous inner class
      ); // end call to addActionListener
      nextRecordButton = userInterface.getDoTask3Button();
      nextRecordButton.setText( "Get Next Record" );
      nextRecordButton.setEnabled( false );
      // register listener to call readRecord when button pressed
      nextRecordButton.addActionListener(
         // anonymous inner class to handle nextRecord event
         new ActionListener() {
            // call readRecord when user clicks nextRecord
            public void actionPerformed( ActionEvent event )
               getNextRecord();
         } // end anonymous inner class
      ); // end call to addActionListener
      pack();
      setSize( 600, 300 );
      setVisible( true );
   } // end ReadSequentialFile constructor
   // enable user to select file to open
   private void openFile()
      // display file dialog so user can select file to open
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
      int result = fileChooser.showOpenDialog( this );
      // if user clicked Cancel button on dialog, return
      if ( result == JFileChooser.CANCEL_OPTION )
         return;
      // obtain selected file
      File fileName = fileChooser.getSelectedFile();
      // display error if file name invalid
      if ( fileName == null || fileName.getName().equals( "" ) )
         JOptionPane.showMessageDialog( this, "Invalid File Name",
            "Invalid File Name!", JOptionPane.ERROR_MESSAGE );
      else {
         // open file
         try {
            input = new ObjectInputStream(
               new FileInputStream( fileName ) );
            openButton.setEnabled( false );
            nextButton.setEnabled( true );
         // process exceptions opening file
         catch ( IOException ioException ) {
            JOptionPane.showMessageDialog( this, "Error Opening File",
               "Error", JOptionPane.ERROR_MESSAGE );
      } // end else
   } // end method openFile
   // read record from file
   public void readRecord()
      Employee record;
      // input the values from the file
      try {
        record = ( Employee ) input.readObject();
     employeeList[count++]= record;
     store.add(record);
          store.displayAll(); // displays store in terminal window
          System.out.println("Count is " + store.getCount());
         // create array of Strings to display in GUI
         String values[] = { String.valueOf(record.getName()),
         String.valueOf(record.getGender()),
          String.valueOf( record.getStartDate() ),
         String.valueOf( record.getID() ),
           String.valueOf( record.getDateOfBirth() ) };
         // display record contents
         userInterface.setFieldValues( values );
      // display message when end-of-file reached
      catch ( EOFException endOfFileException ) {
         nextButton.setEnabled( false );
      nextRecordButton.setEnabled( true );
         JOptionPane.showMessageDialog( this, "No more records in file",
            "End of File", JOptionPane.ERROR_MESSAGE );
      // display error message if class is not found
      catch ( ClassNotFoundException classNotFoundException ) {
         JOptionPane.showMessageDialog( this, "Unable to create object",
            "Class Not Found", JOptionPane.ERROR_MESSAGE );
      // display error message if cannot read due to problem with file
      catch ( IOException ioException ) {
         JOptionPane.showMessageDialog( this,
            "Error during read from file",
            "Read Error", JOptionPane.ERROR_MESSAGE );
   } // end method readRecord
   private void getNextRecord()
           Employee record = employeeList[next++%count];//cycles throught accounts
      //create aray of string to display in GUI
      String values[] = {String.valueOf(record.getName()),
         String.valueOf(record.getGender()),
          String.valueOf( record.getStartDate() ),
         String.valueOf( record.getID() ),
           String.valueOf( record.getDateOfBirth() ) };
  // close file and terminate application
   private void closeFile()
      // close file and exit
      try {
         input.close();
         System.exit( 0 );
      // process exception while closing file
      catch ( IOException ioException ) {
         JOptionPane.showMessageDialog( this, "Error closing file",
            "Error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 );
   } // end method closeFile
   public static void main( String args[] )
      new ReadSequentialFile();
} // end class ReadSequentialFileMy problem is when i compile the code i get the following errors:
ReadSequentialFile.java:181: getStartDate(Date) in Employee cannot be applied to
          String.valueOf( record.getStartDate() ),
                                ^In the employee class I did getStartDate like:
     public Date getStartDate(Date sDate)
          return start;
     }Can anybody tell me why i get this error and how to solve it?

so in
the employee class i need to chnage the getDate
method?Well, it's your class, so it's up to you to know what that method is supposed to do, to give it a signature that allows it to be called with the data to do its job, and the pass it the right data when you call it.
Don't think only about how to make the compiler happy. Think about what you're trying to accomplish and in what way the current code doesn't do that. The compiler can only really detect syntactical errors, but sometimes those errors arise as the result of logic errors in your mental picture of the steps to follow. So take the compiler's complaints as a hint to reexamine what you're doing and see if it makes sense.

Similar Messages

  • Help With String parsing

    Hey guys,
    I need some help with String Parsing. i hope experts here will help me.
    i'm reading a text file and getting data as String in this format
    *ABR, PAT MSSA        2009       7001    B   ABC       Y
    *VBR, SAT ZSSA        2008       5001    A   CED       N
    *ABC, AAT CSSA        5008       001     A   AZX       N
    *CBC, CAT FSSA        308        5001    A   XCV       N
    Now from following lines i have to extract Number data i.e. 2009 and 7001 from 1st line. 2008 and 5001 from 2nd line and so on.
    Can anyone pls suggest me any way to get the data that i want from these Strings
    Thanks for your time to read this.
    Regards,
    sam

    Thanks for the reply
    Data length can vary. ABR, PAT is the last name, First Name of the Users.
    it can be following or any other combination. i just need 2 set of numbers from the complete line rest i can ignore. Any other way to get that
    *ABRaaassd, PATfffff MSSA 2009 7001 B ABC Y
    *VBRaa, SATaa ZSSA 2008 5001 A CED N
    *ABC, AAT CSSA 5008 001 A AZX N
    *CBC, CAT FSSA 308 5001 A XCV N                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help with string object code

    Hello,
    First off thanks in advance to anyone who helps. I am trying to write a program that using a class string object to convert this kind of "text speech" to english. For example if the user inputs "HowAreYou?", I want the program to output "How are you?" I am having too much trouble with strings for some reason. This is what I have so far and I am not sure where to go from here. Should I use a do loop to check through the input string until it is done seperating the words? And how should I go about doing that?
    import java.util.Scanner;
    public class P8
    public static void main( String args[] )
    char choice;
    String line = null;
    String answer = null;
    Scanner scan = new Scanner(System.in);
    do
    System.out.println();
    System.out.print("ENTER TextSpeak sentence(s): ");
    line = scan.nextLine();
    System.out.print( "Converted to English: \t ");
    System.out.print( textSpeaktoEng( line ) );
    System.out.println();
    System.out.print("Want more TextSpeak?\t\t ");
    answer = scan.next();
    choice = answer.charAt(0);
    if( scan.hasNextLine() )
    answer = scan.nextLine();
    }while(choice != 'N' && choice != 'n');
    public static String textSpeakToEng(String s)
    String engStr = null;
    if( Character.isUpperCase( s.charAt(j) ) )
    engStr += ? ?;
    engStr += Character.toLowerCase( s.charAt(j) );
    scan.close();
    }

    I got my program to compile and run but I have a problem. If I input something like "ThisForumIsGreat" it will output just "t f i g" in lower case letters. Any suggestions?
    import java.util.Scanner;
    public class P8
    public static void main( String args[] )
       char     choice;                          // Repeat until n or N                                             
       String line   = null;                     // Sentences to toTextSpeak
       String answer = null;                     // Repeat program scan
       Scanner scan = new Scanner(System.in);    // Read from keyboard
       do
          System.out.println();
          System.out.print("ENTER TextSpeak sentence(s): ");
          line = scan.nextLine();                // Read input line
          System.out.print( "Converted to English: \t    ");
          System.out.print( textSpeakToEng( line ) );
          System.out.println();
          System.out.print("Want more TextSpeak?\t\t ");
          answer = scan.next();                  // Read line, assign to string
          choice = answer.charAt(0);             // Assign 1st character
          if( scan.hasNextLine() )               // <ENTER> character
            answer = scan.nextLine();            // Read line, discard
      }while(choice != 'N' && choice != 'n');    // Repeat until input start n or N
    public static String textSpeakToEng(String s)
       String engStr = null;  
       int i;  
       for ( i = 0; i < s.length(); ++i )
       if( Character.isUpperCase( s.charAt(i) ) )
         engStr += " ";                                  // Append 1 blank space
         engStr += Character.toLowerCase( s.charAt(i) ); // Append lowercase
       return( engStr );
    }

  • Urgent help with string tokenizing.

    Hello Everyone,
    I'm 4 months new to Java and JSP.
    Can some one help me with a small favor please, my program below reads from a file and Tokenize the string, the top layer of the string is OK however I want to write another method to tokenize off of the top layer it must be in a separate method because I want to call the method on a JSP page. Can someone view my code and help me with the other method please.
    Thanks
    KT
    package dev;
    import java.io.*;
    import java.util.*;
    public class RoundDetail2
    public String string_gameID;
    public String string_roundID;
    public String string_bet;
    public String string_win;
    public String string_roundDetail;
    public String string_date_time;
    public String tokenizer_topLayer;
    public String readDetail_topLayer;
    public static final String SUITS[] = {" ", "Clubs", "Hearts", "Spades", "Diamonds", "Joker", "FaceDown"};
    public static final String VALUES[] = {"Joker ","Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    public static final String SuitVALUES[] = {" ","1","2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"};
    public RoundDetail2() throws FileNotFoundException
    DataInputStream inFile=
                 new DataInputStream(
                    new BufferedInputStream(
                   new FileInputStream("C:/apps/jakarta-tomcat-4.0.6/webapps/ROOT/WEB-INF/classes/dev/Data_452SY2.txt")));
    try { 
                 if((readDetail_topLayer = inFile.readLine()) != null)
              StringTokenizer tokenizer_topLayer = new StringTokenizer(readDetail_topLayer,"\t", true);
                   if (tokenizer_topLayer.hasMoreTokens())
                        string_gameID = tokenizer_topLayer.nextToken();
                        string_roundID = tokenizer_topLayer.nextToken();                                   
         catch(IOException e)
                    System.out.println(e.getMessage());
         

    If you are trying to read tab delimited file and tokenize the contents, the code should be as below:
    package dev;
    import java.io.*;
    import java.util.*;
    public class RoundDetail2 {
         public String string_gameID;
         public String string_roundID;
         public String string_bet;
         public String string_win;
         public String string_roundDetail;
         public String string_date_time;
         public String tokenizer_topLayer;
         public String readDetail_topLayer;
         public static final String SUITS[] = {" ", "Clubs", "Hearts", "Spades", "Diamonds", "Joker", "FaceDown"};
         public static final String VALUES[] = {"Joker ","Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
         public static final String SuitVALUES[] = {" ","1","2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"};
         String gameInfoText = "";
         public RoundDetail2() throws FileNotFoundException
              DataInputStream inFile = new DataInputStream(new BufferedInputStream(
                                            new FileInputStream("C:/apps/jakarta-tomcat-4.0.6/webapps/ROOT/WEB-INF/classes/dev/Data_452SY2.txt")));
              try
                   while((readDetail_topLayer = inFile.readLine()) != null)
                        gameInfoText += readDetail_topLayer;
              }     catch(IOException e)
                   System.out.println(e.getMessage());
         public void getGameInfo()
              StringTokenizer tokenizer_topLayer = new StringTokenizer(gameInfoText,"\t", false);
              while (tokenizer_topLayer.hasMoreTokens())
                   string_gameID = tokenizer_topLayer.nextToken();
                   string_roundID = tokenizer_topLayer.nextToken();
                   System.out.println(string_gameID+" : "+string_roundID);
         public static void main(String[] args)
              try
                   RoundDetail2 roundDetail = new RoundDetail2();
                   roundDetail.getGameInfo();
              }catch(Exception e){}
    Test if it works for you by running at command prompt.
    Goodluck
    -Mak

  • Need a little help with strings

    So I would like to have the user input a month by using the abbreviation ex. (mar or apr) instead. So I want month to be a string right? When I tried that I get an error. What should this look like?
    import java.util.*;
    public class MonthSwitch
      static Scanner console = new Scanner(System.in);
      public static void main(String[] args)
        int month;
        System.out.print("Enter a Month: ex. Jan, Feb, Mar ect...");
        month = console.nextInt();
        System.out.println();
        switch (month)
          case 1: System.out.println("First Quarter");
          case 2: System.out.println("First Quarter");
          case 3: System.out.println("First Quarter");
                  break;
          case 4: System.out.println("Second Quarter");
          case 5: System.out.println("Second  Quarter");
          case 6: System.out.println("Second  Quarter");
                  break;
          case 7: System.out.println("Third Quarter");
          case 8: System.out.println("Third Quarter");
          case 9: System.out.println("Third Quarter");
                  break;
          case 10: System.out.println("Fouth Quarter");
          case 11: System.out.println("Fouth Quarter");
          case 12: System.out.println("Fouth Quarter");
                  break;
          default: System.out.println("Sorry Input is Invalid");
    }Edited by: NewJavaKid on Apr 29, 2009 10:47 PM

    If you use an enum construct, then you can create a switch that operates on the abbreviated month value. Note that I made a correction in the Scanner input code, and converted the input to lowercase (to assure a match with the enum) in case capitals were used. The switch was revised to work correctly with enums, which requires the try/catch to catch illegal input.
    import java.util.Scanner;
    public class Xy
        static Scanner console = new Scanner(System.in);
        enum Month
            jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
        public static void main(String[] args)
            System.out.print("Enter a Month: ex. Jan, Feb, Mar etc...");
            String shortMonth = console.next().toLowerCase();
            System.out.println();
            try
                switch (Month.valueOf(shortMonth))
                    case jan:
                    case feb:
                    case mar:
                        System.out.println("First Quarter");
                        break;
                    case apr:
                    case may:
                    case jun:
                        System.out.println("Second  Quarter");
                        break;
                    case jul:
                    case aug:
                    case sep:
                        System.out.println("Third Quarter");
                        break;
                    case oct:
                    case nov:
                    case dec:
                        System.out.println("Fouth Quarter");
            catch (IllegalArgumentException iae)
                System.out.println("Sorry, input is invalid");
    }

  • Need help with string field formula

    Post Author: dshallah
    CA Forum: Formula
    What I am trying to accomplish:
    The report has item numbers and each item number has the
    potential to be associated with up to three u2018binsu2019. So the fields are u2018item
    numberu2019, u2018bin1, u2018bin2u2019 and u2018bin3u2019.
    I tried to write a u2018if thenu2019 statement that would only show
    records that had a value of less than 1 in each u2018binu2019 field. When I try to
    write the statement I get a message that says u2018A string is required hereu2019 and
    it highlights the number 1 in my statement. I have a feeling itu2019s because the u2018binu2019
    fields are string fields and not number fieldsu2026? So I am not sure the proper
    procedure to correct this. Thus help is needed and appreciated.
    Here is what I wrote:
    if {IC_LOC_HIST.BIN_NAME_1} < 1 then
    {IC_LOC_HIST.BIN_NAME_1}
    What is correct way to write a statement that will show me
    the zero values in each column of bin fields?
    Thanks!

    Post Author: bettername
    CA Forum: Formula
    You must have a non-numeric value in there somewhere - up in the top left of the formula editor window, it'll show you the variables you've passed to the formula, which should help track down what's going on.
    You could try and check that the value is a number first by using something like:
    if isnull({IC_LOC_HIST.BIN_NAME_1}) = false and isnumeric({IC_LOC_HIST.BIN_NAME_1}) = false and then "Error - Should be a Number!"
    else
    if isnumeric({IC_LOC_HIST.BIN_NAME_1}) = true and tonumber({IC_LOC_HIST.BIN_NAME_1})<1 then {IC_LOC_HIST.BIN_NAME_1})

  • Can anyone help with string manipulation please?

    I am trying to change this string 43180-1-0001-37 into the following expression 43181-0001-37
    It is a string for Project No + Job Phase + Drawing No + Item No.
    The reduction of '43180' to '4318' is causing me the problem, I have the concatenation.
    Current report code is
    SELECT Os.[Orderno-o] As 'Order Number'
    ,Ph.PH_PHASE_NO + '.' + Re.REQUISITION_NUMBER As 'Req. Number'
    ,Pl.ID As 'Item ID'
    ,@CurrentProjectNumber + '-' + Ph.PH_PHASE_NO + '-' + Dr.DRAWING_NO + '-' + Cast(Pl.ITEM_NO As varchar(max)) As 'Drg & Item No.'
    It is this line giving me the problem?
    ,@CurrentProjectNumber + '-' + Ph.PH_PHASE_NO + '-' + Dr.DRAWING_NO + '-' + Cast(Pl.ITEM_NO As varchar(max)) As 'Drg & Item No.'

    Hi uh... Mr. Rubbish at SQL :)
    Unfortunately, there are many elements in your questions which aren't clear:
    1. What is the content in your columns PH_PHASE_NO, DRAWING_NO, ITEM_NO and what is their data type?
    2. What is the content of the variable @CurrentProjectNumber and what is its data type?
    3. It's unclear what is the logic behind the "reduction" of '43180' to '4318'. Do you want to remove trailing zeros? Shorten the value by one character? Because from what I see in your first sentence, it seems like you simply want to add 1 to '43180'
    and turn it into '43181'. That's a simple +1 operation. I also notice that you want to remove the "Job Phase" part from the string (which is "1" in your case)? Or do you need to add its value to the "Project No" (43180)? It's
    all quite confusing.
    Clarification would be highly appreciated.
    I would suggest, if you can, to please explain what you need NOT by specific examples, but by explaining your requirements IN GENERAL. In other words, don't use specific values like '43180', but start with a variable like 'X', and then let us know specifically
    what operation you want to perform on it (e.g. 'add 1' / 'remove trailing zeros' / 'shorten by one character' / 'add to it the value of some column' etc.). This will make it easier to understand the algorithm needed.
    Eitan Blumin; SQL Server Consultant - Madeira Data Solutions;

  • Help with String/ and or Array loading and comparing

    Hi all,
    I'm having some problems with trying to find the best way to achieve the following on a Poker Dealing program. I randomly shuffle a 52 card deck of playing cards and deal out 5 cards. Cool...
    Now I have to go back thru the String and determine if my hand of cards contains
    a pair
    2 pair
    3 of a kind
    Full House
    etc etc
    I am trying to do String comparisons (there is an empty compareCards method in my code right now, but I'm getting a bit frustrated as to find the best way to do it... Would an array load in a separate method be a better way???? What I need to do is after I load my hand , is to display a message stating a pair, 3 of a kind , etc etc.....
    Thanks in advance
    Mike
    Here is my code (please don't laugh too hard - I'm an old COBOL/Oracle guy):
    // Card shuffling and dealing program
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    // Java extension packages
    import javax.swing.*;
    public class DeckOfCards extends JFrame {
    private Card deck[];
    private Card hand[];
    private int currentCard;
    private JButton dealButton, shuffleButton;
    private JTextArea outputArea ;
    private JTextField displayField;
    private JLabel statusLabel;
    // set up deck of cards and GUI
    public DeckOfCards()
    super( "Poker Game" );
    String faces[] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
    String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
    String display = "" ;
    deck = new Card[ 52 ];
    currentCard = -1;
    // populate deck with Card objects
    for ( int count = 0; count < deck.length; count++ )
    deck[ count ] = new Card( faces[ count % 13 ],
    suits[ count / 13 ] );
    // set up GUI and event handling
    Container container = getContentPane();
    container.setLayout( new FlowLayout() );
    // shuffle button
    shuffleButton = new JButton( "Shuffle cards" );
    shuffleButton.addActionListener(
    // anonymous inner class
    new ActionListener() {
    // shuffle deck
    public void actionPerformed( ActionEvent actionEvent )
    displayField.setText( "" );
    shuffle();
    displayField.setText( "The Deck is Shuffled" );
    statusLabel.setText( "" );
    } // end anonymous inner class
    ); // end call to addActionListener
    container.add( shuffleButton );
    // Deal button
    dealButton = new JButton( "Deal Hand" );
    dealButton.addActionListener (
    // anonymous inner class
    new ActionListener() {
    // deal 5 cards
    public void actionPerformed( ActionEvent actionEvent )
    outputArea.setText( "" ) ;
    displayField.setText( "" );
    for ( int cctr = 1 ; cctr <= 5; cctr++ ){     
    Card dealt = dealCard();
    if ( dealt != null ) {
    outputArea.append( dealt.toString()+"\n" );
    else {
    displayField.setText( "No more cards left" );
    statusLabel.setText( "Shuffle cards to continue" );}
    } // end for structure
    compareCards() ;
    } // end action
    } // end anonymous inner class
    ); // end call to addActionListener
    container.add( dealButton );
    outputArea = new JTextArea (10, 20) ;
    outputArea.setEditable( false ) ;
    container.add( outputArea ) ;
    displayField = new JTextField( 20 );
    displayField.setEditable( false );
    container.add( displayField );
    statusLabel = new JLabel();
    container.add( statusLabel );
    setSize( 275, 275 ); // set window size
    show(); // show window
    // shuffle deck of cards with one-pass algorithm
    public void shuffle()
    currentCard = -1;
    // for each card, pick another random card and swap them
    for ( int first = 0; first < deck.length; first++ ) {
    int second = ( int ) ( Math.random() * 52 );
    Card temp = deck[ first ];
    deck[ first ] = deck[ second ];
    deck[ second ] = temp;
    dealButton.setEnabled( true );
    public void compareCards()
    public Card dealCard()
    if ( ++currentCard < deck.length )
    return deck[ currentCard ];
    else {       
    dealButton.setEnabled( false );
    return null;
    // execute application
    public static void main( String args[] )
    DeckOfCards app = new DeckOfCards();
    app.addWindowListener(
    // anonymous inner class
    new WindowAdapter() {
    // terminate application when user closes window
    public void windowClosing( WindowEvent windowEvent )
    System.exit( 0 );
    } // end anonymous inner class
    ); // end call to addWindowListener
    } // end method main
    } // end class DeckOfCards
    // class to represent a card
    class Card {
    private String face;
    private String suit;
    // constructor to initialize a card
    public Card( String cardFace, String cardSuit )
    face = cardFace;
    suit = cardSuit;
    // return String represenation of Card
    public String toString()
    return face + " of " + suit;
    } // end class Card

    You could have the original face values as integers, thus Ace = 1, Jack = 11 (it'll be easy enough to display the proper values AJQK if you keep your string array and just display whatever corresponds to the value held in your int array).
    Each player gets an array of five cards. You could the loop through each hand and increment values held in another array by one according to the value of the card. Haven't coded the following up but it should work I think.
    // hand [ ] represents the cards held by that player
    int handChecker [ ] = new int [14]
    for (int counter = 0; counter < 5; ++ counter)
    // 1st card is an Ace. handChecker [1] will be incrementd by one and so on
    // 2nd card is a 9. handChecker[9] will be incremented by one.
    handChecker[hand[counter]] += 1;
    // Loop through the array handChecker to find pairs etc.
    boolean pair = false;
    bollean tofk = false;
    for (int counter = 1; counter < 14; ++ counter)
    if (handChecker[counter] == 2)
    pair = true;
    if (handChecker[counter] == 3)
    tofk = true;
    if (pair)
    // player has a pair
    if(tofk)
    // player has three of a kind
    if(pair && tofk)
    // player has a full house

  • Code help with string array

    I have declared a String array as
    String[] records;
    Later in the code I wrote
    records[records.length] = qualifiedRecDefName.substring(lastIndex+1, qualifiedRecDefName.length());
    I am getting a NullPointerException. I see that records is null. How can I correct this. Thanks.

    You have to create your array using new.String[] records = new String[10];Also, arrays go from 0 to length-1, so if you want to access the last item, it's records[records.length-1]as long as records.length > 0.

  • Help with String Question

    while(more){
                   System.out.print("Code:");
              ProductCode = in.readLine();
              if (!(ProductCode.equals("A01")) || !(ProductCode.equals("A28")) || ! (ProductCode.equals("B52")) || !(ProductCode.equals("B12")) || (!ProductCode.equals("C43"))
                        || !(ProductCode.equals("C63")) || !(ProductCode.equals("D24")) || !(ProductCode.equals("D90"))){
                   System.out.println("Check the product code again");
              }

    //*Read in the Product Code and the quantity the buyer wants
              while(more) {
                   System.out.print("Code:");
                   ProductCode = in.readLine();
                   if (ProductCode.equals("XX")) {
                        more = false;
                   else if (!(ProductCode.equals("A01") || ProductCode.equals("A28") || ProductCode.equals("B52") ||ProductCode.equals("B12") || ProductCode.equals("C43")
                        || ProductCode.equals("C63") || ProductCode.equals("D24") || ProductCode.equals("D90"))){
                        System.out.println("Check the product code again");
                   else {     
                        int j = 0;
                        ProdTemp[j] = ProductCode;
                        System.out.print("Quantity:");
                        ProductNum = in.readLine();
                        ProductQuantity = Integer.parseInt(ProductNum);
                        Quantity[j]=ProductQuantity;          
                        j++;
                        NoOfItems++;
                        TotalQuantity = Quantity[j] + TotalQuantity;
    //*Display the list of items the user is buying
                    for(int i=0;i<NoOfItems;i++)
                   if (ProdTemp.equals("A01")){
                        Cost = Quantity[i]*15.99;
                        System.out.println("Vitamin F, 260 tablets, 50mg\t"+Quantity[i]+"@ $15.99\t\t"+NumberFormat.getCurrencyInstance().format(Cost));     
    etc........
    i always get a java.lang.NULLPointerException when i purposely type in the wrong product code..but when all the product code are right..there is no error..can anyone help me debug?

  • Function help with strings

    I have a list of at least 5000 names in my system and i want to make a search module based on the list of those names.
    NAME
    Ashish Nanda
    Jim Chang
    Micheal Douglas
    John
    Steven Seagal
    jim Chang
    I want to to create an id column from this list i have and then add it in the table where i will put in names as
    Id
    ASHISHNANDA
    MICHEALDOUGLAS
    JOHN
    STEVENSEAGAL
    JIMCHANG
    i KNOW I CAN USE THE UPPER TO CONVERT THE STRINGS IN TO UPPERCASE FORMAT BUT HOW DO I GET RID OF THE SPACES IN BETWEEN WHICH OCCUR AT RANDOM INTERVALS.
    Any Suggestions?
    Best Regards,
    Ashish

    It does not work i am using Oracle 8.1
    I tried issuing the command but it does not gie no results.
    SQL> select replace('tiny tim','') from dual;
    REPLACE(
    tiny tim

  • Help with string

    hi,
    i wont to add '-' to field of char 7 in the
    e.g.
    12-2345
    ab-cdef
    regards

    Hi
    Check this Small Program ..
    Hope it helps..
    DATA : a type char7 value '123456' ,
           b type char1 value '-' .
    DATA : c type char5 ,
            d type char5 .
    sy-fdpos = 2 .
            C = a+0(sy-fdpos).
            D = a+sy-fdpos.
            CONCATENATE c '-' d INTO a .
            WRITE a .
    Thanks
    Praveen

  • Need Help with a String Binary Tree

    Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
    plssss... someone pls help me on this
    here is my code now:
    // TreeApp.java
    // demonstrates binary tree
    // to run this program: C>java TreeApp
    import java.io.*; // for I/O
    import java.util.*; // for Stack class
    import java.lang.Integer; // for parseInt()
    class Node
         //public int iData; // data item (key)
         public String iData;
         public double dData; // data item
         public Node leftChild; // this node's left child
         public Node rightChild; // this node's right child
         public void displayNode() // display ourself
              System.out.print('{');
              System.out.print(iData);
              System.out.print(", ");
              System.out.print(dData);
              System.out.print("} ");
    } // end class Node
    class Tree
         private Node root; // first node of tree
         public Tree() // constructor
         { root = null; } // no nodes in tree yet
         public Node find(int key) // find node with given key
         {                           // (assumes non-empty tree)
              Node current = root; // start at root
              while(current.iData != key) // while no match,
                   if(key < current.iData) // go left?
                        current = current.leftChild;
                   else // or go right?
                        current = current.rightChild;
                   if(current == null) // if no child,
                        return null; // didn't find it
              return current; // found it
         } // end find()
         public Node recfind(int key, Node cur)
              if (cur == null) return null;
              else if (key < cur.iData) return(recfind(key, cur.leftChild));
              else if (key > cur.iData) return (recfind(key, cur.rightChild));
              else return(cur);
         public Node find2(int key)
              return recfind(key, root);
    public void insert(int id, double dd)
    Node newNode = new Node(); // make new node
    newNode.iData = id; // insert data
    newNode.dData = dd;
    if(root==null) // no node in root
    root = newNode;
    else // root occupied
    Node current = root; // start at root
    Node parent;
    while(true) // (exits internally)
    parent = current;
    if(id < current.iData) // go left?
    current = current.leftChild;
    if(current == null) // if end of the line,
    {                 // insert on left
    parent.leftChild = newNode;
    return;
    } // end if go left
    else // or go right?
    current = current.rightChild;
    if(current == null) // if end of the line
    {                 // insert on right
    parent.rightChild = newNode;
    return;
    } // end else go right
    } // end while
    } // end else not root
    } // end insert()
    public void insert(String id, double dd)
         Node newNode = new Node(); // make new node
         newNode.iData = id; // insert data
         newNode.dData = dd;
         if(root==null) // no node in root
              root = newNode;
         else // root occupied
              Node current = root; // start at root
              Node parent;
              while(true) // (exits internally)
                   parent = current;
                   //if(id < current.iData) // go left?
                   if(id.compareTo(current.iData)>0)
                        current = current.leftChild;
                        if(current == null) // if end of the line,
                        {                 // insert on left
                             parent.leftChild = newNode;
                             return;
                   } // end if go left
                   else // or go right?
                        current = current.rightChild;
                        if(current == null) // if end of the line
                        {                 // insert on right
                             parent.rightChild = newNode;
                             return;
                   } // end else go right
              } // end while
         } // end else not root
    } // end insert()
         public Node betterinsert(int id, double dd)
              // No duplicates allowed
              Node return_val = null;
              if(root==null) {       // no node in root
                   Node newNode = new Node(); // make new node
                   newNode.iData = id; // insert data
                   newNode.dData = dd;
                   root = newNode;
                   return_val = root;
              else // root occupied
                   Node current = root; // start at root
                   Node parent;
                   while(current != null)
                        parent = current;
                        if(id < current.iData) // go left?
                             current = current.leftChild;
                             if(current == null) // if end of the line,
                             {                 // insert on left
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.leftChild = newNode;
                        } // end if go left
                        else if (id > current.iData) // or go right?
                             current = current.rightChild;
                             if(current == null) // if end of the line
                             {                 // insert on right
                                  Node newNode = new Node(); // make new node
                                  newNode.iData = id; // insert data
                                  newNode.dData = dd;
                                  return_val = newNode;
                                  parent.rightChild = newNode;
                        } // end else go right
                        else current = null; // duplicate found
                   } // end while
              } // end else not root
              return return_val;
         } // end insert()
         public boolean delete(int key) // delete node with given key
              if (root == null) return false;
              Node current = root;
              Node parent = root;
              boolean isLeftChild = true;
              while(current.iData != key) // search for node
                   parent = current;
                   if(key < current.iData) // go left?
                        isLeftChild = true;
                        current = current.leftChild;
                   else // or go right?
                        isLeftChild = false;
                        current = current.rightChild;
                   if(current == null)
                        return false; // didn't find it
              } // end while
              // found node to delete
              // if no children, simply delete it
              if(current.leftChild==null &&
                   current.rightChild==null)
                   if(current == root) // if root,
                        root = null; // tree is empty
                   else if(isLeftChild)
                        parent.leftChild = null; // disconnect
                   else // from parent
                        parent.rightChild = null;
              // if no right child, replace with left subtree
              else if(current.rightChild==null)
                   if(current == root)
                        root = current.leftChild;
                   else if(isLeftChild)
                        parent.leftChild = current.leftChild;
                   else
                        parent.rightChild = current.leftChild;
              // if no left child, replace with right subtree
              else if(current.leftChild==null)
                   if(current == root)
                        root = current.rightChild;
                   else if(isLeftChild)
                        parent.leftChild = current.rightChild;
                   else
                        parent.rightChild = current.rightChild;
                   else // two children, so replace with inorder successor
                        // get successor of node to delete (current)
                        Node successor = getSuccessor(current);
                        // connect parent of current to successor instead
                        if(current == root)
                             root = successor;
                        else if(isLeftChild)
                             parent.leftChild = successor;
                        else
                             parent.rightChild = successor;
                        // connect successor to current's left child
                        successor.leftChild = current.leftChild;
                        // successor.rightChild = current.rightChild; done in getSucessor
                   } // end else two children
              return true;
         } // end delete()
         // returns node with next-highest value after delNode
         // goes to right child, then right child's left descendents
         private Node getSuccessor(Node delNode)
              Node successorParent = delNode;
              Node successor = delNode;
              Node current = delNode.rightChild; // go to right child
              while(current != null) // until no more
              {                                 // left children,
                   successorParent = successor;
                   successor = current;
                   current = current.leftChild; // go to left child
              // if successor not
              if(successor != delNode.rightChild) // right child,
              {                                 // make connections
                   successorParent.leftChild = successor.rightChild;
                   successor.rightChild = delNode.rightChild;
              return successor;
         public void traverse(int traverseType)
              switch(traverseType)
              case 1: System.out.print("\nPreorder traversal: ");
                   preOrder(root);
                   break;
              case 2: System.out.print("\nInorder traversal: ");
                   inOrder(root);
                   break;
              case 3: System.out.print("\nPostorder traversal: ");
                   postOrder(root);
                   break;
              System.out.println();
         private void preOrder(Node localRoot)
              if(localRoot != null)
                   localRoot.displayNode();
                   preOrder(localRoot.leftChild);
                   preOrder(localRoot.rightChild);
         private void inOrder(Node localRoot)
              if(localRoot != null)
                   inOrder(localRoot.leftChild);
                   localRoot.displayNode();
                   inOrder(localRoot.rightChild);
         private void postOrder(Node localRoot)
              if(localRoot != null)
                   postOrder(localRoot.leftChild);
                   postOrder(localRoot.rightChild);
                   localRoot.displayNode();
         public void displayTree()
              Stack globalStack = new Stack();
              globalStack.push(root);
              int nBlanks = 32;
              boolean isRowEmpty = false;
              System.out.println(
              while(isRowEmpty==false)
                   Stack localStack = new Stack();
                   isRowEmpty = true;
                   for(int j=0; j<nBlanks; j++)
                        System.out.print(' ');
                   while(globalStack.isEmpty()==false)
                        Node temp = (Node)globalStack.pop();
                        if(temp != null)
                             System.out.print(temp.iData);
                             localStack.push(temp.leftChild);
                             localStack.push(temp.rightChild);
                             if(temp.leftChild != null ||
                                  temp.rightChild != null)
                                  isRowEmpty = false;
                        else
                             System.out.print("--");
                             localStack.push(null);
                             localStack.push(null);
                        for(int j=0; j<nBlanks*2-2; j++)
                             System.out.print(' ');
                   } // end while globalStack not empty
                   System.out.println();
                   nBlanks /= 2;
                   while(localStack.isEmpty()==false)
                        globalStack.push( localStack.pop() );
              } // end while isRowEmpty is false
              System.out.println(
         } // end displayTree()
    } // end class Tree
    class TreeApp
         public static void main(String[] args) throws IOException
              int value;
              double val1;
              String Line,Term;
              BufferedReader input;
              input = new BufferedReader (new FileReader ("one.txt"));
              Tree theTree = new Tree();
         val1=0.1;
         while ((Line = input.readLine()) != null)
              Term=Line;
              //val1=Integer.parseInt{Term};
              val1=val1+1;
              //theTree.insert(Line, val1+0.1);
              val1++;
              System.out.println(Line);
              System.out.println(val1);          
    theTree.insert(50, 1.5);
    theTree.insert(25, 1.2);
    theTree.insert(75, 1.7);
    theTree.insert(12, 1.5);
    theTree.insert(37, 1.2);
    theTree.insert(43, 1.7);
    theTree.insert(30, 1.5);
    theTree.insert(33, 1.2);
    theTree.insert(87, 1.7);
    theTree.insert(93, 1.5);
    theTree.insert(97, 1.5);
              theTree.insert(50, 1.5);
              theTree.insert(25, 1.2);
              theTree.insert(75, 1.7);
              theTree.insert(12, 1.5);
              theTree.insert(37, 1.2);
              theTree.insert(43, 1.7);
              theTree.insert(30, 1.5);
              theTree.insert(33, 1.2);
              theTree.insert(87, 1.7);
              theTree.insert(93, 1.5);
              theTree.insert(97, 1.5);
              while(true)
                   putText("Enter first letter of ");
                   putText("show, insert, find, delete, or traverse: ");
                   int choice = getChar();
                   switch(choice)
                   case 's':
                        theTree.displayTree();
                        break;
                   case 'i':
                        putText("Enter value to insert: ");
                        value = getInt();
                        theTree.insert(value, value + 0.9);
                        break;
                   case 'f':
                        putText("Enter value to find: ");
                        value = getInt();
                        Node found = theTree.find(value);
                        if(found != null)
                             putText("Found: ");
                             found.displayNode();
                             putText("\n");
                        else
                             putText("Could not find " + value + '\n');
                        break;
                   case 'd':
                        putText("Enter value to delete: ");
                        value = getInt();
                        boolean didDelete = theTree.delete(value);
                        if(didDelete)
                             putText("Deleted " + value + '\n');
                        else
                             putText("Could not delete " + value + '\n');
                        break;
                   case 't':
                        putText("Enter type 1, 2 or 3: ");
                        value = getInt();
                        theTree.traverse(value);
                        break;
                   default:
                        putText("Invalid entry\n");
                   } // end switch
              } // end while
         } // end main()
         public static void putText(String s)
              System.out.print(s);
              System.out.flush();
         public static String getString() throws IOException
              InputStreamReader isr = new InputStreamReader(System.in);
              BufferedReader br = new BufferedReader(isr);
              String s = br.readLine();
              return s;
         public static char getChar() throws IOException
              String s = getString();
              return s.charAt(0);
         public static int getInt() throws IOException
              String s = getString();
              return Integer.parseInt(s);
    } // end class TreeApp

    String str = "Hello";
              int index = 0, len = 0;
              len = str.length();
              while(index < len) {
                   System.out.println(str.charAt(index));
                   index++;
              }

  • I have proubleam with string to date conversion, i out put date fromat is 2012-04-30T23:48:55.727-07:00 . so please help me the format conversion

    i have proubleam with string to date conversion, i out put date fromat is 2012-04-30T23:48:55.727-07:00 . so please help me the format conversion.
    i wrote the method but it not workig
    My method is
    -(NSDate *)dateformstr:(NSString *)str
    NSString *date = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
      [dateFormate setDateFormat:@"yyyy-MM-dd'T'HH:mm:sssZZZZ"]
    // NSDate *formatterDate = [dateFormate  dateFromString:str];
        return formatterDate;
    but i did not the value and if i try othere formate i is working but my requiremet format is 2012-04-30T23:48:55.727-07:00.
    can any help it out in this senario.

    Sorry Butterbean, but I'm interested in the answer to your question myself.
    I've spent a few hours transfering my library from one computer to another and then find out that my ratings didn't transfer. Like you, I've spent many hours rating my 2000+ songs. I'm sure you have more, nevertheless, I want to find out how to get those ratings. They still show in my iTunes on my laptop but, when I go to the iTunes folder and display the details of at song, no rating is there. If you find out how to get them to display there in the iTunes folder, it seems that would be the key.
    Hope you get your answer soon.

  • Still Need Help with this String Problem

    basically, i need to create a program where I input 5 words and then the program outputs the number of unique words and the words themselves. for example, if i input the word hello 5 times, then the output is 1 unique word and the word "hello". i have been agonizing over this dumb problem for days, i know how to do it using hashmap, but this is an introductory course and we cannot use more complex java functions, does ANYONE know how to do this just using arrays, strings, for loops, if clauses, etc. really basic java stuff. i want the code to be able to do what the following program does:
    import java.io.*; import java.util.ArrayList;
        public class MoreUnique {
           public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[5]; int uniqueEntries = 0; ArrayList<String> ue = new ArrayList<String>();
             for (int i = 0; i < 5; i++) { System.out.print((i +1) + ": "); str[i] = br.readLine(); }
             for (int j = 0; j < 5; j++) {
                if (!ue.contains(str[j].toLowerCase())) { ue.add(str[j].toLowerCase()); } } uniqueEntries = ue.size(); System.out.print("Number of unique entries: " + uniqueEntries + " { ");
             for (int q = 0; q < ue.size(); q++ ) { System.out.print(ue.get(q) + " "); } System.out.println("}"); } } but i need to find how to do it so all 5 words are put in at once on one line, and without all the advanced java functions that are in here, can anyone help out?

    you have to compare string 0 to strings 1-4, then
    string 1 with strings 2-4, then string 2 with strings
    3 and 4 then string 3 with string 4....right???Here's a way to do it:
    public class MoreUnique {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            final int NUM_WORDS = 5;
            String[] words = new String[NUM_WORDS];
            int uniqueEntries = 0;
            for(int i = 0; i < NUM_WORDS; i++) {
                System.out.print((i+1)+": ");
                String temp = br.readLine();
                if(!contains(temp, words)) {
                    words[uniqueEntries++] = temp;
            System.out.print("Number of unique entries: "+uniqueEntries+" { ");   
            for (int i = 0; i < uniqueEntries; i++ ) {   
                System.out.print(words[i]+" ");
            System.out.println("}");
        private static boolean contains(String word, String[] array) {
                 Your code here: just a simple for-statement to
                 loop through your array and to see if 'word'
                 is in your 'array'.
    }Try to fill in the blanks.
    Good luck.

Maybe you are looking for