How to store the string scanned by the scanner class

try {
       Scanner scanner = new Scanner(new File("D:\\textfile.txt"));
       String sb;
       scanner.useDelimiter("\\t");
       while (scanner.hasNext()== true)
       System.out.println(scanner.next());
          scanner.close();
       catch (FileNotFoundException e)
       e.printStackTrace();
     }Output i get is
Hi
how
are
you
I would like to store each word in a different string.What changes do i need to make in the code given above?

warnerja wrote:
But what if the text file contains "Trolls are annoying"? Then your solution fails.No warnerjav - this is not so.
Solution still nearly works but assigns "Trolls" to variable 'hi', "are" to variable 'how' and "annoying" to variable 'are'.
But you are right to point out that we must now trap exception for call to
String you = scanner.next();in order to fix the javs for the sentence you suggest because there will be no more words in the scanner darkly.
Best thankyou for you pointing this out to me for the hlep of us all learning more about the Javs we love.
Best greetings,
Bob Gateaux.

Similar Messages

  • How to use the scanner class to ask for a character?

    Hey guys, this is my assignment:
    Ask the user for a single letter and a sentence, and print out the
    number of times that letter shows up in the sentence.
    Please tell me how to scan for a character. I tried this:
    import java.util.Scanner;
    public class Frequencies
        public static final void main(String[] args)
            Scanner scanner = new Scanner(System.in);
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter a sentence");
            String x = scanner.next();
            System.out.println("Enter a letter to look for");
            String y = scan.next();
            char z = y.charAt(0);
            int chara = 0;
            for(int i = 0; i<x.length(); i++){
                    if(z==y.charAt(i)){
                            chara = chara++;
            System.out.println("There are " + chara + " " + z + "s in the sentence");
    }and got the error after Running (not compiling):
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)I thought this meant that I was asking for the character in postition 1 of string y, but in my code I wrote position 0
    when I tried inserting words in the character place (just to see what happened, not expecting functionallity, I got
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: [NUMBER OF CHARACTERS]
            at java.lang.String.charAt(String.java:687)
            at Frequencies.main(Frequencies.java:16)Please help.
    The assignment isn't due nor graded, this is just killing me lol.
    Thanks in advance
    Edited by: Sevan on Oct 18, 2008 4:40 PM

    jverd wrote:
    Skydev2u wrote:
    I've used this method for a while now and it gets the job done.
    import java.util.Scanner;
    public class ReadInput {
    public static void main(String[] args) {
    Scanner UserInput = new Scanner(System.in);
    char letter = UserInput.findWithinHorizon(".", 0).charAt(0);
    I know you're trying to help, but this isn't really doing it. It does nothing to address the source of the OP's problem. The way he's doing it now is almost right. He just needs to do a tiny bit of detective work to fix a small bug. Tossing off a totally different approach, with no explanation, is not particularly helpful.Your right jverd I skimmed the OP's problem too quick;y and in tern didn't understand it fully. After reading the post thoroughly I saw that the problem can be solved by taking the sentence the user enters and then converting it into a array of characters. Then searching for the specific letter the user enters is achieved by comparing it to each individual element of the char array. Then incrementing a counter variable each time a match is made. I hope this example code solve your problem.
    * @author skydev
    import java.util.Scanner;
    public class SentenceReader {
        public static void main(String[] args) {
            int counter = 0; //Amount of time the letter appears in the sentence
            char letter;    //Letter the user search for
            char[] sentenceArray; //char array to hold the elements of the string the user inputs
            String sentence; //sentence the user inputs
            Scanner UserInput = new Scanner(System.in);
            System.out.println("Please enter a sentence! ");
            sentence = UserInput.nextLine();
            sentenceArray = sentence.toCharArray(); //splits up the users sentence into a array of char
            System.out.println("Please enter a letter to search for ");
            letter = UserInput.findWithinHorizon(".", 0).charAt(0);
             for(int i = 0; i < sentence.length(); i++){
                    if(letter == sentenceArray){ //search to see if the letter of interest equals to each char (letter) of the array
    counter++; //increments the amount of time the letter appears, set to 0 by default
    System.out.println("The letter appeared " + counter + " times in the sentence"); //Displays the result :) I love programming

  • How to store the output of a analog to digital converter into an 2D array

    Hi
    I am doing my M.Tech Thesis in Image reconstruction and I am using labview for simulation and I want to know how to store the output of a analog to digital converter into an 2D labview array.

    nitinkajay wrote:
    I want to know how to store the output of a analog to digital converter into an 2D labview array.
    How exactly are you performing 'Analog to Digital'???
    Grabbing image using camera OR performing data acquisition using DAQ card OR some other way????
    I am not allergic to Kudos, in fact I love Kudos.
     Make your LabVIEW experience more CONVENIENT.

  • How to store the images in Oracle?

    Hi,
    I am a new developer, trying to find out how to store the images in Oracle. Is there anyway that I can store the images in Oracle and insert them into my html file?
    Thanks!
    Sarah

    There is a simple image example available from OTN.
    From the OTN main page, go to Products --> interMedia --> Sample Code. The name of the example is "Load rich media content with a browser."
    This example loads and retrieves an image from an Oracle8i database through a web page using the Oracle interMedia Web Agent.
    Hope this helps.
    null

  • How to store the images in tables

    how to store the images in tables .what is the use of "clob ,blob"

    Using with the CLOB or BLOB, you can store the images in the table.
    Srini C

  • How to store the flat file data into custom table?

    Hi,
    Iam working on inbound interface.Can any one tell me how to store the flat file data into custom table?what is the procedure?
    Regards,
    Sujan

    Hie
    u can use function
    F4_FILENAME
    to pick the file from front-end or location.
    then use function
    WS_UPLOAD
    to upload into
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'   "Function to pick file
        EXPORTING
          field_name = 'p_file'     "file
        IMPORTING
          file_name  = p_file.     "file
      CALL FUNCTION 'WS_UPLOAD'
       EXPORTING
         filename                       = p_file1
        TABLES
          data_tab                      = it_line
    *then loop at it_line splitting it into the fields of your custom table.
    loop at it_line.
              split itline at ',' into
              itab-name
              itab-surname.
    endloop.
    then u can insert the values into yo table from the itab work area.
    regards
    Isaac Prince

  • How to store the zip file in oracle table?

    hi,
    How to store the zip file in oracle table ?
    is it possible to unzip and read the file ?
    Thanks
    Rangan S

    SQL> DESC BLOB_TABLE;
    Name Type Nullable Default Comments
    A INTEGER Y
    B BLOB Y
    SQL> INSERT INTO BLOB_TABLE VALUES(5,BLOB('MWDIR_TST','TEST.ZIP'));
    INSERT INTO BLOB_TABLE VALUES(5,BLOB('MWDIR_TST','TEST.ZIP'))
    ORA-00904: "BLOB": invalid identifier
    SQL> INSERT INTO BLOB_TABLE VALUES(5,('MWDIR_TST','TEST.ZIP'));
    INSERT INTO BLOB_TABLE VALUES(5,('MWDIR_TST','TEST.ZIP'))
    ORA-00907: missing right parenthesis
    SQL> INSERT INTO BLOB_TABLE VALUES(5,('\\MWDIR_TST\TEST.ZIP'));
    INSERT INTO BLOB_TABLE VALUES(5,('\\MWDIR_TST\TEST.ZIP'))
    ORA-01465: invalid hex number
    SQL> INSERT INTO BLOB_TABLE VALUES(5,('\\MWDIR_TST\TEST.ZIP'));

  • Chat App: how to store the user IP in database when they login.

    hello,
    i am working on chat application. first i made a login GUI form. after login when we run the Chat program, it ask the ip address of the server to whom it want to connect. and if u enter the ip address, it will connect to the server and chat will begin, thats working perfect.
    but i want to show the list of users who r logged on and when i simply click on the user name, chat should begin.
    i have the logic that when any user log in, then its IP address will be stored in the database. this ip address will shown to the online users.
    but i dont know how to store the user information in database when they log in. can any body suggest me wht lines of code i should use.
    thanks.

    palakk wrote:
    i have the logic that when any user log in, then its IP address will be stored in the database. Bad approach. That will only work if this chat is only intended for use on a LAN. If it's used on the internet, then your users' IP addresses will almost always be either a) those of their routers, or b) private IP addresses, and in both cases, multiple users can have the same IP address.
    this ip address will shown to the online users. Why would you want to do that? I want to chat with "Bill", not with "1.2.3.4".
    but i dont know how to store the user information in database when they log in.Do the same thing that you're currently doing to store the IP address, but with the other information you want to store.
    can any body suggest me wht lines of code i should use. This is not a code writing service.

  • How to store the datas in a .txt file in to a JTable in Java Swing

    Hi sir,
    Here i want to know how to store the data's of a .txt file
    in to a JTable in java swing.
    Where here the .txt file like for eg,spooler.txt is in the server and from there it will come to my client machine what i have to do is to take that .txt file and store the datas of the .txt file
    in a JTable.This is what i want.So pls. do help and provide the code as well.I will be thankful.Since i am involved in a project which involves this it is Urgent.
    Thanx,
    m.ananthu

    You can't just display data from a text file in a JTable. You have you understand the structure of the data so that you can parse the data and create a table model that can access the data in a row/column format. Here is an example of a simple program that does this:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=315172

  • How to store the 2d graphics with matrix?

    Hello everybody,
    I met a problem,and the question is "How to store the 2d graphics with matrix?".
    who can help me?
    Best wishes to all of you.
    James Wei.

    Hello,
    It is possible to store the time in user variables. How to export those variables depends on the deployment of the file.
    Some information about showing elapsed time can perhaps give you a start:
    Display Time Information
    Lilybiri

  • How to store multiline string literal in to java bean shell variable

    Hello Experts
    How to store multiline string literals in java bean shell like we use triple quote for jython variable
    Using Jython
    str=""" helllo
    welcome to my world"""
    above syntax is working but not for java bean shell like below
    String str=""" hello
    welcome to my world""";
    So how to do this in java bean shell. I came to this scenario while storing logs to a variable. I believe there is no solution for storing multiline strings to java bean shell variable.
    <@
    String str="<%=odiRef.getPrevStepLog("MESSAGE")%>";
    @>
    Any suggestion will be highly appreciated.
    Thank You.

    maddythehunk wrote:
    Im trying this but its not working...
    while(billingQueryParamsItr.hasNext()) {
         billingQueryParam = (BillingQueryParam) billingQueryParamsItr.next();
         System.out.println("****** Param Name-->"+billingQueryParam.getParamName());
         String[0] name = billingQueryParam.getParamName(); // giving error ; expected
         //billingItemActionForm.setParamName(billingQueryParam.getParamName());
    Declare the array outside of the loop. Fill the array as you iterate. And stop putting your error messages inside of comments in the code.

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • Where to store the servlet classes

    can anyone tell me where to store the servlet classes(inside a package)in oracle9iAS used with oracle8i database ?
    Also how to deploy an ejb in oracle9iAS. should we have to use oracle8i deployment guide or any other procedure??
    thanks in advance

    Copy Servlet in DefaultWebApp/Web-Inf/classes directory.
              Configure Servlet in web.xml deployment descriptor.
              <servlet>
              <servlet-name></servlet-name>
              <servlet-class></servlet-class>
              </servlet>
              <servlet>
              <servlet-name></servlet-name>
              <servlet-class></servlet-class>
              </servlet>
              <servlet-mapping>
              <servlet-name></servlet-name>
              <url-pattern></url-pattern>
              </servlet-mapping>
              hiren dossani wrote:
              > If, I store the class files for servlets under WEB-INF/classes folder,
              > i get file not found exception while using WL 6.1 sp2. But, if i store
              > the class file under DefaultWebApp folder, it works fine.
              > Any help about where to store the class files for servlets would be
              > great help.
              >
              > Thanks.
              >
              > --
              > hiren
              

  • How to use the implementation class in propetty pallete

    Hi,
    I am using forms 10g....I have to insert horizontal scroll bar in text item..
    I have only class files instead of jar files ...how cani place the class file instead of jar file...
    How to use the implementation class in property palette to display the PJC
    Thanks,
    Ansaf.

    The Implementation Class must reflect the full name of the class. For instance, if the full class name is : xx.yyy.zz.class_name, then put this in the Implementation Class property of the corresponding item.
    Also, the class must be stored in the equivalent directory structure, so that, in my example: <DEV_HOME>/forms/java/xx/yyy/zz
    Francois

  • How to get the object class field value in CDHDR table for vendor

    hi
    how to get the object class field value in CDHDR table for vendor

    Try KRED/KRED_N as object class in CDHDR for Vendor.

  • How to find the Feeder class behind Incident creation in SAP EHS?

    I have a requirement where i need to change the message text after clicking "Send" button while creating Incident.
    How to find the feeder class and method which is called behind "Send" button ?
    Thanks,
    Vimal

    I dont have such.. but you can set  external debug point in function module POWL_QUERY_REFRESH
    * get the result object type from the feeder
       lr_feeder->get_object_definition(
          EXPORTING
           i_selcrit_values = lt_crit_para  " selcrit dependent object def.
           i_langu = l_langu                                     "nt_1673495
           i_type  = i_query_data-type
          IMPORTING
           e_object_def = lr_object_def
    In I_QUERY_DATA-TYPE you can see name of POWL ID.
    Find it in transaction POWL_TYPE and you get name of feader class!

Maybe you are looking for

  • New iMac: Thunderbird works OK but Apple Mail cannot receive

    Just bought iMac in July 2010. Thunderbird email sends/receives fine, but Apple Mail v4.3 does not receive emails. Apple mail will send, which is received by Thunderbird. Incoming Mail Server settings good, and default mail reader is Apple Mail. Help

  • How do I set up iMessage on my Mac?

    I was trying to use iMessage from my MacBook, but I can't figure out how to set it up. I tried doing it through iChat, but it doesn't give me the option to sign in w/ my Apple ID & password.

  • Ping blocks when looking up reverse dns PTR/RR

    Hi! If someone could shed some light on this behaviour, it would really make my day! When using ping -s to ping an ip address that doesn't have a PTR RR, ping will timeout until dns timeout. This would be fine, except that when the replys do show, it

  • Group bar graph

    Hello Is there a simple method to display data on bar graph where various Y-values for given X are staying like neighbors but not like one Y above another Y (I've seen on http://forums.ni.com/ni/board/message?board.id=170​&message.id=315293&query.id=

  • Does anyone knows how itunes keep ur iphone back up record?

    I have a problem for my iPhone back up. three weeks ago, I borrow my friend's MacBook to back up my iPhone 5, but I didn't delete anything when I retune his MacBook. now he sold his MacBook, how can I protect my information in that case? somebody hel