Scanner Input from File

I'm trying to read from an external file using the Scanner class and to store the input in the applicable arrays, but I don't know how to skip lines.
For example, if a text file has this in it:
Name: Bob
Age: 30
Job: Engineer
Name: Joe
Age: 40
Job: ManagerIt reads fine, and stores fine. But, if I have this instead:
Name: Bob
Age: 30
Job: Engineer
Name: Joe
Age: 40
Job: ManagerWith the empty line, the String class throws an index out of range exception. Same goes for if the very first line of the file is also blank.
Here is my code:
String[] name = new String[100];
int[] age = new int[1000];
String[] job= new String[1000];
     try {
              Scanner input = new Scanner(new BufferedReader(new FileReader("test.txt")));
              for (int i = 0; input.hasNext(); i++) {
                   name[i] = input.nextLine().substring(6);
                   age[i] = Integer.parseInt(input.nextLine().substring(5));
                   job[i] = input.nextLine().substring(5);
                   System.out.println("Name: " + name);
               System.out.println("Age: " + age[i]);
               System.out.println("Job: " + job[i]);
          input.close();
     } catch (FileNotFoundException error) {}Thank you all very much!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

I already have something else that is handling non-existent files, so I don't need to do anything there.
And thank you very much, I figured out how to do it! I just needed to temporarily store the line, see if it was longer than 1 in length, and perform based on that.
Thank you very much!
Edited by: ManiKatti on Dec 31, 2009 7:14 PM

Similar Messages

  • Follow Up to Scanner Input from File

    Alright, I have another problem. My code is this:
    for (int j = 0; j < username.length; j++) {
         String line = input.nextLine();          // Create a temporary String that will store each line
         // Check if the temporary line isn't empty
         if (line.length() > 1) {
                 numAccounts++;
                 username[j] = line.substring(10);
                 password[j] = input.nextLine().substring(10);
                 System.out.println(username[j]);
         } else {     // If the temporary line is empty, go back on the loop to prevent empty array entries
                  j--; }
         }It runs through once, and then stops. Here are the declarations:
    static int numAccounts = 1;
    static String[] username = new String[numAccounts];
    static String[] password = new String[numAccounts];
    static  Scanner input = new Scanner(new BufferedReader(new FileReader("account.txt")));Which was done outside of the main method.
    Why does the loop iterate only once?

    Woah, don't need to get all heated up about something I'm doing wrong. I'm just trying to figure this out. Sorry if I'm getting on your nerves.
    So anyways, I did the ArrayList method with your suggestion of making it an ArrayList of Objects. This is what I have so far:
    // Declare the ArrayList that will store all the Account Objects retrieved from the database
    static ArrayList<Account> accounts = new ArrayList<Account>();
    while (input.hasNextLine()) {
        String line = input.nextLine();          // Create a temporary String that will store each line
        // Check if the temporary line isn't empty
        if (line.length() > 0) {
             //System.out.println(line);
             String currentName = line.substring(10);
             String currentPass = input.nextLine().substring(10);
             Account current = new Account(currentName, currentPass);
             accounts.add(current);
    }Yes, I stuck with using the line.length() > 0, because trying to use line != null doesn't work properly for me. Not entirely sure why. Just throws IndexOutOfBoundsException when it's called.
    And my Account Object class is as so:
    class Account {
         static String username, password;
         Account(String username, String password) {
              this.username = username;
              this.password = password; }
    }I tried to print out the username and passwords to the indexes of 0, 1, and 2, and they're all the same.
    System.out.println(accounts.get(0).username);
    System.out.println(accounts.get(0).password);
    System.out.println(accounts.get(1).username);
    System.out.println(accounts.get(1).password);
    System.out.println(accounts.get(2).username);
    System.out.println(accounts.get(2).password);What is also interesting, is that it only fetched (or copied) the last two lines in the text document. It ignores all the entries before that.
    Do you know what I did wrong? I think I did a logic error in there somewhere.

  • Redirect standard input from file to terminal

    Is there any way to redirect standard input from file to terminal within the same program? That is, get data from a file then redirect standard input to make it interactive with the terminal?

    BIJ001 wrote:
    No, the stdin, stderr, stdout, and working directory are environmental variables that are set
    when your process is launched, and they cannot be changed from within your java application.Can't they?
    //java.lang.System
    public static void setIn(InputStream in)
    //   Reassigns the "standard" input stream.
    public static void setOut(PrintStream out)
    //  Reassigns the "standard" output stream.
    public static void setErr(PrintStream err)
    //  Reassigns the "standard" error output stream.
    Since:
    JDK1.1
    Duh, you're right. I researched this looking for a way to change the working directory and found that you could not change that after launch - for some reason I remembered it wrong as being the stderr, stdin, and stdout in addition.

  • Setting up position of front panel objects using input from file

    I am working on a project and i have got the following query.
    i have a front panel with lot of objects like knobs,dials,push buttons etc..
    the entire panel will be the console to the user and as he changes the various
    positions of the objects their values will be written in to a file.
    now after a days work when the system is restarted again the next day
    the values of various objects should be read from the file and the front panel objects should be set in their position according to it
    in short the objects(knobs,buttons etc) should both act as o/p i.e when user interacts with them and they should also act as i/p when their position will be set from
    file.
    how can i achieve this.any help regard
    ing this would be greatly appreciated

    You should separate the read portion of this vi from the write portion of the vi. You want to execute the read portion of the vi only at startup and the write portion of the vi only at shutdown. So you'll be reading the file and writing the output to the property nodes, running your program, and then taking the value of the controls and writing to file. I have attached an example of how this might work. You might also do this with a state machine structure to control the data flow.
    Hope that helps
    Attachments:
    query.vi ‏49 KB
    read_file.vi ‏42 KB
    write_file.vi ‏36 KB

  • Scanner input from other class

    i have the following scanner class
    import java.util.Scanner;
    public class Input {
       // Prompted input of an int
       public static int getInt( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           int result = in.nextInt();
           return result;
       // Prompted input of a float
       public static float getFloat( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           float result = in.nextFloat();
           return result;
       // Prompted input of a word/token
       public static String getToken( String prompt ) {
          Scanner in = new Scanner(System.in);
           System.out.print( prompt + " : " );
           String result = in.next();
           return result;
    however i want to edit the code to get the following things from a different class to be displayed when run.
    String name = cname.getText();
    int length = Integer.parseInt(length.getText());
    any ideas on how to do this

    Edit: Nevermind. I guess for the prompts.
    ANY-who...
    float f = Input.getFloat(/*prompt string */);
    String s = Input.getText(/* prompt string */);
    Input. ...etc.
    Message was edited by:
    jGardner

  • Remove  "  from file

    Hallow Im doing a batch input from file csv (comma dilmeted) In the file I have company that ok and company name with before and after the company name word <b>''</b>    how can I get rid of  from that . just<b> ''</b> before and after the company name .
    *--table with data from file(csv)--
      LOOP AT itab1.
        SPLIT itab1 AT ',' INTO:
           itab-osek_morsh
           <b>itab-company_name</b>
           itab-company_code.
        APPEND itab.
      ENDLOOP.

    Hi Antonio ,
    Now what i understand is that some companies may have " at begining , some may have at end , some may have both and some none .
    So your requirement is that if there is a " as the first char or last then we need remove it , for all other cases it is not required.
    If my understanding is correct , here is the code which gives the desired result
    * Selection Screen
    parameters : p_string type string .
    start-of-selection.
    DATA : t_result type  MATCH_RESULT_TAB. " Internal table
    data : v_string type i .
    v_string = strlen( p_string ).   " Get the lenght of string
    * get the offset of all occurances of " in your string
    FIND ALL OCCURRENCES OF '"' IN P_STRING RESULTS T_RESULT.
    v_string = v_string - 1.  " Here the offset start with zero
    * Check if last char is "
    read table t_result with key OFFSET = v_string transporting NO FIELDS .
    if sy-subrc = 0.
    " If yes remove if from string
    p_string = p_string+0(v_string).
    endif.
    *Check if the first char is "
    read table t_result with key OFFSET = '0' transporting NO FIELDS .
    if sy-subrc = 0.
    * if yes replace with space
      replace '"' in p_string with ' '
    endif.
    Check if this serves your purpose , if not please tell what is the concern you have.
    Thanks
    Arun

  • When I try to load an image from the scanner, or from a file, into a bank deposit script, I get a message - "Error Java heap space". Need help to diagnose and fix this problem.

    I am running a script from my banking facility which asks me to load an image of the front and back of the check. I never had a problem before, but this time when I try to load the images either directly from the scanner, or from previously saved jpg files I get an error window message that says - Error Java heap space,
    Ed Marcato

    I am running a script from my banking facility which asks me to load an image of the front and back of the check. I never had a problem before, but this time when I try to load the images either directly from the scanner, or from previously saved jpg files I get an error window message that says - Error Java heap space,
    Ed Marcato

  • Is there an easy way to run an Ajax function from input type=file to test the file name in DB?

    I've had the <input type="file">  ... <cffile ...> thing going for a few years now. 
    There is a database where the uploaded file names are stored once the files are uploaded to the server.  It sees things in terms of problems and stores uploaded file name accordingly with the ProbID prepended onto the file name; e.g., MyPicture.jpg would end up in the designated directory and databawe as P416_MyPicture.jpg.  This allows user to store pictures with the same name in different problems without a conflict.  There has been an issue with certain characters (e.g., spaces, +, #, etc.) causing problems when they are in file names so we have come up with a way using the <cffile ... rename> to replace these chars with _.  This means that MyPic+.jpg would end up being P416_MyPic_.jpg. 
         This is where the problem appears.  If someone were to upload MyPic+.jpg after someone else uploaded MyPic_.jpg in the same problem, then the + file would overwrite the _ file before the system knew they had a problem.  And there is now way to restore the original file without going to the system backup and doing so – which is a whole other story … especially, if the person doesn’t tell anyone.
         The logical solution would be to be able to test the new final file name (the name after making the substitutions mentioned above) against the existing files in the database before you went from the page where the <input type=file> control to the associated _action.cfm page where the <cffile> object is located.  Given that this seems to be the province of Ajax, this would seem like a natural use of the really interesting technology.  I have can determine the file name from the onChange action on the <input type=File> so that this would be the place for Ajax to come to the rescue by looking up the final file name and then letting the user know whether the resultant name is a unique within the database or not.  If so, I'll just enable the Add button which sets right next to the <input > control and let them upload it.  If not, I'll put up an error message telling them that this file already exists in the system.
         This would be the perfect solution.  It would let me do some Ajax stuff like I've wanted to do for the past year, but never have had the time to do because this is the project that won't go away.  This is, in fact, the last thing of any consequence that remains to do on this 2-1/2 year nightmare – be careful what you wish for.  If I can get this done this week, then maybe I can finally take a weekend off … maybe it will finally come to an end.
         Which finally leads to my question:  I'm looking for some tips on how to get this thing going since I can barely spell Ajax.  I've got a book and looked at some stuff online about CF and Ajax, but a good example or two or three would be worth a day's worth of poking around on the web and in my books.
         Thanks in advance for any suggestions, ideas, help, whatever.
    Len

    Adam,
         Thank you for your suggestion, but, after spending the night working with Ben Forta's CF8, vol 2, Chap 34, working with <cfajaxproxy>, I was able to do exactly what I wanted and it appears, after some testing, to work exactly as I had envisoned it should. 
         I am now calling a JavaScript function (testFileName) from the onChage event on the <input type="file"> or Browse button, which calls my proxy.cfc that contains the server side of the equation.  This funciton testFileName (I've run out of cleaver function/file names).  The query contained therein hits the database to see if the passed in parameters can pull up an existing file.  If they do, the particulars (file name, data attahced, etc.) are returned to the JavaScipt procedure that puts up the error notice.  The user can then chose to either overwrite the file or quit.  Quiting leaves the your on the Attachment PopUp where he/she started with nothing being uploaded. 
         Thanks again for your suggestion.  I appreciate your taking the time to do so.
    Len

  • From browse button of input type=file, can I show the content of a file

    Hi all,
    I am using, input type=file, where browse button appears. I am having a text area. My requirement is after I select the browse button, I need to show the content of the file in the text area. As of now I 've handled by having another button 'show', which should be pressed after browse done. But, How to handle it in the browse button itself, how will I get that action event from browse button. Plz help.
    Regards,
    Sam

    I think someone asked a very similar question here,
    http://forum.java.sun.com/thread.jsp?forum=45&thread=501889
    check the thread, it may help you.
    -S-

  • Cannot find file I'm trying to input from

    I created a small text file called "Trial.txt" and tried inputting from it, but always got a runtime error saying the file cannot be found. Here's the relative code, but I'm not sure how I can identify the file.
    File inputFile = new File("Trial.txt");
    FileReader in = new FileReader(inputFile);
    StreamTokenizer LetterFilter = new StreamTokenizer(in);

    Problem solved. ;) Thanks for everyone who was willing to help!

  • User Input from Text File

    Hello
    I would like to incorporate code into this to allow the script I found on the internet to pull input from a txt file and then wait for the script to end before using the next entry in the text file and run until all entries in the text file have been used.
    Any help would be great thx.
    Jason
    ' Get Options from user
    GetOptions
    If (bInvalidArgument) Then
        WScript.Echo "Invalid Arguments" & VbCrLf
        bDisplayHelp = True
    End If
    If (bDisplayHelp) Then
        DisplayHelp
    Else
        If (bCheckVersion) Then
            CheckVersion
        End If
        If (strComputer = "") Then
            strComputer = InputBox("What Computer do you want to document (default=localhost)","Select Target",".")
        End If
        If (strComputer <> "") Then
            ' Run the GatherWMIInformation() function and return the status
            ' to errGatherInformation, if the function fails then the
            ' rest is skipped. The same applies to GatherRegInformation
            ' if it is successful we place the information in a
            ' new word document
            errGatherWMIInformation = GatherWMIInformation()
            If (errGatherWMIInformation) Then
                If (bDoRegistryCheck) Then
                    errGatherRegInformation = GatherRegInformation
                End If
                GetWMIProviderList
            Else
                WScript.Quit(999)
            End If
            If (bHasMicrosoftIISv2) Then ' Does the system have the WMI IIS Provider
                GatherIISInformation
            End If
            SystemRolesSet
            If (errGatherWMIInformation) Then
                Select Case strExportFormat
                    Case "word"
                        PopulateWordfile
                    Case "xml"
                        PopulateXMLFile
                End Select
            End If
        End If
    End If

    Unfortunately the script is too long to be posted but can be found at
    http://sydiproject.com/download/and is called Server v.2.3. I have also contacted the author and made the suggestion I
    asked about.
    Jason
    I do not know which script you had in mind but the one I looked at had 1,600 lines of code. As you say, posting it here would be inappropriate. At the same time it is unrealistic to ask for help for such a large script. Asking the author is one option. The
    other option would be to identify the module you wish to modify, analyse it until you fully understand it, modify it so that you can run it in a stand-alone manner, then post your question here. You will probably find that you can answer the question yourself
    after analysing the code!

  • How to read input from handheld scanner on a keyboard port

    Hi everybody,
    i have an application that should read input from a scanner.
    If i use a jTextField to input scanned data it works fine.
    the problem is that i don't want to use any text component to input data into it.
    And if i set the jtextField not visible then the focus sustem doesnt work.
    I tried to read a buffered input stream from System.in but it doesnt work.
    If the scanner was installed on a serial port i could use javax.comm to monitor it.
    But unfortunately i must use the keyboard wedge thing...
    Do you have any ideas?
    Thank you in advance

    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))
    null

  • Get input from user and create a file and run a script in command line.

    Hi all,
    i'm trying to get a input from user and write it into a file named alpe.jacl
    To get multiple userinputs like address and jobtitle etc etc in the same single window.
    and the code will save the inputs in alpe.jacl one by one in a new line like
    nameis name
    address russia
    jobtitle dev
    So i coded like below.
    Though GUI for user input looks dull Its working fine.
    Now I want this code to perform one more task which is the GUI will contain one more button INSTALL with OK and CALCEL .
    and when after putting all inputs and creating the alpe.jacl file if someone clicks INSTALL it should start ./install.sh script present at the same folder which contains some unix shell commands.
    Here am not able to figure out how to go further...
    One more thing after all the inputs given when I am clicking on the OK button its closing the window instantly which i dont want. I want it like it should wait till someone press CANCEL to exit.
    Please some one help me.
    import javax.swing.*;
    import java.io.*;
    public class file
    public static void main(String []args)throws IOException
    FileWriter ryt=new FileWriter("alpe.jacl");
    BufferedWriter out=new BufferedWriter(ryt);
    JTextField wsName = new JTextField();
    JTextField sName = new JTextField();
    JTextField cName = new JTextField();
    Object[] message = {    "Web Server Name:", wsName,"Server Name:", sName,"Cluster Name:", cName};
    int answer = JOptionPane.showConfirmDialog(    null, message, "Enter values", JOptionPane.OK_CANCEL_OPTION);
    if (answer == JOptionPane.OK_OPTION){    String webserver = wsName.getText();
    String server = sName.getText();
    String cluster = cName.getText();
    out.write("set webservername " +wsName.getText()+"\n");
    out.write("set ClusterName " +cName.getText()+"\n");
    out.write("set ServerName " +sName.getText()+"\n");
    out.close();
    }}Thanks,
    Ricky

    Thanks a lot.
    Is there any way through which i can assign a scroll bar to my panel.
    As when the number of user inputs grows the GUI becomes more bulky and some of the fields are not showing up.
    Cheers
    _Ricky                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problems with clearing files from input type="file"

    I'm using &lsaquo;input type="file".. to upload files in some javascript.
    The page containing the &lsaquo;input type="file".. is not reloaded, so data on the &lsaquo;input type="file".. is not cleared.
    I've done this with form.reset() in IE, which cleares files from &lsaquo;input type="file".., but this doesn't work in Firefox. The next time I try to submit a file two files are submitted.
    I've even tried to replace the &lsaquo;input type="file".. to clear all data, but if i replace it with a &lsaquo;input type="file".. with same id, the files is still there from before.
    So my question is, how do I clear files selected
    ''(Edited to make the HTML code display properly -TonyE)''

    The firmware/file system on the iPhone is locked unless you jailbreak your iPhone. The sync function via a USB cable and iTunes is the only way to add or retreive data unless your phone is jailbroken (and that is limited to music, movies, contacts, pictures, etc)
    There are applications in App Store which will create a file storage system on your iPhone and allow your PC to access those folders/files via WiFi network (iFiles is one, there are others)
    iBluetooth requires your phone to be jailbroken.
    You can use a bluetooth connection from iPhone to PC to play music only thru the PC speakers without having a jailbroken phone.
    If all you want to do is transfer pictures, iTunes will do that.  It is already set up, just plug in the phone, and go to the photos tab and choose which picture app on the PC to transfer the photos into.  Then everytime you sync your phone, it pulls the new pictures off the camera roll.
    What was I thinking when I bought an HP ?
    Oh yea, I wasn't !
    IQ504 & IQ506

  • Getting input from a file(user I/O redirection)

    alright i am stuck on this program. Heres what i have to do
    I have to write a program usinbg arrays and looping. The program should get its input from a file (user I/O redirection). The first number in the file will be the number of numbers that follow to find the average of (maximum of 100) and print if they are above or below the average.
    I have called the program lab9.java. I already made a file called lab9.dat. This is whats inside the lab9.dat file.
    16
    15
    751
    24
    -56
    81
    227
    54
    99
    0
    102
    57
    58
    43
    245
    47
    73
    16 is how many numbers i am using.
    I am just stuck on how i should do this.
    I have to have the program look at those numbers from that file and then calculates the average and then it has to look at each individual number and print out if that number is above or below average. First off im getting an error when i put in java lab9 < lab9.dat. Am i messing up somewhere.
    I also have the loop:
    int numnums = cisio.GetInt();
    double nums[] = new double[numnums];
    int k;
    for(k=0;k<numnums;k++)
    nums[k]=cisio.GetInt();
    This is where im stuck. I need the program to get the average of the numbers and then compare each number to the average and say if its above or below average. I dont know how to do that. If someone can help me out that would be great.

    Yes, you would need three loops: one to get the input, other the calculate the sum, and a third to print out what numbers are less than and what more than the average. That is the easiest thing to do. It's possible to combine getting the input and calculating the sum in one single loop though. I'm glad you got it working! :)

Maybe you are looking for

  • IMac 21.5-inch, Late 2013 freezes and crashes

    I purchased this computer April 2014 and within 2 months it started freezing and then crashing. This happens randomly and has occurred approximately 12 - 15 time; Apple Care has been consulted five times - once which involved taking the computer back

  • Using external HD for backup with Macbook Pro

    Hi. I've got a Macbook Pro 4.1 with a 300 GB primary HD running OS X v10.5.8. Am about to connect a 2.0 TB external drive in an OWC mercury Elite Pro enclosure via an eSATA controller card. My partition scheme is as follows: 1st partition: 950 GB (fo

  • Error  while running the project

    This is my first project. I am able to make the project succesfully. But I run into warning and err messages. Any help is appreciated WARNING: J2EEComponent.logging NameNotFoundException: Unable to find/read deployment info for C:\oracleDevDay\JDevel

  • Report in background, how to avoid the header at every new page?

    Dear all,     I have a big report which gives time out, so I run it in background mode, the problem arises when I go to SP01 and download the output, it doesnt appear as a continuous list but as a bunch of pages with a header in each one, so it is a

  • Canopus ADVC110 Hi8 capture

    Hi, I have a G10 Canon HI8 camcorder. After reading on this forum about capturing analog tapes onto FCP, I purchased a Canopus ADVC110 for $260 + shipping. My FCP does see the picture and captures, but no color and no sound! Only in black and white a