Please help with File input!

This is my first time dealing with file I/O and need help figuring out the best way to read in data and store it for further manipulation. I have a file that contains an individual's salary, and 3 product ratings on each line, such as: 75000 01 05 09
What is the best way to store this data? I know how to use BufferedReader and how to tokenize each integer. I must write this program to deal with any number of lines in a file. There are three income brackets, and I must also be able to perform the following calculations:
a) For each income bracket, the average rating for each product
b) The number of persons in Income Bracket $50000-74000 that rates all three products with a score of 5 or higher.
c) The average rating for Product 2 by persons who rated Product 1 lower than Prodcut 3.
Thus far, I've written the following code to open the file and perform 2 reads to get the total number of lines (individuals) and the total number of inidividuals in each income bracket. It compiles, but I get a null pointed exception at StringTokenizer, for some reason.
Please help! Do I need to take lines in as arrays? (tried this, but don't understand how to get at individual data) Do I need to somehow create objects for each person (if so, how?). My reference text covers this area poorly. Thanks for all help.
import java.io.*;
import java.util.*;
public class Product_Survey
     public static void main(String [] args)
          int lineCount = 0;
          int inc1total = 0;
          int inc2total = 0;
          int inc3total = 0;
          String name = null;
          System.out.println("Please enter income and product info file name:  ");
          Scanner keyboard = new Scanner(System.in);
          name = keyboard.next();
          File fileObject = new File(name);
          while ((! fileObject.exists()) || ( ! fileObject.canRead()))
               if( ! fileObject.exists())
                    System.out.println("No such file");
               else
                    System.out.println("That file is not readable.");
                    System.out.println("Enter file name again:");
                    name = keyboard.next();
                    fileObject = new File(name);                    
          try
               BufferedReader inputStream = new BufferedReader(new FileReader(name));
               String trash = "No trash yet";
               while (trash != null)
                    trash = inputStream.readLine();
                    lineCount++;
               inputStream.close();
          catch(IOException e)
               System.out.println("Problem reading from file.");
          try
               BufferedReader inputStream = new BufferedReader(new FileReader(name));
               String trash = "No trash yet";
               while (trash != null)
                    trash = inputStream.readLine();
                    StringTokenizer st = new StringTokenizer(trash);
                    int income = Integer.parseInt(st.nextToken());
                    if(income<50000)
                         inc1total++;
                    else if(income<75000)
                         inc2total++;
                    else if(income<100000)
                         inc3total++;
               inputStream.close();
          catch(IOException e)
               System.out.println("Problem reading from file.");
}

Try adding a print statement to see what is happening in your second read loop:
            while (trash != null)
                trash = inputStream.readLine();
                System.out.println("trash = " + trash);
                StringTokenizer st = new StringTokenizer(trash);Another way to read in a while loop:
            while ((trash = inputStream.readLine()) != null)

