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

Similar Messages

  • Help creating 2D array from tab delimited text file

    I can print the info from the file, but darned if I can't make a 2-D array.
    import java.util.regex.*;
    import java.io.*;
    public final class goodSplitter {
        private static BufferedReader br;
        private static BufferedReader br2;
        private static String INPUT;
        private static int numLines;
        private static int numLine2;
        private static int q;
        private static int t;
        private static int n;
        private static String [][] indexArray;
        public static void main(String[] argv) {
            initResources();
            processTest();
            closeResources();
        private static void initResources() {
           try {
                  br = new BufferedReader(new FileReader("index.txt"));
              System.out.println("found the input file.");
                } catch (FileNotFoundException fnfe)
                   System.out.println("Cannot locate input file! "+fnfe.getMessage());
                          System.exit(0);
           try {
                  br2 = new BufferedReader(new FileReader("index.txt"));
              System.out.println("found file again.");
                } catch (FileNotFoundException fnfe)
                   System.out.println("Cannot locate input file again! "+fnfe.getMessage());
                          System.exit(0);
         try {     
                   int numLines = 0;     
                   while ( ( INPUT = br.readLine( ) ) != null )
                        { numLines++; } // end while
                   System.out.println("file has the number of lines: " + numLines);
                   q = numLines;
                   System.out.println("creating the array.");
                   String [][] indexArray = new String[q][];
                   System.out.println("populating the array.");
                   while ( ( INPUT = br2.readLine( ) ) != null ) {
                        n = t++;
                        System.out.println("first array index = " + n);
                        String[] ss = INPUT.split("\\s");
                        for(int i = 0; i < ss.length; i ++)
                                  System.out.println( new String( ss[i] ) );
                                  indexArray[n] = ss[i];
                             } // end for
                        } // end while
         } catch (Exception e)
              {System.out.println("something went wrong in populating the array of length " + q); }}
    private static void processTest() { System.out.println("processed text."); }
    private static void closeResources() {
    try{ br.close();  }catch(IOException ioe){} }

    you haven't sized the 2nd part of the 2d array
    add this line
    String[] ss = INPUT.split("\\s");
    indexArray[n] = new String[ss.length];//<--------------
    for(int i = 0; i < ss.length; i ++)
    but note you have declared indexArray both as a class variable
    private static String [][] indexArray;
    and a variable local to the try/catch block
    String [][] indexArray = new String[q][];
    probably what you want is
    indexArray = new String[q][];

  • I need your help with a decision to use iPhoto.  I have been a PC user since the mid 1980's and more recently have used ACDSee to manage my photo images and Photoshop to edit them.  I have used ProShow Gold to create slideshows.  I am comfortable with my

    I need your help with a decision to use iPhoto.  I have been a PC user since the mid 1980’s and more recently have used ACDSee to manage my photo images and Photoshop to edit them.  I have used ProShow Gold to create slideshows.  I am comfortable with my own folder and file naming conventions. I currently have over 23,000 images of which around 60% are scans going back 75 years.  Since I keep a copy of the originals, the storage requirements for over 46,000 images is huge.  180GB plus.
    I now have a Macbook Pro and will add an iMac when the new models arrive.  For my photos, I want to stay with Photoshop which also gives me the Bridge.  The only obvious reason to use iPhoto is to take advantage of Faces and the link to iMovie to make slideshows.  What am I missing and is using iPhoto worth the effort?
    If I choose to use iPhoto, I am not certain whether I need to load the originals and the edited versions. I suspect that just the latter is sufficient.  If I set PhotoShop as my external editor, I presume that iPhoto will keep track of all changes moving forward.  However, over 23,000 images in iPhoto makes me twitchy and they are appear hidden within iPhoto.  In the past, I have experienced syncing problems with, and database errors in, large databases.  If I break up the images into a number of projects, I loose the value of Faces reaching back over time.
    Some guidance and insight would be appreciated.  I have a number of Faces questions which I will save for later. 

    Bridge and Photoshop is a common file-based management system. (Not sure why you'd have used ACDSEE as well as Bridge.) In any event, it's on the way out. You won't be using it in 5 years time.
    Up to this the lack of processing power on your computer left no choice but to organise this way. But file based organisation is as sensible as organising a Shoe Warehouse based on the colour of the boxes. It's also ultimately data-destructive.
    Modern systems are Database driven. Files are managed, Images imported, virtual versions, lossless processing and unlimited editing are the way forward.
    For a Photographer Photoshop is overkill. It's an enormously powerful app, a staple of the Graphic Designers' trade. A Photographer uses maybe 15% to 20% of its capability.
    Apps like iPhoto, Lightroom, Aperture are the way forward - for photographers. There's the 20% of Photoshop that shooters actually use, coupled with management and lossless processing. Pop over to the Aperture or Lightroom forums (on the Adobe site) and one comment shows up over and over again... "Since I started using Aperture/ Lightroom I hardly ever use Photoshop any more..." and if there is a job that these apps can do, then the (much) cheaper Elements will do it.
    The change is not easy though, especially if you have a long-standing and well thought out filing system of your own. The first thing I would strongly advise is that you experiment before making any decisions. So I would create a Library, import 300 or 400 shots and play. You might as well do this in iPhoto to begin with - though if you’re a serious hobbyist or a Pro then you'll find yourself looking further afield pretty soon. iPhoto is good for the family snapper, taking shots at birthdays and sharing them with friends and family.
    Next: If you're going to successfully use these apps you need to make a leap: Your files are not your Photos.
    The illustration I use is as follows: In my iTunes Library I have a file called 'Let_it_Be_The_Beatles.mp3'. So what is that, exactly? It's not the song. The Beatles never wrote an mp3. They wrote a tune and lyrics. They recorded it and a copy of that recording is stored in the mp3 file. So the file is just a container for the recording. That container is designed in a specific way attuned to the characteristics and requirements of the data. Hence, mp3.
    Similarly, that Jpeg is not your photo, it's a container designed to hold that kind of data. iPhoto is all about the data and not about the container. So, regardless of where you choose to store the file, iPhoto will manage the photo, edit the photo, add metadata to the Photo but never touch the file. If you choose to export - unless you specifically choose to export the original - iPhoto will export the Photo into a new container - a new file containing the photo.
    When you process an image in iPhoto the file is never touched, instead your decisions are recorded in the database. When you view the image then the Master is presented with these decisions applied to it. That's why it's lossless. You can also have multiple versions and waste no disk space because they are all just listings in the database.
    These apps replace the Finder (File Browser) for managing your Photos. They become the Go-To app for anything to do with your photos. They replace Bridge too as they become a front-end for Photoshop.
    So, want to use a photo for something - Export it. Choose the format, size and quality you want and there it is. If you're emailing, uploading to websites then these apps have a "good enough for most things" version called the Preview - this will be missing some metadata.
    So it's a big change from a file-based to Photo-based management, from editing files to processing Photos and it's worth thinking it through before you decide.

  • Importing schema+ data using a text file containing sql commands

    I have the 2012 SQL SVR Mgmt Studio installed. I received a file--snippet below... from an export of our current DB provider, Advantage. I know I have to edit a lot of commands, but my question is quite simple--how do I use a text file with commands in it
    like below to create tables, columns and load data into SQL SVR.
    ---data.txt file contents----
    -- Table Type of Beneficiary is ADT
    Create Table Beneficiary(
       PlanId Char( 9 ),
       Hash Integer,
       Line1 Char( 128 ),
       Line2 Char( 128 ),
       Batch Char( 16 ) );
    EXECUTE PROCEDURE sp_CreateIndex90( 'Beneficiary', 'LAC_LACV1_Beneficiary.adi', 'KEY1', 'Hash;PlanId', '', 2051, 4096, NULL );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 983, 'Judith Pursifull~Spouse~100~~~', 'Michael Pursifull~Son~50~Thomas Pursifull~Son~50', '761011042' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 996, 'Anna Brownlow~Spouse~100~~~', 'Kaitlin Brownlow~Daughter~85~Lawanda Brownlow~Mother~15', '49036615' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 1005, 'Weldon Shelton~Other~50~Star Shelton~Other~50', 'Danica Shelton~Sister~50~Ryan Shelton~brother~50', '109075816' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 1031, 'Donald D Duffy~Spouse~100~~~', 'Brandon M Duffy~Son~100~~~', '219979254' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 1063, 'Lynne Roffino~Other~50~John Roffino~Other~50', 'Katy Roffino~Sister~50~Margaret Roffino~Sister~50', '604232358' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 1062, 'John Teaven Redstone~Spouse~100~~~', '~~~~~', '482024691' );
    INSERT INTO "Beneficiary" VALUES( 'LACV1', 1032, 'Judith Anne Brown (for cat care)~Other~50~Judith Ann (Kappler) Barklage~Other~50', 'LaVerne Cocke (for cat care)~Friend-PantegoBibl~50~~~', '358324107' );
    -- Table Type of Date is ADT
    Create Table Date(
       Hash Integer,
       PlanId Char( 9 ),
       Type Char( 24 ),
       Date Date,
       Override Logical,
       Batch Char( 32 ) );
    EXECUTE PROCEDURE sp_CreateIndex90( 'Date', 'LAC_LACV1_Date.adi', 'KEY1', 'Hash;Date;PlanId;Type', '', 2051, 4096, NULL );
    INSERT INTO "Date" VALUES( 1018, 'LACV1', 'HARDSHIPEND', '2010-02-20', False, '20090820-9414719' );
    INSERT INTO "Date" VALUES( 1018, 'LACV1', 'HARDSHIPSTART', '2009-08-20', False, '20090820-9414719' );
    INSERT INTO "Date" VALUES( 1001, 'LACV1', 'HARDSHIPEND', '2010-02-06', False, '20090806-9371968' );
    INSERT INTO "Date" VALUES( 1001, 'LACV1', 'HARDSHIPSTART', '2009-08-06', False, '20090806-9371968' );
    INSERT INTO "Date" VALUES( 1022, 'LACV1', 'LUMPSUMDISTRIBUTION', '2009-07-21', False, '20090721-9337640' );
    charles.leggette

    from an export of our current DB provider, Advantage.....
    -- Table Type of Date is ADT
    Create Table Date(
       Hash Integer,
       PlanId Char( 9 ),
       Type Char( 24 ),
       Date Date,
       Override Logical,
       Batch Char( 32 ) );
    Hello Charles,
    The SQL Syntax especially for DDL commands are different between MS SQL Server and Advantage Database, so you have to modify them to get them work.
    As David already wrote we don't have a stored procedure "sp_CreateIndex90" in SQL Server, you may remove these commands, and we also don't have a data type "Logical", next could be "bit"
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • Get information from an array saved into a text file

    I am trying to get information from an array saved as a text file to extract the information to build an string. This string will go out from the serial port to a device which will listen this message and it will answer the question. All the information sended sequencially it has to be obtained from that array. Every row contain one instruction and this has to be sended one after one.
    Could you tell me if is possible to make this driver? And if you have a similar driver, Where can I get it from?

    The VIs that I would suggest using are found in the String Function Pallet:
    Spreadsheet String To Array
    Array To Spreadsheet String
    The delimiter should be the termination character. These VIs will adapt to a string array.
    For the Spreadsheet String To Array wire an empty string array and use %s as the format. The delimiter should be the termination character of the text file, most likely a end of line (\r\n).
    For the Array To Spreadsheet String the delimiter should be the termination required for your serial device.
    Using a combination of these two VIs should provide you the functions required to make the driver.

  • Help with my array problem.

    Here I have 3 class. One main class, a class to add passengers and a class to display the seating chart.
    A blank seat represented by a "-" is turned into "x". When that is done it goes back to the main class to ask the user if if another passenger wants to be added, display seating chart or quit.
    The problem I have is if the user wants to add passengers after the first time then the array is set back to all blanks "-". I need help how on how to use the changed array after the first time so I can build onto existing seats that are already full, but initially the array has to be filled with "-". Also this changed array needs to be sent to the SeatingChart class to display the changed seating chart if the user selects that.
    I tried some stuff with tempArray[] but can't figure it out. Any help would be appreciated, thanks.
    Main class
    import java.util.*;
    public class Airline {
      public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        int mainOption = 0, passengers = 0;
        String seatingClass;
        Reservation reserveSeat;
        SeatingChart displaySeat = new SeatingChart();
        while (mainOption != 3){
          mainOption = 0;
          // Menu loop
          while (mainOption < 1 || mainOption > 3) {
            System.out.println("Welcome to the Airline. Please choose an option.\n");
            System.out.println(
                "Press 1 to add passengers. \nPress 2 to display the " +
                "seating chart. \nPress 3 to Quit.");
            mainOption = scan.nextInt();
        // if statement when 1 is chosen to add passengers
        if (mainOption == 1) {
          Scanner input = new Scanner(System.in);
          // User chooses first or economy class
          do {
            System.out.println("Type E for economy or F for first class:");
            seatingClass = input.nextLine();
          while (!seatingClass.equalsIgnoreCase("e") &&
                 !seatingClass.equalsIgnoreCase("f"));
          // If statement to get number of passengers for economy class
          if (seatingClass.equalsIgnoreCase("e")) {
            do {
              System.out.println("Enter the numbers of passengers: ");
              passengers = scan.nextInt();
            while (passengers < 1 || passengers > 3);
          // If statment to get number of passengers for first class
          if (seatingClass.equalsIgnoreCase("f")) {
            do {
              System.out.println("Enter the numbers of passengers: ");
              passengers = scan.nextInt();
            while (passengers < 1 || passengers > 2);
          // Passes info to Reservation class
          reserveSeat = new Reservation(seatingClass, passengers);
          // Prints out seating chart
          System.out.println(reserveSeat);
        // if statement when 2 is chosen to display seating chart
        if (mainOption == 2) {
          System.out.println(displaySeat);
        // if statement when 3 is chosen to quit
        if (mainOption == 3) {
          System.exit(0);
    }  reservation class for adding passengers.
    [codepublic class Reservation {
      private String seatClass;
      private int numPassengers;
      // First class has 8 seats (2 rows of 4 seats each)
      String[] firstClassSeat = new String[8];
    // Economy class has 24 seats (4 rows of 6 seats each)
    String[] economyClassSeat = new String[18];
    // Temp array for first class
    String[] tempArrayF = new String[8];
    // Temp array for economy class
    String[] tempArrayE = new String[18];
    public Reservation(){
    for (int i = 0; i < firstClassSeat.length; i++)
    firstClassSeat[i] = "-";
    for (int i = 0; i < economyClassSeat.length; i++)
    economyClassSeat[i] = "-";
    public Reservation(String c, int p) {
    seatClass = c;
    numPassengers = p;
    for (int i = 0; i < firstClassSeat.length; i++)
    firstClassSeat[i] = "-";
    for (int i = 0; i < economyClassSeat.length; i++)
    economyClassSeat[i] = "-";
    for (int i = 0; i < tempArrayF.length; i++){
    tempArrayF[i] = firstClassSeat;
    for (int i = 0; i < tempArrayE.length; i++){
    tempArrayE[i] = economyClassSeat[i];
    // First class statements
    if (seatClass.equalsIgnoreCase("f")) {
    if (numPassengers == 1){
    int countF = 0;
    for (int i = 0; i < firstClassSeat.length; i++){
    if (countF < 1){
    // If seat is blank - then fill seat with x
    if (firstClassSeat[i] == "-"){
    firstClassSeat[i] = "x";
    countF++;
    // Economy class statements
    if (seatClass.equalsIgnoreCase("e")) {
    if (numPassengers == 1){
    int countE = 0;
    for (int i = 0; i < economyClassSeat.length; i++) {
    if (countE < 1){
    // If seat is blank - then with seat with x
    if (economyClassSeat[i] == "-"){
    economyClassSeat[i] = "x";
    countE++;
    for (int i = 0; i < tempArrayF.length; i++){
    tempArrayF[i] = firstClassSeat[i];
    for (int i = 0; i < tempArrayE.length; i++){
    tempArrayE[i] = economyClassSeat[i];
    Getter Methods
    public String getSeatingClass() {
    return seatClass;
    public int getNumPassengers() {
    return numPassengers;
    public String[] getFirstClassSeat(){
    return firstClassSeat;
    public String[] getEconomyClassCeat(){
    return economyClassSeat;
    public String toString(){
    int f = 0, e = 0, count1;
    String text = "";
    while (f < 8) {
    if (f == 0 || f == 4 || f == 2 || f == 6) {
    text += firstClassSeat[f];
    f++;
    if (f == 1 || f == 5) {
    text += firstClassSeat[f] + "\t";
    f++;
    if (f == 3 || f == 7) {
    text += firstClassSeat[f] + "\n";
    f++;
    while (e < 18) {
    if (e == 0 || e == 1 || e == 3 || e == 4 || e == 6 || e == 7 ||
    e == 9 || e == 10 || e == 12 || e == 13 || e == 15 || e == 16) {
    text += economyClassSeat[e];
    e++;
    if (e == 2 || e == 8 || e == 14) {
    text += economyClassSeat[e] + "\t";
    e++;
    if (e == 5 || e == 11 || e == 17) {
    text += economyClassSeat[e] + "\n";
    e++;
    return text;
    Display Seating chart class
    public class SeatingChart extends Reservation{
      String seatClass;
      int numPassengers;
      // First class has 8 seats (2 rows of 4 seats each)
      String[] firstClassDisplay = new String[8];
      // Economy class has 24 seats (4 rows of 6 seats each)
      String[] economyClassDisplay = new String[24];
      public SeatingChart(){
      public SeatingChart(String[] f, String[] e) {
        firstClassDisplay = f;
        economyClassDisplay = e;
                   Getter Methods
      public String[] getFirstClassDisplay(){
        return firstClassDisplay;
      public String[] getEconomyClassDisplay(){
        return economyClassDisplay;

    Then how do I pass the information and keep the same object and not let it get set skip over the initialation part in Class Reservation so it doesn't go back too "-".
    Heres some updated since we can't edit. But it still doesn't work.
    Main Airline class
    import java.util.*;
    public class Airline {
      public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        int mainOption = 0, passengers = 0;
        String seatingClass;
        Reservation reserveSeat;
        SeatingChart displaySeat = new SeatingChart();
        while (mainOption != 3){
          mainOption = 0;
          // Menu loop
          while (mainOption < 1 || mainOption > 3) {
            System.out.println("Welcome to the Airline. Please choose an option.\n");
            System.out.println(
                "Press 1 to add passengers. \nPress 2 to display the " +
                "seating chart. \nPress 3 to Quit.");
            mainOption = scan.nextInt();
        // if statement when 1 is chosen to add passengers
        if (mainOption == 1) {
          Scanner input = new Scanner(System.in);
          // User chooses first or economy class
          do {
            System.out.println("Type E for economy or F for first class:");
            seatingClass = input.nextLine();
          while (!seatingClass.equalsIgnoreCase("e") &&
                 !seatingClass.equalsIgnoreCase("f"));
          // If statement to get number of passengers for economy class
          if (seatingClass.equalsIgnoreCase("e")) {
            do {
              System.out.println("Enter the numbers of passengers: ");
              passengers = scan.nextInt();
            while (passengers < 1 || passengers > 3);
          // If statment to get number of passengers for first class
          if (seatingClass.equalsIgnoreCase("f")) {
            do {
              System.out.println("Enter the numbers of passengers: ");
              passengers = scan.nextInt();
            while (passengers < 1 || passengers > 2);
          // Passes info to Reservation class
          reserveSeat = new Reservation(seatingClass, passengers);
          // Prints out seating chart
          System.out.println(reserveSeat);
        // if statement when 2 is chosen to display seating chart
        if (mainOption == 2) {
          System.out.println(displaySeat);
        // if statement when 3 is chosen to quit
        if (mainOption == 3) {
          System.exit(0);
    }Reservation class
    public class Reservation extends Airline{
      private String seatClass;
      private int numPassengers, count;
      // First class has 8 seats (2 rows of 4 seats each)
      String[] firstClassSeat = new String[8];
      // Economy class has 24 seats (4 rows of 6 seats each)
      String[] economyClassSeat = new String[18];
      // Temp array for first class
      String[] tempArrayF = new String[8];
      // Temp array for economy class
      String[] tempArrayE = new String[18];
      public Reservation(){
        for (int i = 0; i < firstClassSeat.length; i++)
          firstClassSeat[i] = "-";
        for (int i = 0; i < economyClassSeat.length; i++)
          economyClassSeat[i] = "-";
      public Reservation(String c, int p) {
        seatClass = c;
        numPassengers = p;
        if (count < 1){
          for (int i = 0; i < firstClassSeat.length; i++)
            firstClassSeat[i] = "-";
          for (int i = 0; i < economyClassSeat.length; i++)
            economyClassSeat[i] = "-";
        if (count > 0){
          for (int i = 0; i < tempArrayF.length; i++) {
            firstClassSeat[i] = tempArrayF;
    for (int i = 0; i < tempArrayE.length; i++) {
    economyClassSeat[i] = tempArrayE[i];
    // First class statements
    if (seatClass.equalsIgnoreCase("f")) {
    if (numPassengers == 1){
    int countF = 0;
    for (int i = 0; i < firstClassSeat.length; i++){
    if (countF < 1){
    // If seat is blank - then fill seat with x
    if (firstClassSeat[i] == "-"){
    firstClassSeat[i] = "x";
    countF++;
    // Economy class statements
    if (seatClass.equalsIgnoreCase("e")) {
    if (numPassengers == 1){
    int countE = 0;
    for (int i = 0; i < economyClassSeat.length; i++) {
    if (countE < 1){
    // If seat is blank - then with seat with x
    if (economyClassSeat[i] == "-"){
    economyClassSeat[i] = "x";
    countE++;
    for (int i = 0; i < tempArrayF.length; i++){
    tempArrayF[i] = firstClassSeat[i];
    for (int i = 0; i < tempArrayE.length; i++){
    tempArrayE[i] = economyClassSeat[i];
    count++;
    Getter Methods
    public String getSeatingClass() {
    return seatClass;
    public int getNumPassengers() {
    return numPassengers;
    public String[] getFirstClassSeat(){
    return firstClassSeat;
    public String[] getEconomyClassCeat(){
    return economyClassSeat;
    public String toString(){
    int f = 0, e = 0, count1;
    String text = "";
    while (f < 8) {
    if (f == 0 || f == 4 || f == 2 || f == 6) {
    text += firstClassSeat[f];
    f++;
    if (f == 1 || f == 5) {
    text += firstClassSeat[f] + "\t";
    f++;
    if (f == 3 || f == 7) {
    text += firstClassSeat[f] + "\n";
    f++;
    while (e < 18) {
    if (e == 0 || e == 1 || e == 3 || e == 4 || e == 6 || e == 7 ||
    e == 9 || e == 10 || e == 12 || e == 13 || e == 15 || e == 16) {
    text += economyClassSeat[e];
    e++;
    if (e == 2 || e == 8 || e == 14) {
    text += economyClassSeat[e] + "\t";
    e++;
    if (e == 5 || e == 11 || e == 17) {
    text += economyClassSeat[e] + "\n";
    e++;
    return text;
    display seat class
    public class SeatingChart extends Reservation{
      String seatClass;
      int numPassengers;
      // First class has 8 seats (2 rows of 4 seats each)
      String[] firstClassDisplay = new String[8];
      // Economy class has 24 seats (4 rows of 6 seats each)
      String[] economyClassDisplay = new String[24];
      public SeatingChart(){
      public SeatingChart(String[] f, String[] e) {
        firstClassDisplay = f;
        economyClassDisplay = e;
                   Getter Methods
      public String[] getFirstClassDisplay(){
        return firstClassDisplay;
      public String[] getEconomyClassDisplay(){
        return economyClassDisplay;

  • How to build an array based on inputs from a text file

    Hi
    I have ta text file that has the following format. The apmlitude is the first value then I have the start index number and last index number
    Other index values in between should be zero
    (amplitide, start index number, end index number)
    2, 2 ,3
    4, 6, 7
    5, 10,11
    using this format I should make the foloowing array
    0,0,2,2,0,0,4,4,0,0,5,5
    Could you please help me to implement it in LabVIEW
    Thanks

    A few notes:
    - You'll want to use the Initialize Array function for 1) and 3) (if this is, in fact, how you want to do this.)  This function takes two inputs when initializing a 1D array- element value and array size.   
    - Change the polymorphic instance of Read From Spreadsheet File.vi to "Double" or "Integer"- there's no reason to read in these numeric values as strings and convert them later.
    - Will the text file always contain 12 elements worth of data?  If not, you'll need to change your logic for the number of elements to initialize.
    As Altenbach said, this seems a lot like a basic logic/homework problem.  My suggestion was only that-a suggestion.  It is not the only way to do this. Figure out a sequence of steps to get you from point A to point B before you jump in and start coding. 
    Regards,
    Tom L.

  • 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.

  • Reading dilimited input from a text file with tokenizer

    i am trying to read in a text file with the following structure: 2 integers on each line with comma as the delimitor.
    i am using the BufferedReader stream and Tokenizer to detect ",".
    try {
    BufferedReader in = new BufferedReader(new FileReader(filename));
    //read in the data file
    while ((s = in.readLine())!= null) {
    int i = 0;
    for (i = 0; i < 100; i++) {
    t = new StringTokenizer(s,",");
    A1 = Integer.parseInt(t.nextToken());
    catch (IOException e) {System.err.println(e);}
    When i print out A1[i], it only reads the last line of the text file. Please tell me what's wrong.
    Also i'd really like A1[i] to store the integer before the comma and another array A2[i] to store the integer after the comma. Please help.
    Thanks.
    p.s. A1 and A2 are arrays...when i previewd message in Netscape 7 it left out the brackets and the index....

    What is the for i loop for? If it is to read the next line from the file, then the while loop has taken care of it. Other than this there should be no problem with the rest of the code.
    Just add another line to store the next token into A2.

  • 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 .

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to save input from a text file in to array

    I got this assignment, and almost have no clue, and my teacher doesn't even teaches us anything
    This is what i am suppose to do
    5. The program must store the following data about each student in this Talent Show:
    * The student's name (store as a String)
    * The student's average time score [only for the events they competed in] (store as a Double)
    Note: Some of the data comes directly from the text file, and some of the data must be calculated from the data that is read from the file.
    6. The program must search through all of the student's scores to find the student who has the minumum average time of all students.
    7. You must calculate how many events each student played. Zero values are not counted.
    8. You must then generate a report on the screen that prints out
    * the total number of students in the competition,
    * the winning student's ...
    o name
    o times
    o average time (rounded to one decimal places)
    Sample output
    btw this is the data file
    Bart Simpson
    7.5
    12.3
    7.8
    19.2
    9.9
    5.3
    8.5
    11.8
    2.2
    4.6
    Stewie Griffin
    9.5
    29.7
    7.8
    22.5
    9.9
    12.6
    8.5
    0
    8.2
    0
    Pinky
    2.5
    0
    1.8
    0
    3.9
    0
    6.5
    0
    5.2
    12.1
    Rocky N Bullwinkle
    10.0
    22.2
    9.5
    17.5
    9.9
    1.5
    8.7
    23.7
    9.2
    11.0
    Angelica Pickles
    5.5
    11.1
    6.8
    12.2
    7.9
    13.3
    8.1
    5.1
    7.2
    7.9
    Pink Panther
    8.5
    5.5
    8.8
    6.6
    8.9
    7.7
    9.9
    8.8
    2.2
    9.9
    Josie
    9.5
    0
    8.8
    12.2
    9.9
    0
    8.5
    0
    9.2
    5.3
    Rogue
    8.5
    1.1
    7.8
    2.2
    7.9
    3.3
    7.5
    4.4
    8.2
    5.5
    Usagi Tsukino
    8.5
    15.5
    8.8
    30.1
    9.9
    19.7
    9.5
    11.0
    8.2
    8.6
    Yosemite Sam
    0
    15.2
    0
    29.5
    3.9
    0
    0
    16.0
    0
    7.7
    My code so far
    import java.io.*;
    public class test
        public static void main (String [] args)
            FileInputStream File1;
            DataInputStream In;
            String fileInput = "";
            try
               File1 = new FileInputStream ("data.txt");
                In = new DataInputStream (File1);
                while (In.available () > 0)
                    fileInput = In.readLine ();
                    System.out.println (fileInput);
                In.close ();
            catch (FileNotFoundException e)
                System.out.println ("Error - this file does not exist");
            catch (IOException e)
                System.out.println ("error=" + e.toString ());
    }My question, how do i save the data in to an array, and how do i seperatly save names in to different array, and their scores in to different arrays
    bte he said you can use scanner class
    Thanks
    Edited by: supahsain08 on Mar 26, 2008 2:55 PM

    supahsain08 wrote:
    Well, you are not in my class and you don't even know my teacher
    who are you to judge meHe is jaded by our experiences here. 99% of posters who complain that the teacher doesn't teach have adequate (note that I didn't say good) teachers, but it's the student who is failing to take responsibility for his own education. It is after all your responsibility and complaining won't help you any.
    Good luck.

  • How to Test, Inbound idoc ,with out the Sender System, using a Text File

    Hi Guru's .
    we wanted to test BLAORD03 inbound idoc (Message Type BLAORD).with out the SENDER SYSTEM.
    on the same client.
    we wanted to test this idoc with text file from our local machine.
    Can anyone give us detail steps.like how to create  File layout
    with Segment name,and values for the fields.how to pass this file to the system.
    Thanks in advance.

    Hi Aparna.
    My requirement is to test the idoc with Inbound File.
    Generate a file with the data entered through segments through we19 ,and use the same file for processing through we16.
    when i am trying to do this syst complaing about
    Partner Profile not available, and some times
    port not available. and some  times with
    'No further processing defined'.
    but i maintained part profiles and port perfectly.
    Can you help me in testing with test 'File' port.

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

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

Maybe you are looking for

  • Iphone won't sync with itunes as my Mac software 10.5.8 means that I cannot update Itunes.

    Hi, I updated my iphone's software to ios7 but can't update Itunes to 11.3 as my is Mac software is  10.5.8 (needs at least 10.6). I can't sync my iphone to itunes now because of this- I can't afford to update my Mac software so i am wondering if the

  • Multiple Line Chart in BI Publisher

    Hi All, I have a requirement where i have to display the time taken by concurrent programs in last week Say.. I have 3 concurrent programs ( I can have more also) and the data can be represented as below. ConcProg-1 ConcProg-2 ConcProg-3 Mon 1 min 2

  • Bios F28 for dv2

    I have 2 identical laptops HP Pavillion dv2-1035ea - p/n NP805EA#ABU. I had given one for repair in 2010 and the HP Service repair installed the Bios F28 which made the machine quieter and it is performing smoothly. I did not realise it then, but rec

  • Getting an Acer external monitor to work with a MacBook Pro

    I just made the switch from PC to Mac and while I'm excited I'm having a few growing pains. Here's one thing I'm trying to figure out. Both at home and at the office I have external monitors configured. These worked well with the PC but I having some

  • Oracle Tree Hierarchy Query

    Hi, Hoping someone can assist with this query: I am currently using this query to construct a tree hierarchy, i.e. SELECT "EMP"."MGR" as "MGR",         "EMP"."EMPNO" as "EMPNO",         "EMP"."ENAME" as "ENAME" ,         (select count(*)  from "EMP"