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.

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/ 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

  • 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 );
    }

  • Help with PHP array code

    Not sure what's going on here, but hopefully someone can spot where I'm going wrong.
    Its especially weird, as I'm using the same code, with the same database table names etc but on a different site.
    Basically, I've set up a database table to store customer feedback on products.
    Its all working fine on this site :
    http://www.mye-reader.co.uk/customerreviews.php
    But on the site I'm working on, its only showing the first record. There are only a couple of records at the moment, but I've tried changing the query from ASC to DESC, and it swaps the one it shows, so it looks like the issue is with the array. Even though its the same code.
    http://www.mybabymonitors.co.uk/reviews.php
    Anyway, my query looks like :
    mysql_select_db($database_connPixelar, $connPixelar);
    $query_rsReviews = "SELECT * FROM feedback WHERE Approved = 'Yes' ORDER BY Product DESC";
    $rsReviews = mysql_query($query_rsReviews, $connPixelar) or die(mysql_error());
    $row_rsReviews = mysql_fetch_assoc($rsReviews);
    $totalRows_rsReviews = mysql_num_rows($rsReviews);
    And the array code looks like :
    <table cellpadding="0" cellspacing="0" width="100%" border="0">
           <?php
         $groups = array();
    while ($row = mysql_fetch_assoc($rsReviews)) {
        $groups[$row['Product']][] = $row;
    foreach ($groups as $product_name => $rows) {
        echo "<tr><td class=\"product\">$product_name</td></tr>";
        foreach ($rows as $row) {
            echo "<tr><td class=\"review\">".$row['Review']."</td></tr>";
            echo "<tr><td class=\"name\">".$row['CustomerName']."</td></tr>";
            echo "<tr><td class=\"date\">".$row['Date']."</td></tr>";
    ?>
    </table>
    Any ideas what's going on here?

    Its OK - I figured it out - it was the
    $row_rsReviews = mysql_fetch_assoc($rsReviews);
    line in the query.
    Turns out it wasn't that one was working, and the other not - they were both starting from the second record.

  • Problems with string array, please help!

    I have a String array floor[][], it has 20 rows and columns
    After I do some statement to modify it, I print this array
    out in JTextArea, why the output be like this?
    null* null....
    null null...
    null null...
    How to correct it?

    a turtle graphics applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TG extends JApplet implements ActionListener {
      private int x, y;
      private int pendown, command, movement;
      String direction, output, temp;
      JLabel l1;
      JTextField tf1;
      JTextArea ta1;
      String floor[][] = new String[20][20];;
      public void init()
        x = 0;
        y = 0;
        pendown = 0;
        direction = "r";
        Container c = getContentPane();
        c.setLayout( new FlowLayout() );
           l1 = new JLabel( "Please type a command:" );
           c.add( l1 );
           tf1 = new JTextField(20);
           tf1.addActionListener( this );
           c.add( tf1 );
           ta1 = new JTextArea(20,20);
           ta1.setEditable( false );
           c.add( ta1 );
    public void actionPerformed( ActionEvent e )
           temp = tf1.getText();
           if( temp.length() > 1)
           command = Integer.parseInt(temp.substring(0,1));
           movement = Integer.parseInt(temp.substring(2,temp.length()));
           else
           command = Integer.parseInt(temp);
           switch(command)
                case 1:
                pendown=0;
                break;
                case 2:
                pendown=1;
                break;
                case 3:
                direct("r");
                break;
                case 4:
                direct("l");
                break;
                case 5:
               move(movement);           
                break;
                case 6:
                print();
                break;                                     
      public void direct(String s)
           if(direction == "r" && s =="r")
              direction = "d";
           else if(direction == "r" && s =="l")
              direction = "u";
           else if(direction == "l" && s =="r")
              direction = "u";
           else if(direction == "l" && s =="l")
              direction = "d";
           else if(direction == "u" && s =="r")
              direction = "r";
           else if(direction == "u" && s =="l")
              direction = "l";
           else if(direction == "d" && s =="r")
              direction = "l";
           else if(direction == "d" && s =="l")
              direction = "r";
      public void move(int movement)
           if(pendown == 1)
                if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "*";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "*";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "*";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "*";
            else if(pendown == 0)
                 if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "-";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "-";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "-";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "-";
          public void print()
         for(int row=0;row<20;row++)
           for( int column=0;column<20;column++)
                output += floor[row][column];
                if(column == 19)
                 output+="\n";
            ta1.setText(output);
    }

  • Help with parallel arrays of different data types

    Hello all, I am having an issue with parallel arrays. My program requires me to read information from a text file into 4 parallel arrays (2 String and 2 double). My text file needs to look something like this:
    John Johnson
    0000004738294961
    502.67
    1000.000
    Jane Smith
    0000005296847913
    284.51
    1000.000
    ...and so on
    Where the first thing is the name (obviously), an account number, the balance in the account, and the credit limit. I just cant figure out how to read everything into the arrays. We havent learned anything too heavy, and this seems a little too advanced for my class, but I guess we will manage. Any help will be appreciated. Thanks guys.
    Casey

    Man this is a dumb homework assignment. The requirements scream out for a class along the lines of
    public class Account{
      private String name, number;
      private double balance,creditlimit;
       // more code here
    }and then to use a List of Account objects.
    Anyway what's your actual problem. There's nothing very hard about it. A loop. So....
    You should consider posting (formatted) code showing what you have done and where exactly you are stuck.

  • HELP WITH CHAR ARRAY

    Here is the go folks this is a pice of code which I was helped with by a member of this forum, THANX HEAPS DUDE. What has happened now is the criteria is changed, previously it would search for a string in the vector. But now I have to have searches with wildcards, so it needs to utilize a char array methinks. So it will go through change the parameter to a char array, then go through the getDirector() method to return a director string, then it needs to loop through the char array and check if the letters are the same. then exit on the wild card. Now all this needs to be happening while this contruct down the bottom is looping through all the different elements in the moviesVector :s if anyone could give me a hand it is verry welcome. I must say also that this forum is very well run. 5 stars
    public void searchMovies(java.lang.String searchTerm) {
    Iterator i = moviesVector.iterator();
    while (i.hasNext()) {
    Movie thisMovie = (Movie)i.next();
    //Now do what you want with thisMovie. for instanse:
    if (thisMovie.getDirector().equals(searchTerm))
    foundMovies.add(thisMovie);
    //assumes foundMovies is some collection that we will
    //return later... or if you just want one movie, you can:
    //return thisMovie; right here.
    }

    Sorry, I clicked submit, but i didnt enable to wtch it, so i stoped it before it had sent fully. Evidently that didnt work.

  • Hello guys need help with reverse array

    Need help reversing an array, i think my code is correct but it still does not work, so im thinking it might be something else i do not see.
    so far the input for the array is
    6, 25 , 10 , 5
    and output is still the same
    6 , 25 , 10 , 5
    not sure what is going on.
    public class Purse
        // max possible # of coins in a purse
        private static final int MAX = 10;
        private int contents[];
        private int count;      // count # of coins stored in contents[]
         * Constructor for objects of class Purse
        public Purse()
           contents = new int[MAX];
           count = 0;
         * Adds a coin to the end of a purse
         * @param  coinType     type of coin to add
        public void addCoin(int coinType)
            contents[count] = coinType;
            count = count + 1;
         * Generates a String that holds the contents of a purse
         * @return     the contents of the purse, nicely formatted
        public String toString()
            if (count == 0)
                return "()";
            StringBuffer s = new StringBuffer("(");
            int i = 0;
            for (i = 0; i < count - 1; ++i)
                s.append(contents[i] + ", "); // values neatly separated by commas
            s.append(contents[i] + ")");
            return s.toString();
         * Calculates the value of a purse
         * @return     value of the purse in cents
        public int value()
            int sum = 0; // starts sum at zero
            for( int e : contents) // sets all to e
                sum = sum + e; //finds sum of array
            return sum; //retur
         * Reverses the order of coins in a purse and returns it
        public void reverse()
           int countA = 0;
           int x = 0;
           int y = countA - 1;                                          // 5 - 1 = 4
           for (int i = contents.length - 1; i >=0 ; i--)                        // 4, 3 , 2, 1, 0
                countA++;                                             // count = 5
            while ( x < y)
                int temp = contents[x];
                contents[x] = contents [y];
                contents [y] = temp;
                y = y- 1;                                         // 4 , 3 , 2, 1 , 0
                x = x + 1 ;                                             // 0 , 1,  2  , 3 , 4
    }

    ok so i went ahead and followed what you said
    public void reverse()
          int a = 0;
          int b = contents.length - 1;
          while (b > a)
              int temp = contents[a];
              contents[a] = contents;
    contents [b] = temp;
    a++;
    b--;
    }and its outputting { 0, 0, 0, 0}
    im thinking this is because the main array is has 10 elements with only 4 in use so this is a partial array.
    Example
    the array is { 6, 25, 10, 5, 0, 0, 0, 0, 0, 0,}
    after the swap
    {0, 0 , 0 , 0, 0 , 0 , 5 , 10 , 25, 6}
    i need it to be just
    { 5, 10, 25, 6}
    so it is swapping the begining and end but only with zeroes the thing is i need to reverse the array without the zeroes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I need help with 2 arrays

    I need help with this portion of my program, it's supposed to loop through the array and pull out the highest inputted score, currently it's only outputting what is in studentScoreTF[0].      
    private class HighScoreButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              double highScore = 0;
              int endScore = 0;
              double finalScore = 0;
              String tempHigh;
              String tempScore;
              for(int score = 0; score < studentScoreTF.length; score++)
              tempHigh = studentScoreTF[score].getText();
                    tempScore = studentScoreTF[endScore].getText();
              if(tempHigh.length() <  tempScore.length())
                   highScore++;
                   finalScore = Double.parseDouble(tempScore);
             JOptionPane.showMessageDialog(null, "Highest Class Score is: " + finalScore);This is another part of the program, it's supposed to loop through the student names array and pull out the the names of the students with the highest score, again it's only outputting what's in studentName[0].
         private class StudentsButtonHandler implements ActionListener
               public void actionPerformed(ActionEvent e)
              int a = 0;
              int b = 0;
              int c = 0;
              double fini = 0;
              String name;
              String score;
              String finale;
              String finalName = new String();
              name = studentNameTF[a].getText();
              score = studentScoreTF.getText();
              finale = studentScoreTF[c].getText();
              if(score.length() < finale.length())
                   fini++;     
                   name = finalName + finale;
         JOptionPane.showMessageDialog(null, "Student(s) with the highest score: " + name);
                   } Any help would be appreciated, this is getting frustrating and I'm starting to get a headache from it, lol.
    Edited by: SammyP on Oct 29, 2009 4:18 PM
    Edited by: SammyP on Oct 29, 2009 4:19 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Heres a working example:
    class Compare {
        public int getHighest(int[] set) {
            int high = set[0];
            for(int i = 0; i < set.length; i++) {
                if(set[i] > high) {
                    high = set;
    return high;

  • Need help with an array function

    I'm using the array index function and i would like to be able to control what elements go out on it.  For example, if i wanted only the first element to go out, i don't want the second element to send out zero.  Is there any way i can control what elements leave the array index function.  I also don't understand what the index inputs do on that function either.  If anyone has any advice on the application or can modify it in any way, please help.
    Attachments:
    Array and for loop.vi ‏1190 KB

    The index inputs determine what elements are retrieved. For example of you would wire a 10 and a 20 to your two index inputs, you would bet element #10 and element #20 of your array. You can resize it to get any desired number of elements.
    If you don't wire the index inputs, you'll get the first two elements.
    If you only wire the top index input (e.g a 10), you'll get element #10 and #11.
    LabVIEW Champion . Do more with less code and in less time .

  • Help with method/array lab

    I need some help creating an array of students in my lab, using a method. I'm fairly confused on how to do this. This is a sample of my code, i've deleted a lot of the stuff further down thats not needed atm.
    Anyhow, I understand how arrays work and whatnot, but have no clue as to how to create the array in the method. Any help please! (The last few lines of posted code is where the array should go)
    import java.util.Scanner;
    import java.io.*;
    public class Lab6
        public static void main(String[] args)
            // Fill in the body according to the following comments
             Scanner keyboard = new Scanner(System.in);
             // Input file name
         String fileName = getFileName(keyboard);
             // Input number of students
         int numberOfStudents = FileIOHelper.getNumberOfStudents(fileName);
             // Input all student records and create Student array and
         Student [] studentAry = new Student [numberOfStudents];
             // integer array for total scores
        // Given a Scanner in, this method prompts the user to enter
        // a file name, inputs it, and returns it.
        private static String getFileName(Scanner keyboard)
             String fileName;
         System.out.print("Enter input file name: ");
        fileName = keyboard.nextLine();
        return fileName;
        // Given the number of students records n to input, this
        // method creates an array of Student of the appropriate size,
        // reads n student records using the FileIOHelper, and stores
        // them in the array, and finally returns the Student array.
        private static Student[] getStudents(int n)
            // Fill in the body
        }

    Oh btw, this is sample code givin to me by my professor that may help?
            // Copy a student from the file to the array
              Student aStudent = FileIOHelper.getNextStudent();
              studentAry[0] = aStudent;
              // Copy another student to the array
              aStudent = FileIOHelper.getNextStudent();
              studentAry[1] = aStudent;
              // Get student information from the array
              String name = studentAry[1].getName();
              int s1 = studentAry[1].getScore(1);
              int s2 = studentAry[1].getScore(2);
              int s3 = studentAry[1].getScore(3);

  • Problems with string arrays

    Previous task was:
    Write a class "QuestionAnalyser" which has a method "turnAnswerToScore". This method takes a String parameter and returns an int. The int returned depends upon the parameter:
    parameter score
    "A" 1
    "B" 2
    "C" 3
    other 0
    Alright, here's the recent task:
    Write another method "turnAnswersToScore". This method takes an array of Strings as a parameter, works out the numerical score for each array entry, and adds the scores up, returning the total.
    That's my code:
    class QuestionAnalyser{
    public static int Score;
    public String[] Answer;
    public static void main(String[] args) {}
         public int turnAnswerToScore(String[] Answer)
    for (int i = 0; i < Answer.length;i++) {
    if (Answer.equals("A")) {
    Score = Score + 1; }
    else if (Answer[i].equals("B")) {
    Score = Score + 2;}
    else if (Answer[i].equals("C")) {
    Score = Score + 3;}
    else {
    Score = Score + 0;}
    return Score;
    this is the error message I get:
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    QATest2.java:15: cannot resolve symbol
    symbol : method turnAnswersToScore (java.lang.String[])
    location: class QuestionAnalyser
    if(qa.turnAnswersToScore(task)!=total){
    ^
    What went wrong?
    Suggestions would be greatly appreciated!

    If I declare int score in the method i get this message
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ./QuestionAnalyser.java:20: variable score might not have been initialized
    score++; }
    ^
    ./QuestionAnalyser.java:23: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:27: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:34: variable score might not have been initialized
    return score;
    ^
    4 errors
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: QuestionAnalyser
         at QATest2.main(QATest2.java:4)
    This is the message I get from the submission page, but trying to compile it I get the same messages.
    The code looks like this, then
    class QuestionAnalyser{
    String[] answer;
    public static void main(String[] args) {}
         public int turnAnswersToScore(String[] answer)
    int score;
    for (int i = 0; i < answer.length; i++) {
    if (answer.equals("A")) {
    score++; }
    else if (answer[i].equals("B")) {
    score++;
    score++; }
    else if (answer[i].equals("C")) {
    score++;
    score++;
    score++; }
    else {}
    return score;
    When I leave 'public int score;' where it was before (right after the class declaration below the declaration of the string array) I get this but it compiles normally.
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    wrong answer in turnAnswersToScore for
    BDCAADDCA
    Alright, even university students need to sleep :-)
    Good night.

  • How to use a WebService Model with String Arrays as its input  parameter

    Hi All,
    I am facing the following scenario -
    From WebDynpro Java i need to pass 2 String Arrays to a Webservice.
    The Webservice takes in 2 input String Arrays , say, Str_Arr1[] and Str_Arr2[] and returns a string output , say Str_Return.
    I am consuming this WebService in WebDynpro Java using WEB SERVICE MODEL. (NWDS 04).
    Can you please help out in how to consume a WSModel in WD where the WS requires String Arrays?

    Hi Hajra..
    chec this link...
    http://mail-archives.apache.org/mod_mbox/beehive-commits/200507.mbox/<[email protected]>
    http://www.theserverside.com/tt/articles/article.tss?l=MonsonHaefel-Column2
    Urs GS

  • Help with 2D array input using a text file

    I'm writing a JAva program using BlueJ, which requires me to read info from a text file and put them into an 2D array. I got this error msg and I couldn't gifure out how to fix it. Please help me. Thanks a lot. The program is due tomorrow, please help.
    Error message:
    NoSuchElementException:
    null(in Java.util.StringTokenizer)
    Here's the program with the line where the problem is highlighted
    import java.io.*;
    import java.util.StringTokenizer;
    public class ***
    // Reads students' test scores from a file and calculate their final grade
    public static void main (String[] args) throws IOException
    String file1 = "C:/Temp/scores.txt";
    int[][] input = new int[25][5];
    StringTokenizer tokenizer;
    String line;
    FileReader fr = new FileReader (file1);
    BufferedReader inFile = new BufferedReader (fr);
    line = inFile.readLine();
    tokenizer = new StringTokenizer (line);
    for (int row = 0; row < 25; row++)
    for (int col = 0; col < 5; col++)
    input[row][col] = Integer.parseInt(tokenizer.nextToken()); --> porblem
    This is what the text file looks like:
    1 74 85 98
    2 97 76 92
    3 87 86 77
    4 73 85 93
    5 99 99 83
    6 82 84 95
    7 78 83 91
    8 84 79 84
    9 83 77 90
    10 75 78 87
    11 98 79 92
    12 70 73 95
    13 69 80 88
    14 81 77 93
    15 86 72 80
    16 70 76 89
    17 71 71 96
    18 97 81 89
    19 82 90 96
    20 95 85 95
    21 91 82 88
    22 72 94 94

    Try this code..(I've tested this code in my machine and it works fine)
              try {
                   FileReader fileReader = new FileReader("Z:\\fileInput.txt");
                   BufferedReader reader = new BufferedReader(fileReader);
                   int[][] fileData = new int[22][4];
                   StringTokenizer tokenizer = null;
                   String line = reader.readLine();
                   int rowCount = 0;
                   while(line != null) {
                        tokenizer = new StringTokenizer(line, " ");
                        int columnCount = 0;
                        while(tokenizer.hasMoreTokens()) {
                             fileData[rowCount][columnCount] = Integer.valueOf(tokenizer.nextToken()).intValue();
                             columnCount++;
                        line = reader.readLine();
                        rowCount++;
                   fileReader.close();
                   System.out.println("Done");
              } catch (FileNotFoundException fnfe) {
                   System.out.println("File not found " + fnfe);
              } catch (IOException ioe) {
                   System.out.println("IO Exception " + ioe);
    The problem with your code is that you should first check whether there are any tokens before doing nextToken().
    -Amit

Maybe you are looking for

  • How to open a net device in kernel?

    Hello there, Does someone have ideas to open a particular ethernet device in kernel? If there are several same type device, how to do that? Any advice will be really appreciated. zane

  • Multiple instances of a table & join supported in OBIEE SQLQuery report

    Hello All, I am creating a report in BIP based on the RPD created in OBIEE. I have to use multiple instances of same table in this case. But when I do that, I am getting "'The query contains a self join/This is a non-supported operation" error. Have

  • How can I have a stronger Facetime session?

    How can I have a stronger Facetime session between my Macbook and an iPhone? The calls seem to have a delay/latency. What would improve this? Is 4g the fastest mode available? Would using a cellular data plan work? Would having my own personal hotspo

  • StringIndexOutOfBoundsException - both cmd and ant error

    Hi there, having the following pblm. Using pmd 1.0 (latest available version, archived named 1.0.1 something) BUILD FAILED java.lang.StringIndexOutOfBoundsException: String index out of range: -1         at java.lang.String.substring(String.java:1938

  • XL-H1 aspect ratio error when exporting from FCP 1080p24 to compressor

    PLEASE HELP I have a finished project in fcp in a 1080p24 project. My source footage is 1440 x 1080i 24f from an xl-h1. When i export from final cut pro to compressor, compressor squeezes my footage into a square. if i export to dvd from compressor t