Similar Messages

  • Please Help with XML input file

    I created a flash swf with AS3 and i am loading the data via XML. I have a background that needs to load and I also created a box in which I can change the color via XML. I am have problems writing the XML code. Could someone please help. I'm brand new to this so I don't know if i'm even close. Here is the xml info i have so far. thanks
    <data backgroundColor="0x202020" width="400" marginTop="150" marginBottom="150"><![CDATA[<p align="left">COPY GOES HERE<br><br></p>]]>
    </data>
    <backgrounds switchDelay="6000">
    <image allowScaling="true">background_images/image1.jpg</image>
    </backgrounds>

    Yes, it is possible. Unfortunately I can't provide any specifics for an XML data file because we use the "field nominated" format.
    Essentially, the data file contains data definition elements and references to the form(s) that the data gets applied to. With the field nominated data file (and an XML file is probably similar) there are two basic methods to do this. One, there is a form reference followed by all the field definitions that are to be applied to that form; then if there are other forms there would be another form reference followed by the fields for that form. Two, the data file would contain data field definitions as "global" fields and this would be followed by all of the form references that these global fields would be applied to; optionally, there would be form-specific field definitions following some of the form references.
    In field nominated format this looks like:
    ^form form-1-name.mdf
    ^field name
    George Jones
    ^field amount
    1234.00
    ^field date
    01/01/2000
    ^form form-2-name.mdf
    ^field regarding
    Tammy Wynette
    ^field occupation
    country music artist
    or
    ^global name
    George Jones
    ^global amount
    1234.00
    ^global regarding
    Tammy Wynette
    ^global occupation
    country music artist
    ^form form-1-name.mdf
    ^field date
    01/01/2000
    ^form form-2-name.mdf
    As I stated, I don't know how this would look within an XML file but I'm sure the concept would be the same. For the first example there might be a form reference followed by all the associated field definitions. In the second example there would be the global field references followed by the form references with the optional imbedded field reference(s). Or, at least, something similar.
    Perhaps someone that uses XML files will provide appropriate samples.

  • Please help with file reading component

    i am currently writing a program in which i need to have a JTable
    which displays data from a text file which can be selected from an
    option via a JList. I can get the info from the file into the JTable
    but for some reason which i can't figure out! the file reading method
    which i have written to read the data in the text file keeps reading the text file twice so i am getting duplicate data in the JTable. it may
    be easier to understand with the code i have supplied for the ListListener and the file reading method. the text file which is to be read contains data in the form - aName%anAddress%aBirthdate%aGender
    here is the code:-
    //class listening for JList selection
    class ListListener implements ListSelectionListener{
              public void valueChanged(ListSelectionEvent e){
    try{
    //send the selected index to file reading method
                   readFile(fileList.getSelectedIndex());
                   catch(IOException exception){
                   JOptionPane.showMessageDialog(
                                  PeopleJTable3.this,
                                  "File not found", "Error",
                                  JOptionPane.ERROR_MESSAGE);
              }//end of valueChanged
    //method to read a file given a specific index
    public void readFile(int fileNumber)throws IOException{
              BufferedReader keyboard = new
                   BufferedReader(new InputStreamReader(System.in));
    PrintWriter screen = new PrintWriter(System.out, true);
    //declare variables to enable separating the data in the file
    String fileName, name, address, birthdate, gender, line;
    int i=0;
    int lineLength,firstPercent,secondPercent, thirdPercent;
    PersonRecord[] group = new PersonRecord[20];
    final char PERCENT = '%';
    if(fileNumber == 0){
    fileName = new String("datafile.txt");
    //create filereader to read a byte stream from a file
    //oparameter has name of file;
    FileReader fr = new FileReader("datafile.txt");
    //create buffered reader object takes stream of characters
    //from filereader
    BufferedReader in = new BufferedReader(fr);
    line = in.readLine();
    // while (line != null){
    while( !line.equals("0")){
              //find second percentage
              firstPercent = line.indexOf(PERCENT);
              int a = firstPercent + 1;
              while(line.charAt(a) != '%'){
                   a++;
    //find third percentage
              secondPercent = a;
              int b = secondPercent + 1;
              while(line.charAt(b) != '%'){
                   b++;
              thirdPercent = b;
              //extract the name
              name = line.substring(0,firstPercent);
              //extract the address
              address = line.substring(firstPercent + 1, secondPercent);
              //extract the D.O.B.
              birthdate = line.substring(secondPercent + 1, thirdPercent);
    //extract overdraft amount;
    gender = line.substring(thirdPercent + 1, line.length());
    String[] tabEntry = {name,address,birthdate,gender};
    //add this row to JTable
    people.addRow(tabEntry);
    line = in.readLine();
    screen.println(i);//this was used to check that the
    //file was actually being read twice
    //from this method
    i++;
         }//end while loop
    in.close();
    }//end readFile
    if you can tell me why this read the file twice that would be fantastic!
    Cheers
    iain

    oh, that is right... the valueChanged() method will get called twice when you use a mouseclick, but if selecting from the keyboard it will only be called once. I'm not sure why it does that either, but what camickr suggested will fix it.
    Here is my substitution using the StringTokenizer..
    // you will need to import the class
    import java.util.StringTokenizer;
    // this will actually read the entire file until EOF
    while( (line = in.readLine()) != null )
         StringTokenizer st = new StringTokenizer( line, "%", false );
         // make sure there are at least 4 tokens in this line to read
         while( st.countTokens() == 4 )
              name = st.nextToken();
              address = st.nextToken();
              birthdate = st.nextToken();
              gender = st.nextToken();
         String[] tabEntry = {name,address,birthdate,gender};
         //add this row to JTable
         people.addRow(tabEntry);
    } //end while loopHere's the link to the StringTokenizer's API http://java.sun.com/j2se/1.3/docs/api/java/util/StringTokenizer.html
    good luck,
    .kim

  • Windows 8.1 BSOD please help Minidump file attached

    Windows 8.1 BSOD please help Minidump file and dxdiag info file link is below,
    This BSOD frequency is about once every  1 hour to 4 hours,
    Memtest passed with one pass on the one chip of 4GB
    Brand new 8.1 install
    https://drive.google.com/file/d/0B39S6eNyRvOHRnZHRG1Jd1lwT2M/view?usp=sharing
    https://docs.google.com/document/d/1XueM-ov7wjfePJh45Pp3fg1QSSzFBqMuO1tfr9GZm8k/edit?usp=sharing

    This is a crash related to some type of hardware failure. Please refer to the Wiki link below, for some troubleshooting tips.
    BugCheck Code 124 Co-Authored by ZigZag3143& JMH3143
    http://answers.microsoft.com/en-us/windows/wiki/windows_other-system/bugcheck-code-124/98c998d2-447a-40ce-ae1f-8211e355f14d
    WARNING: Whitespace at end of path element
    Symbol search path is: SRV*c:\symbols*http://msdl.microsoft.com/download/symbols
    Executable search path is:
    Windows 7 Kernel Version 9600 MP (2 procs) Free x64
    Product: WinNt, suite: TerminalServer SingleUserTS
    Built by: 9600.16422.amd64fre.winblue_gdr.131006-1505
    Machine Name:
    Kernel base = 0xfffff800`c0e7b000 PsLoadedModuleList = 0xfffff800`c113f990
    Debug session time: Tue Mar 3 23:19:34.178 2015 (UTC - 5:00)
    System Uptime: 0 days 0:00:04.947
    Loading Kernel Symbols
    Loading User Symbols
    Mini Kernel Dump does not contain unloaded driver list
    * Bugcheck Analysis *
    Use !analyze -v to get detailed debugging information.
    BugCheck 124, {0, ffffe000016f88f8, 0, 0}
    Probably caused by : hardware
    Followup: MachineOwner
    1: kd> !analyze -v
    * Bugcheck Analysis *
    WHEA_UNCORRECTABLE_ERROR (124)
    A fatal hardware error has occurred. Parameter 1 identifies the type of error
    source that reported the error. Parameter 2 holds the address of the
    WHEA_ERROR_RECORD structure that describes the error conditon.
    Arguments:
    Arg1: 0000000000000000, Machine Check Exception
    Arg2: ffffe000016f88f8, Address of the WHEA_ERROR_RECORD structure.
    Arg3: 0000000000000000, High order 32-bits of the MCi_STATUS value.
    Arg4: 0000000000000000, Low order 32-bits of the MCi_STATUS value.
    Debugging Details:
    BUGCHECK_STR: 0x124_AuthenticAMD
    CUSTOMER_CRASH_COUNT: 1
    DEFAULT_BUCKET_ID: VISTA_DRIVER_FAULT
    PROCESS_NAME: System
    CURRENT_IRQL: 0
    STACK_TEXT:
    ffffd000`2087f6c0 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!WheapCreateLiveTriageDump+0x81
    STACK_COMMAND: kb
    FOLLOWUP_NAME: MachineOwner
    MODULE_NAME: hardware
    IMAGE_NAME: hardware
    DEBUG_FLR_IMAGE_TIMESTAMP: 0
    FAILURE_BUCKET_ID: X64_0x124_AuthenticAMD_PROCESSOR_BUS_PRV
    BUCKET_ID: X64_0x124_AuthenticAMD_PROCESSOR_BUS_PRV
    Followup: MachineOwner
    1: kd> !errrec ffffe000016f88f8
    ===============================================================================
    Common Platform Error Record @ ffffe000016f88f8
    Record Id : 01d0563268a81312
    Severity : Fatal (1)
    Length : 928
    Creator : Microsoft
    Notify Type : Machine Check Exception
    Timestamp : 3/4/2015 4:19:34
    Flags : 0x00000002 PreviousError
    ===============================================================================
    Section 0 : Processor Generic
    Descriptor @ ffffe000016f8978
    Section @ ffffe000016f8a50
    Offset : 344
    Length : 192
    Flags : 0x00000001 Primary
    Severity : Fatal
    Proc. Type : x86/x64
    Instr. Set : x64
    Error Type : BUS error
    Operation : Generic
    Flags : 0x00
    Level : 3
    CPU Version : 0x0000000000100f42
    Processor ID : 0x0000000000000000
    ===============================================================================
    Section 1 : x86/x64 Processor Specific
    Descriptor @ ffffe000016f89c0
    Section @ ffffe000016f8b10
    Offset : 536
    Length : 128
    Flags : 0x00000000
    Severity : Fatal
    Local APIC Id : 0x0000000000000000
    CPU Id : 42 0f 10 00 00 08 02 00 - 09 20 80 00 ff fb 8b 17
    00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00
    00 00 00 00 00 00 00 00 - 00 00 00 00 00 00 00 00
    Proc. Info 0 @ ffffe000016f8b10
    ===============================================================================
    Section 2 : x86/x64 MCA
    Descriptor @ ffffe000016f8a08
    Section @ ffffe000016f8b90
    Offset : 664
    Length : 264
    Flags : 0x00000000
    Severity : Fatal
    Error : BUSLG_OBS_ERR_*_NOTIMEOUT_ERR (Proc 0 Bank 4)
    Status : 0xba00001000020c0f

  • [ETL]Could you please help with a problem accessing UML stereotype attributes ?

    Hi all,
    Could you please help with a problem accessing UML stereotype attributes and their values ?
    Here is the description :
    -I created a UML model with Papyrus tool and I applied MARTE profile to this UML model.
    -Then, I applied <<PaStep>> stereotype to an AcceptEventAction ( which is one of the element that I created in this model ), and set the extOpDemand property of the stereotype to 2.7 with Papyrus.
    -Now In the ETL file, I can find the stereotype property of extOpDemand as follows :
    s.attribute.selectOne(a|a.name="extOpDemand") , where s is a variable of type Stereotype.
    -However I can't access the value 2.7 of the extOpDemand attribute of the <<PaStep>> Stereotype. How do I do that ?
    Please help
    Thank you

    Hi Dimitris,
    Thank you , a minimal example is provided now.
    Version of the Epsilon that I am using is : ( Epsilon Core 1.2.0.201408251031 org.eclipse.epsilon.core.feature.feature.group Eclipse.org)
    Instructions for reproducing the problem :
    1-Run the uml2etl.etl transformation with the supplied launch configuration.
    2-Open lqn.model.
    There are two folders inside MinimalExample folder, the one which is called MinimalExample has 4 files, model.uml , lqn.model, uml2lqn.etl and MinimalExampleTransformation.launch.
    The other folder which is LQN has four files. (.project),LQN.emf,LQN.ecore and untitled.model which is an example model conforming to the LQN metamodel to see how the model looks like.
    Thank you
    Mana

  • Please help with slideshow problems!

    Am using Photoshop Elements 8 and trying to make a slideshow. Have tried 4 times now and keep ending up with same problem, cannot reopen project to continue edititing.  Won't show up in orginizer and when I find on harddrive and try to open get message " wmv file cannot be opened".  How can I save a
    slideshow inprogress and be able to reopen and continue to edit and make slideshow?  I want to thank anyone who can help me with this in advance as I
    have gotten so frustrated that I want to just scream.
    Thanks

    Thanks for the help, thought I had done so but maybe not.  Anyway will have another go at it, now may I ask another
    question?  I am trying to add audio to slideshow.  I have some music I purchased thru amazon as mp3 files but I get
    message no codec and when I try to add wmv I get same message.  What type of file do I need and how can I add
    multiple songs to one slideshow.   I have one little wmv file that will go in, but it just replicates itself multiple times until
    it fills slide show. 
    Thanks again, sorry to be a bother, but this thing is driving this old man crazy.
    Date: Sun, 26 Dec 2010 20:34:32 -0700
    From: [email protected]
    To: [email protected]
    Subject: Please help with slideshow problems!
    You need to save the slideshow project in order to be able to go back later and make changes or additions to an existing slideshow . The wmv file is a final output format.
    Now you are most probably using only the Output command: that is what makes the wmv file.
    You should also do the Save Project command. (and I make it a practice to do the Save Project command before I do the Output command).
    If you look at the Elements Organizer 8 Help, there is a topic on "Create a slide show".
    -- Very close to the beginning of that topic is a screen shot of the Sldie Show Editor screen,
    -- The bar below the usual menu bar is labeled with a "B" and called the Shortcuts bar.
    -- The 1st entry on that Shortcuts bar is "Save Project"
    It is the Save Project command that saves the information about which photos, audio, etc you placed in that specific slide show so that you can come back again to do subsequent editing.  Save each Project with a unique name.
    After completing the Save Project command, you shoud see an "icon" in the Organizer for that slide show.
    Note:  you must also keep the photo files and audio files which you have used in this slide show: you can't delete them because the project file does NOT contain a copy of the photos, it only has the identification and folder location of the photo and audio files.
    >

  • My "fn" button is stuck on only revealing mission control in Lion. With this problem none of my "f" keys will work nor can I hold "fn" and delete to delete text in opposite direction. Can someone please help with this?

    My "fn" button is stuck on only revealing mission control in Lion. With this problem none of my "f" keys will work nor can I hold "fn" and delete to delete text in opposite direction. Can someone please help with this?

    Following the fix here worked for me:
    https://discussions.apple.com/message/15680566#15680566
    except my plist file was in ~/Library instead of /Library.
    -Scott

  • HT5824 I switched over from an iPhone to a Samsung Galaxy S3 & I haven't been able to receive any text messages from iPhones. Please help with turning my iMessage completely off..

    I switched over from an iPhone to a Samsung Galaxy S3 & I haven't been able to receive any text messages from iPhones. I have no problem sending the text messages but I'm not receivng any from iPhones at all. It has been about a week now that I'm having this problem. I've already tried fixing it myself and I also went into the sprint store, they tried everything as well. My last option was to contact Apple directly. Please help with turning my iMessage completely off so that I can receive my texts.

    If you registered your iPhone with Apple using a support profile, try going to https://supportprofile.apple.com/MySupportProfile.do and unregistering it.  Also, try changing the password associated with the Apple ID that you were using for iMessage.

  • How can I sync my iPhone on a different computer without erasing my applications? My iPhone was earlier synced with a PC which I don't use anymore. Please help with proper steps, if any.

    How can I sync my iPhone on a different computer without erasing my applications? My iPhone was earlier synced with a PC which I don't use anymore.
    On the new computer, I am getting a message that my all purchases would be deleted if I sync it with new iTunes library.
    Please help with proper steps, if any.

    Also see... these 2 Links...
    Recovering your iTunes library from your iPod or iOS device
    https://discussions.apple.com/docs/DOC-3991
    Syncing to a New Computer...
    https://discussions.apple.com/docs/DOC-3141

  • Please help with "You can't open the application NovamediaDiskSupressor because PowerPC applications are no longer supported." I have seen other responses on this but am not a techie and would not know how to start with that solution.

    Please help with the message I am receving on startup ""You can't open the application NovamediaDiskSupressor because PowerPC applications are no longer supported."
    I have read some of the replies in the Apple Support Communities, but as I am no techie, I would have no idea how I would implement that solution.
    Please help with what I need to type, how, where, etc.
    Many thanks
    AppleSueIn HunterCreek

    I am afraid there is no solution.
    PowerPC refers to the processing chip used by Apple before they transferred to Intel chips. They are very different, and applications written only for PPC Macs cannot work on a Mac running Lion.
    You could contact the developers to see if they have an updated version in the pipeline.

  • Hi, please help with the installation of Lightroom 4, I bought a new Mac (Apple) and I want to install a software that I have on the album cd. My new computer does not have the drives. Can I download software from Adobe? Is my license number just to be ab

    Hi, please help with the installation of Lightroom 4, I bought a new Mac (Apple) and I want to install a software that I have on the album cd. My new computer does not have the drives. Can I download software from Adobe? Is my license number just to be able to download the srtony adobe.

    Adobe - Lightroom : For Macintosh
    Hal

  • Want a complete migration guide to upgrade 11.1.0.7 to 11.2.0.3 database using DBUA..We are implementing R12.1.3 version and then have to migrate the default 11gR1 database to 11.2.0.3 version. Please help with some step by step docs

    Want a complete migration guide to upgrade 11.1.0.7 to 11.2.0.3 database using DBUA..We are implementing R12.1.3 version and then have to migrate the default 11gR1 database to 11.2.0.3 version. Please help with some step by step docs

    Upgrade to 11.2.0.3 -- Interoperability Notes Oracle EBS R12 with Oracle Database 11gR2 (11.2.0.3) (Doc ID 1585578.1)
    Upgrade to 11.2.0.4 (latest 11gR2 patchset certified with R12) -- Interoperability Notes EBS 12.0 and 12.1 with Database 11gR2 (Doc ID 1058763.1)
    Thanks,
    Hussein

  • Welcome. At the outset, I'm sorry for my English :) Please help with configuration Photoshop CS6 appearance. How to disable the background of the program so you can see the desktop. (same menus and tools) Chiałbym to be the same effect as CS5.

    Welcome.
    At the outset, I'm sorry for my English
    Please help with configuration Photoshop CS6 appearance.
    How to disable the background of the program so you can see the desktop. (same menus and tools)
    i wantto be the same effect as CS5.

    Please try turning off
    Window > Application Frame

  • HT201210 cont contact apple server error please help with ipad touch 4. im just fed up with apple please help me because why is it only apple with these kind of problems?

    cont contact apple server error please help with ipad touch 4. im just fed up with apple please help me because why is it only apple with these kind of problems?

    If you mean updae server
    Update Server
    Try:
    - Powering off and then back on your router.
    - iTunes for Windows: iTunes cannot contact the iPhone, iPad, or iPod software update server
    - Change the DNS to either Google's or Open DNS servers
    Public DNS — Google Developers
    OpenDNS IP Addresses
    - For one user uninstalling/reinstalling iTunes resolved the problem
    - Try on another computer/network
    - Wait if it is an Apple problem
    Otherwise what server are you talking about

  • HT3209 Purchased DVD in US for Cdn viewing. Digital download will not work in Cda or US? please help with new Digital code that will work

    Purchased DVD in US for Cdn viewing. Digital download will not work in Cda or US? please help with new Digital code that will work

    You will need to contact the movie studio that produced the DVD and ask if they can issue you a new code valid for Canada. Apple cannot help you, and everyone here in these forums is just a fellow user.
    Regards.

Maybe you are looking for