Why do we use scanner

Please could someone tell me why do use we the following method
scanner scanner = new Scannerin java programing ?
I am new to java and I wana know about the usage and purposes of the above mentioned method.
Edited by: syedejaz on Aug 22, 2008 4:07 AM

Well, a general explanation of what a class does can always be found on its API:
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
or if you want more information you could search it in google... basically you use Scanner to read from some source (System.in, or a file, a string, etc).
If you're still in doubt you should probably ask a more specific question...
and the code you wrote should be:
Scanner scanner = new Scanner(...) // with uppercase S for the class name don't forget Java is case sensitive... and since you're new to Java, let me give you some advice: I strongly recommend you stick to Java conventions of writing classes with capital letter, variables in lowercase, etc.... it really helps a lot, though for some reason people who are new to java are sometimes too annoyed to follow conventions...
Hope this helps.

Similar Messages

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

  • Problem using Scanner

    Hi, I am relatively new to Java and I am trying to write a chat program using nonblocking I/O. I think that I have most of the networking part down but I am having a problem reading the input. I am using a Scanner to read the input coming from the socket channel, using a "~" as the delimiter. The first token is the name of the place where the incoming message is coming from (the server or another client). For some reason, I can't get the if statement that tests if the communication is coming from the server to return true.
    private void doRead(SocketChannel socket) {
         String readMessage;
         String clientName;
         Scanner scanner;
         readBuff = ByteBuffer.allocate(5000);
         try {
              socket.read(readBuff);
              readBuff.flip();
              readMessage = decoder.decode(readBuff).toString();
              System.out.println(readMessage);
              scanner = new Scanner(readMessage);
              scanner.useDelimiter("~");
              clientName = scanner.next();
              System.out.println(clientName);
              if (clientName.equals("Server")) {
                   System.out.println("Client name is: " + clientName);
                   serverComm(socket, scanner);
              else {
                   System.out.println("Client name is " + clientName + " instead of Server");
         catch (IOException e) {
    } // end doRead()The else statement at the end is just used to see if the if was returning true or not. If I manually set clientName = "Server" then the if statement returns true and the program continues on the right way, until the Scanner is used in the serverComm method, where the same problem occurs. I am sure that readMessage = "Server" because the System.out.println(readMessage) prints "Server" and the else statement prints "Client name is Server instead of Server". Does anyone have any idea what the problem could be? Thank you very much.

    System.out.println(readMessage);This prints out the exact message that I sent from the server (with the delimiter and no whitespace characters or anything). It just doesnt make any sense at all to me. I appreciate the help though thanks. Would there be another way of reading the input that didnt involve a Scanner and would work better? I need to be able to send messages between server/client that can be broken down into separate pieces. For example, the first piece tells the client where the message is coming from, the second will tell it what the message is about (whether it is an updated buddy list or something like that), and so on... Thats why I chose a Scanner. With a non-whitespace delimiter, a Scanner seems to be perfect for reading messages coded in a specific way like I need. They can include short, one-word segments (like "server" for example), or longer, multi-word messages. Is there anything else that could be used in this way, or should I keep trying with the Scanner? Thanks.

  • Why do I use my ipod as a camera when I lose precious photos even when I try to back up before an update! Selling my ipod at the first chance I get

    Why do I use my Ipod tiuch as a camera when lose precious photos of my granddaughter every time there is an operating system update? Even when I try to back up the ipod, I can't find the pics etc on my pc. It is very annoying and I am seriously considering selling my ipod because of this. No warning is given that photos will be lost. So very disappointed in aple, lost all my music last time, as well as my pics.

    Yes, using the windows photo capture application is how you get photos taken with the iPod onto your pc. You should store them there, and organize them in folders.
    Create one main photo folder. Inside that folder create additional folders to hold photos. Each folder will become an album on an iPod, iPad, or iPhone. Do not next any other folders inside the first album folder.
    Then start iTunes on your pc and connect your iPod. Select your iPod in itunes and select the Photos tab that will be ps enter. You will most likely have first find your main photos folder. Ten select to sync all photos from your pc or select only those albums you want to have on your iPod. The click on Apply or Sync. That will copy the photos to your iPod.
    If you should do something later to cause these albums to disappear from your iPod you can quickly copy them back by doing another sync.

  • Help with using Scanner Class

    Hi there - I'm a newbie to Java and may have posted this in the wrong forum previously.
    I am trying to modify a program so instead of using a BufferReader, a scanner class will be used. It is basically a program to read in a name and then display the variable in a line of text.
    Being new to Java and a weak programmer, I am getting in a mess with this and missing something somewhere. I don't think I'm using scanner in the correct way.
    Any help or pointers would be good. There are 2 programs of code being used. 'Sample' and 'Run Sample'
    Thanks in advance.
    Firstly, this program will run named 'Sample'
    <code>
    * Sample.java
    * Class description and usage here.
    * Created on 15 October 2006
    package internetics;
    * @author John
    * @version 1.2
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    // import com.ralph.*;
    public class Sample extends JFrame
    implements java.awt.event.ActionListener{
    private JButton jButton1; // this button is for pressing
    private JLabel jLabel1;
    private String name;
    /** Creates new object ChooseFile */
    public Sample() {
    initComponents();
    name = "";
    selectInput();
    public Sample(String name) {
    this();
    this.name = name;
    private void initComponents() {
    Color bright = Color.red;
    jButton1 = new JButton();
    jLabel1= new JLabel();
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    exitForm(evt);
    getContentPane().setLayout(new java.awt.GridLayout(2, 1));
    jButton1.setBackground(Color.white);
    jButton1.setFont(new Font("Verdana", 1, 12));
    jButton1.setForeground(bright);
    jButton1.setText("Click Me!");
    jButton1.addActionListener(this);
    jLabel1.setFont(new Font("Verdana", 1, 18));
    jLabel1.setText("05975575");
    jLabel1.setOpaque(true);
    getContentPane().add(jButton1);
    getContentPane().add(jLabel1);
    pack();
    public void actionPerformed(ActionEvent evt) {
    System.out.print("Talk to me " name " : ");
    try {
    jLabel1.setText(input.readLine());
    } catch (IOException ioe) {
    jLabel1.setText("Ow! You pushed my button");
    System.err.println("IO Error: " + ioe);
    /** Exit this Application */
    private void exitForm(WindowEvent evt) {
    System.exit(0);
    /** Initialise and Scan input Stream */
    private void selectInput() {
    input = new Scanner(new InputStreamReader(System.in));
    /**int i = sc.nextInt(); */
    /** Getter for name prompt */
    public String getName() {
    return name;
    /** Setter for name prompt */
    public void setName(String name) {
    this.name = name;
    * @param args the command line arguments
    public static void main(String args[]) {
    new Sample("John").show();
    </code>
    and this is the second program called 'RunSample will run.
    <code>
    class RunSample {
    public static void main(String args[]) {
    new internetics.Sample("John").show();
    </code>

    The compiler I'm using is showing errors in these areas of the code. I've read the tutorials and still can't get it. They syntax for the scanner must be in the wrong format??
    the input.readLine appears incorrect below.
      public void actionPerformed(ActionEvent evt) {
        System.out.print("Talk to me " +name+ " : ");
        try {
            jLabel1.setText(input.readLine());
        } catch (IOException ioe) {
          jLabel1.setText("Ow! You pushed my button");
          System.err.println("IO Error: " + ioe);
        }and also here...
    the input is showing errors
      /** Initialise and Scan input Stream */
      private void selectInput() {
        input = new Scanner(new InputStreamReader(System.in));
       /**int i = sc.nextInt(); */
      }Thanks

  • How do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full

    how do you remove back up data from the memory storage? my storage data states that i have over 80gb of data used for back ups and i dont know why as i use a external hard drive as a time machine .now my 250gb flash storage is nearly full.. HELP!

    When Time Machine backs up a portable Mac, some of the free space will be used to make local snapshots, which are backup copies of recently deleted files. The space occupied by local snapshots is reported as available by the Finder, and should be considered as such. In the Storage display of System Information, local snapshots are shown as  Backups. The snapshots are automatically deleted when they expire or when free space falls below a certain level. You ordinarily don't need to, and should not, delete local snapshots yourself. If you followed bad advice to disable local snapshots by running a shell command, you may have ended up with a lot of data in the Other category. Ask for instructions in that case.
    See this support article for some simple ways to free up storage space.

  • Error message when attempting to use scanner Canon model MP610

    Error message when attempting to use scanner Canon model MP610, any one have any fixes, suggestions?

    Safe Boot from the HD, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, empty trash, reboot when complete.
    For the other problems...
    See if the Disk is issuing any S.M.A.R.T errors in Disk Utility...
    http://support.apple.com/kb/PH7029
    Open Activity Monitor in Applications>Utilities, select All Processes & sort on CPU%, any indications there?
    How much RAM & free space do you have also, click on the Memory & Disk Usage Tabs.
    Open Console in Utilities & see if there are any clues or repeating messages when this happens.
    In the Memory tab of Activity Monitor, are there a lot of Pageouts?

  • Why do we use open URL in default browser function? What are the uses of it?

    Why do we use "open URL in default browser" function?  What are the uses of it?

    kdm7 wrote:
    Okay.
    So can we keep a web button to access the www.ni.com ? So that web site opens only when button pressed?
    P.S  I,m a newbie.
    Yes, you can also, e.g. include a help file or manual as html and open that in the browser.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • WHY CANT I USE FINAL CUT EXPRESS HD IN MY MACBOOK

    WHY CANT I USE FINAL CUT EXPRESS HD IN MY MACBOOK?

    hey there DavoMrMac,
    according to Apple's 'site:
    System Requirements
    Macintosh computer with 500MHz or faster PowerPC G4 or G5 (550MHz for PowerBook G4) or Intel Core Duo
    512MB RAM
    Display with 1024-by-768 (or higher) resolution
    An AGP or PCI Express graphics card compatible with Quartz Extreme or an Intel GMA integrated graphics processor in MacBook or Mac Mini
    Mac OS X 10.4.6 or later
    QuickTime 7.0.4 or later
    HDV features require 1GHz or faster processor and 1GB of RAM (2GB recommended)
    500MB disk space required for applications; additional 16GB of additional storage space for Soundtrack and LiveType content (can be installed on separate disks)
    DVD drive for software installation
    i've been running FCE HD 3.5 on my MacBook since i got it in November '06. runs okay for the few short SD projects(15:00) or less i've put together.

  • I cannot use a website I need to use, with Firefox 5.0. So, I need to uninstall and go back to 3.5 or 3.6. Please advise. Also, my control panel locks up since Windows Explorer has pbms. Which is why I am using Firefox instead. Thanks for any help!

    I cannot use a website I need to use, with Firefox 5.0. So, I need to uninstall and go back to 3.5 or 3.6. Please advise. Also, my control panel locks up since Windows Explorer has pbms. Which is why I am using Firefox instead. Thanks for any help!

    ''I figured it was going to be FAFSA causing your problem.''
    Install Portable Firefox 3.6.x to your hard drive for that one website. It won't affect your current Firefox installation at all. <br />
    http://portableapps.com/apps/internet/firefox_portable/localization#legacy36

  • Function module: why do we use FM and what is the purpose of using FM

    hi,
       Can any please explain. Why do we use FM?
                                           What is the purpose of using FM ?
                                           Where we are using FM and for what tables in R/3 ?
    I could be thankful to you if any one answer above questions.
    Arun

    Hi,
      We go for creating FM when there is a chance of using the same code in different reports in R/3.
    Suppose I have a requirement say, to display the Payer Name for every sale order.
    This is most common requirement in any project.
    You can create a FM say READ_CUSTOMER_NAME in SE37.
    Write a select statement from the table VBAP to fetch the Payer Name based on the Sales Order.
    Now you can activate the FM and it is ready to be used across all the reports in R/3.
    Need : To avoid redundant coding and to modularize the code.
    If you want to see the list of Standard FMs, got SE37 --> press F4 and you'll get all the SAP standard FMs.
    For customized FMs (User defined), type Z* or Y* and press F4.
    Hope this helps a bit !!!
    Regards,
    Balaji V

  • What is the significance of Marker interface? Why are we using, even though

    What is the significance of Marker interface? Why are we using, even though it has no method?

    Well, what's the significance of an interface? They can define a set of methods a class may implement but the class could equally well implement these methods without the interface so why having interfaces at all?
    The answer is that the most important aspect of an interface is that it constitutes a type (you can declare variables of it). And it's a type regardless of how many methods it defines, including none. So the reason for having a marker interface is that you're interested solely in the type aspect of interfaces.

  • Why do we use dunning for vendors

    Hi All...
    We create dunning for customer to send them reminders for payment....But why do we use dunning for vendors (in Vendor Master Data)??
    Txk,
    Umesh

    Hi,
    If you dun customers who are also vendors and want to clear the items, the dunning program lists both the overdue customer items and the overdue vendor items in the dunning proposal, and determines a joint balance.When you dun a customer who is also a vendor, only the master record information of the customer is relevant.The items can only be cleared if the same dunning procedure has been defined in the standard dunning area for both customer and vendor.
    Hope this helps you. let me know if you need anyother information.
    Rgds
    Manish
    ===========================================================================

  • Why do we use Allowed Operations in DML Process

    Hello,
    Why do we use Allowed Operations in DML Process ??
    Can you please clear this confusion:
    I am using apex 4.1. oracle 11g R2 SOE ...
    Using the Wizard, I created a Form and IR on Dept Table...
    In the form page:
    - Create Button
    The name is "CREATE"
    NO Database Action
    - DML Process
    Allowed Operations: nothing is checked
    This will insert a new row in the Dept table
    In the form page:
    - Create Button
    The name is "CREATE2"
    Database Action : insert
    - DML Process
    Allowed Operations: nothing is checked
    This will insert a new row in the Dept table
    So, What difference does it make if INSERT check box in Allowed Operations of DML Process is TICKED OR NOT ??
    Regards,
    Fateh

    kdm7 wrote:
    Okay.
    So can we keep a web button to access the www.ni.com ? So that web site opens only when button pressed?
    P.S  I,m a newbie.
    Yes, you can also, e.g. include a help file or manual as html and open that in the browser.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • Problem in reading data using scanner

    In a client - server application,Iam sending the data "~!Raam7krishna~!" continously to the server periodically.... In the server side,Iam using scanner to read the data with the delimiter ~!. Server should continously read the data from the client.so iam using infinite for loop to read the data from the inputstream using scanner..
    Problem is when a client send the data first time,i am received the data correctly in server side... At the second time of transmission of data from client to server,Server should not read any data .... but it does not throw any exception... but my client send the data to the server.... can anyone give me solution......
    Scanner scan=new Scanner(InputStream);
    for(;;)
    {     String data=scan.next
    }

    In a client - server application,Iam sending the data "~!Raam7krishna~!" continously to the server periodically.... In the server side,Iam using scanner to read the data with the delimiter ~!. Server should continously read the data from the client.so iam using infinite for loop to read the data from the inputstream using scanner..
    Problem is when a client send the data first time,i am received the data correctly in server side... At the second time of transmission of data from client to server,Server should not read any data .... but it does not throw any exception... but my client send the data to the server.... can anyone give me solution......
    Scanner scan=new Scanner(InputStream);
    for(;;)
    {     String data=scan.next
    }

Maybe you are looking for