Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2006

Tip: Looking for answers? Try searching our database.

Problems with Map.size()..........

Thread view: 
gbattine - 30 May 2006 23:24 GMT
Hi,
i've a question to resolve.
I'm developing an application that have to receive an input text file
with first column of string type and the others columns of double type.
I have used a map and i create an objet composed by a key string and an
array of double.
My question is that Ncol(number of columns) is not well calculated.
Can you help me to find the error?
Here is my code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.HashMap;
public class AddDb2 {
   private static String fileName = "Dato2.txt";
   private Map <String, double[]>dataMap = null;
   private int Nrows=0;
   private int Ncol=0;
   public static void main(String[] args) throws IOException {
       new AddDb2();
   }

   public AddDb2() throws IOException { //constructor
       /* Get a reference to the input file. */
       FileReader file = new FileReader(fileName);
       BufferedReader br = new BufferedReader(file);
       /* Create the empty map. */
       this.dataMap = new HashMap<String, double[]>();/*Constructs an
empty HashMap
       with the default initial capacity (16) and the default load
factor (0.75).*/
       /* Populate the map from the input file. */
       populateMap(br);
       Ncol=(dataMap.size()+1);//include the first string row
       System.out.println("Il numero di colonne
e'"+(dataMap.size()+1));
       //System.out.println("Il numero di colonne del file
è"+dataMap.size());
       /* Display the contents of the map. */
       displayMap(this.dataMap);
       /* Close the reader. */
       br.close();
   }

   /**
    * Populate an HashMap from an input file.
    *
    * <p>This method accomodates an input file with any number of
lines in
it. It also accomodates any number of doubles on the input line as long
as the
first value on the line is a String. The number of doubles on each
input line can also
vary.</p>
    *
    * @param bufferedReader
    * @return a Map that has one element for each line of the input
file;
the key is the first column from the input file and the entry is the
array
of doubles that follows the first column
    * @throws IOException
    */
   public Map populateMap(BufferedReader bufferedReader) throws
IOException
{
       System.out.println("Caricamento dell'array di double in
corso.....");
       /* Store each line of the input file as a separate key and
entry in
       the Map. */
       String line = null;
       while ((line = bufferedReader.readLine()) != null) {
           //line = line.replace (',', '.');
           Nrows++;
           /* Create a tokenizer for the line. */
           StringTokenizer st = new StringTokenizer(line);
           /*
            * Assuming that the first column of every row is a String
and
the remaining columns  are numbers, count the number of numeric
columns.
            */
           //int ColNumber=st.countTokens();
          // int numberOfNumericColumns = ColNumber- 1;
           int numberOfNumericColumns = (st.countTokens()-1);
           //System.out.println("Il numero di colonne del file
è"+dataMap.size());
           System.out.println("Il numero di colonne numeriche del file
è"+numberOfNumericColumns);
           /*
            * Get the first token from the line. It will be a String
and
its value will be a  unique key for the rest of the row.
            */
           String key = st.nextToken().trim();
           /* Create the array for the numbers which make up the rest
of the line. */
           double[] array = new double[numberOfNumericColumns];
           /* Populate the array by parsing the rest of the line. */
           for (int column = 0; column < numberOfNumericColumns;
column++){
               array[column] =
Double.parseDouble(st.nextToken().trim());
           }
           /* Store the first column as the key and the array as the
entry.
*/
           this.dataMap.put(key, array); /*Associates the specified
value with
           the specified key in this map.*/

       }
       System.out.println("Il numero di righe del file e'"+Nrows);
       System.out.println("Il numero di colonne del file
è"+dataMap.size());
       return this.dataMap;
   }

   public void displayMap(Map<String,double[]> myMap) {
       /* Iterate through the values of the map, displaying each key
and
its corresponding array. */
       for (Map.Entry<String, double[]> entry : myMap.entrySet()) {
           /* Get and display the key. */
           System.out.print(entry.getKey() + " : ");
           /* Get the array. */
           double[] myArray = entry.getValue();
           /*
            * Display each value in the array. Put a semicolon after
each
value except the last.
            * Keep all the values for a given key on a single line.
            */
           for (int ix = 0; ix < myArray.length; ix++) {
               if (ix <  myArray.length - 1) { //the value is not the
last one in the array ,allora metti ;
                   System.out.print(myArray[ix] + "; ");
               } else { //the value is the last one in the array ,la
linea finisce così
                   System.out.println(myArray[ix]);
               }
           }
       }
   }
}

Another question:
I'm working on devoloping an application with JSF that allow to user to
upload a txt file like that in my application above...can i use this
java function to count the number of columns of my uploaded file with
JSF application?Are they compatible?
Please help me,thanks
chris brat - 31 May 2006 07:07 GMT
Hi,

What exactly is the error with the column calculation? Too high, too
low?

If you get your backend code running correctly it won't matter what you
use in the front i.e. command line, JSF etc.

Chris
gbattine - 31 May 2006 15:51 GMT
chris brat ha scritto:

> Hi,
>
> What exactly is the error with the column calculation? Too high, too
> low?

It's too low of one unit and i don't understand he cause

> If you get your backend code running correctly it won't matter what you
> use in the front i.e. command line, JSF etc.
>
> Chris
Thomas Weidenfeller - 31 May 2006 16:08 GMT
> It's too low of one unit and i don't understand he cause

Think harder.

>>>             int numberOfNumericColumns = (st.countTokens()-1);
                                                              ^^

>>>             /*
>>>              * Get the first token from the line. It will be a String
>>> and
>>> its value will be a  unique key for the rest of the row.
>>>              */
>>>             String key = st.nextToken().trim();

key is never added to the map. So of course there is one element less in
the map than columns in the file. Always.

If you re-read my original post, you will find that I sad that there are
 Map.size() (-1) columns in the map. I wrote that -1 for a reason.

/Thomas
Signature

The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.