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?

Similar Messages

  • Help using scanner.class someone help me

    ive been working on some code and the thing is i am stuck on how do i count the number of intergers between 1 and 5. for example lets say i inputted using a scanner.class 1,2,2,3,3,3 i want my program to then say how many 2's I have entered and and how many 3's i have entered. So basically if using a scanner.class (keyboard class) in java instead of hardwiring the numbers into an array how do i count out the number of intergers and display them in my output

    hardwiring the numbers into an array how do i count
    out the number of intergers and display them in my
    outputTry this.
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter numbers:");
            int i = 0;
            int count = 0;
            Map <Integer, Integer> intMap = new TreeMap <Integer, Integer>();
            while( true ) {
                i = sc.nextInt();
                if(i < 0 || i > 5) break;
                // Code to count the numbers entered.
                if(intMap.containsKey(new Integer(i))) {
                    count = intMap.get(new Integer(i)).intValue();
                    count++;
                } else {
                    count = 1;
                intMap.put(new Integer(i), new Integer(count));
            System.out.println(intMap);At forum users: Pardon me for all my variable names and poor coding style and lack of comments and...

  • 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

  • Need help using my class

    I recently made a class called time that let me store times and return their values. I needed to do this for another class called flight, which uses the class time to store times. My question is, how would i use my time class in the flight class. Whenever i try to make a new time.
    //i.e.
    Time x = new Time(0,0,0);It says that the class Flight cannot find the Time class within it. Does anyone know how i can use my time class inside of my Flight class without making Flight an extension of Time, if it is even possible. My Time code is posted below.
    public class Time{
        private int Hours;
        private int Minutes;
        private int Seconds;
       public Time(int newHours, int newMinutes, int newSeconds){
            setTime(newHours, newMinutes, newSeconds);
       public int getHours(){
            return Hours;
       public int getMinutes(){
           return Minutes;
       public int getSeconds(){
           return Seconds;
    public int setHours(int newHour){
        Hours = newHour;
        return Hours;
    public int setMinutes(int newMinute){
        Minutes = newMinute;
        return Minutes;
    public int setSeconds(int newSecond){
        Seconds = newSecond;
        return Seconds;
    public String toString(){
        int newHours = Hours;
        String type = "";
        String minuteZero = "";
        String secondZero = "";
        if(Hours>=0 && Hours<=11){
            type = " AM";
            if(Hours==0){
                newHours +=12;  
        if(Hours>=12 && Hours<=23){
            type = " PM";
            if(Hours>=13 && Hours<=23){
                newHours = newHours - 12;
        if(Minutes>=0 && Minutes<=9){
            minuteZero = "0";
        if(Seconds>=0 && Seconds<=9){
            secondZero = "0";
        return newHours + ":" + minuteZero + Minutes + ":" + secondZero + Seconds + type;
    public void setTime(int setHours, int setMinutes, int setSeconds){
        if(setHours>=0 && setHours<=23 && setMinutes>=0 && setMinutes<=59 && setSeconds>=0 && setSeconds<=59){
        setHours(setHours);
        setMinutes(setMinutes);
        setSeconds(setSeconds);
    public int secondsUntil(Time newTime){
        int totalSeconds;
        totalSeconds = ((this.Hours*3600)+(this.Minutes*60)+(this.Seconds))-((newTime.Hours*3600)+(newTime.Minutes*60)+(newTime.Seconds));
        return totalSeconds;
    }

    My Time class is in a folder called Time on my flash drive, and my Flight class is in a folder called Flight on my flash drive. And what do you mean how am i compiling them?

  • Using tie-classed to change name of file uploaded through FTP protocol srvr

    Hi,
    I'm trying to use the extendedPreAddItem (or Post) method in an S_TieFolder class to automatically change the name of a file (an S_PublicObject) when it enters a Folder (via an FTP put upload).
    I'm fiddling around with code like this:
    AttributeValue val = AttributeValue.newAttributeValue(newDocName);
    val.setName(Document.NAME_ATTRIBUTE);
    rightpo.setAttribute(val);
    But it does not work: in the FTP client the filename is indeed changed, but somewhere at lower levels the original filename is still being used...
    Any helpfull ideas would be appreciated.
    TOon

    I'm aware of this... My ftp-client (FTP-Voyager) will prompt me if I "put" a file that already exists in the remote folder, and ask me to go ahead and replace the file, or cancel the put-operation.
    However in this case the ftp-client sees file X' remotely and I'm putting file X, so it does not prompt me at all...
    Stopping and restarting the FTP-client (in case it caches remote folder-contents...) does not change the behaviour.
    Timewise this is what happens:
    1) I put file X.
    2) My S_TieFolder class (extendedPreAddItem) changes it's name into X'.
    3) The ftp-put successfully completes
    4) I refresh the remote folder contents and see the X' name instead of the original X name.
    5) I re-put X (and would now like to have it changed into file X'').
    6) Before my S_TieFolder code executes, something (I'm still suspecting the cm-sdk) deletes the X' file first... ==> the logfile does not show any communication with the ftp-client here now.
    7) Then my S_TieFolder code executes and changes the name into X''.
    8) I refresh the remote folder contents: File X' disappears, file X (just re-put) changes into X''.
    More testing has shown that I'm also not able to delete these files (whose names have been changed by S_TieFolder): 'file does not exist' error.
    I need to know:
    a) If changing the files name on-the-fly using S_Tie class is supported at all.
    and
    b) if so, what am I doing wrong?
    Thanks
    Toon

  • [Help] Using a class at the other class

    hi guys, i'm still new to java. So that i tried to learn by myself.
    i got 2 class: 'Person.java' and 'Ex1.java'
    basically, Person just a class for making an object of Person. and the main function is made at Ex1.java.
    my problem is: i made 2 Person objects (p1 and p2). then i tried to initialise them in 2 ways (using default constructor and user-defined constructor). Why when i print 'em (p1.print() and p2.print()), it printed p1 attributes only. I tried many ways to do this, but can't find the way out. pls help me...
    * Person.java *
    public class Person {
         // attributes
         private static String name;
         private static int age;
         // constructor
         public Person() {
              name = "";
              age = -1;
         public Person(String n, int a) {
              name = n;
              age = a;
         // mutator
         public static void setName( String n ) { name = n; }
         public static void setAge( int a) { age = a; }
         // other methods
         public static void print() {
              System.out.println( name + " (" + age + " years old)" );
    * Ex1.java *
    public class Ex1{
         private static Person p1;
         private static Person p2;
         public static void main(String args[]) {
              p1 = new Person();
              p2 = new Person("Jessica", 25);
              p1.setName("Antonio");
              p1.setAge(20);
              p1.print();
              p2.print();
    }

    Change
    public class Person {
         // attributes
         private static String name;
         private static int age;
    to
    public class Person {
         // attributes
         private String name;
         private int age;
    You're using incorrectly static for object attributes:)

  • Need help using 'visited' class with Colorbox

    Hi guys,
    I'm creating a site for a client that uses the Colorbox script for the store. When you click on a thumbnail of a product in the store, the browser uses Colorbox to display the external PHP page with the product information.
    This all works fine but what I would like to do is...
    When you click on a product thumbnail and it brings up the page (using Colorbox), when you close the Colorbox window and return to the thumbnails, I would like the padded background of the image to be a different color and not grey like the rest of them - so you can see which products you have looked at and which products you haven't.
    I've tried using...
    #productContainer img:visited {background-color:#0973ba;}
    ...but it didn't work.
    Click here for the link to the test site if that helps.
    Does anyone have any suggestions as to how I can achieve what I need to do?
    Thank you very much and I look forward to hearing from you.
    SM

    Did you try adding the pseudoclasses here?
    #content a {
        color: #0973BA; 
        text-decoration: none;

  • Need help using multiple classes in different folders.

    Hey everyone.
    Im trying to make a trading card game, in Java. Each card is going to be a class derived from a main card class (called card). The problem is that each card is going to be in a different folder based on the set and card number. (ex. card 001 from set 02 would be in "game/02/001/")
    I found this is a real good way to organize the game since there will be new cards all the time and players wont have all of them. Is it posible to call classes from different folders, and if it is how do I do it?
    -Thanks to anyone who answers

    The problem is that each card is going to be in a different folder based on the set and card number.Why don't you simply add two attributes to your Card class:
    cardNumber
    setNumber
    Or better, have a Set class with attribute:
    number
    and a Card class with two attributes:
    number
    set

  • Help using GROUP BY and COUNT

    The following SELECT statement will yield a report showing 3 days of the week and the number of "Msgs" that occurred for each day. How can I make it so that there's a 3rd column showing how many of those "Msgs" were "TxMsgs"
    (where IsTxMsg=1)
    DECLARE @Msgs TABLE (MsgId INT, DayOfWeek VARCHAR(5), IsTxMsg INT)
    INSERT INTO @Msgs VALUES (1, 'Mon', 1)
    INSERT INTO @Msgs VALUES (2, 'Mon', 0)
    INSERT INTO @Msgs VALUES (3, 'Tue', 1)
    INSERT INTO @Msgs VALUES (4, 'Tue', 0)
    INSERT INTO @Msgs VALUES (5, 'Wed', 1)
    INSERT INTO @Msgs VALUES (6, 'Wed', 0)
    INSERT INTO @Msgs VALUES (7, 'Wed', 0)
    SELECT DayOfWeek, COUNT(*) FROM @Msgs
    GROUP BY DayOfWeek
    ORDER BY DayOfWeek
    Thanks! 
    -- Curt

    DECLARE @Msgs TABLE (MsgId INT, DayOfWeek VARCHAR(5), IsTxMsg INT)
    INSERT INTO @Msgs VALUES (1, 'Mon', 1)
    INSERT INTO @Msgs VALUES (2, 'Mon', 0)
    INSERT INTO @Msgs VALUES (3, 'Tue', 1)
    INSERT INTO @Msgs VALUES (4, 'Tue', 0)
    INSERT INTO @Msgs VALUES (5, 'Wed', 1)
    INSERT INTO @Msgs VALUES (6, 'Wed', 0)
    INSERT INTO @Msgs VALUES (7, 'Wed', 0)
    SELECT DayOfWeek, COUNT(*) cnt1, SUM(Case when IsTxMsg=1 Then 1 Else 0 End) cnt2 FROM @Msgs
    GROUP BY DayOfWeek
    ORDER BY DayOfWeek

  • How different Web Services can use a class which parses an XML file

    I am using RAD6.1 for developing and deploying web services.As I am using 15 web Services which uses a common class which is used to parse an XML file.As this XML file should be parsed only once and should be used by all the web services.I have made this common class as Singleton but it works as singleton for only one webservice and for other web service again it is parsing the xml file.I want to parse this xml file only once and used by all the web services.In my case tis file is parsed 15 times for 15 web services, but it should be parse donly once and used by all 15 services.Please give me the solution.
    Thanks and Regards
    Sayeeduzzaman

    Hello,
    the 15 Webservices should have a static attribute which contains the xml:
    private static String xml;
    then initialise the xml like this:
    if (xml == null)
    xml = parseIt();
    else
    //do nothing, XML already initialised!
    }

  • Help!!! - Line Count in Text file

    I need to write a program for an assignment due next week. I should read between 30 and 70 lines of text from a text file. Each line contains an integral number of words. The program is required to display all the words on each line in revers order: "pass before they can enter" to read "enter can they before pass". I can reverse the words but the issue of 30 - 70 lines is a problem. I have the following code. What I'm I doing wrong???
    import java.io.*;
    import java.util.*;
    import java.util.StringTokenizer;
    public class LineReaderVector{
    public static void main(String args[])throws IOException{
    BufferedReader in=new BufferedReader(new FileReader("inpfile.txt"));
    LineNumberReader read=new LineNumberReader(new FileReader ("inpfile.txt"));
    String thisLine;
    int line=0;
    while((thisLine=in.readLine()) !=null){
         line=read.getLineNumber();
         StringTokenizer st = new StringTokenizer(thisLine);
         Vector v1=new Vector();
         while (st.hasMoreTokens()){
              String part= st.nextToken();
              v1.addElement(part);
         line++;
         System.out.println("\n");
         int size=v1.size()-1;
         for(int i=size; i>-1; i--){
         System.out.print(v1.elementAt(i).toString()+" ");
    }

    To read a file line by line this should do:
    try
      BufferedReader br = new BufferedReader(new FileReader("inpfile.txt"));
      String s = br.readLine();
      while (s != null)
        System.out.println(s);
        s = br.readLine();
      br.close();
    catch (IOException ex)
      ex.printStackTrace();
    ...

  • Using MessageDigest Class to check if a File was changed

    Hello,
    i want to write an application which times out at a Certain date.
    I would like to store this date in a seperate File and each time the apllication starts, it has to check first if the File has been manipulated or Changed.
    So, how can I remind what the original message digest is

    no idea

  • Scanner class

    i m very new to Java..i have Netbeans 5 to compile and run my Java programs.....when i try to run the following program
    import java.util.Scanner;
    class EchoLine {
    public static void main(String args[]) {
    Scanner myScanner = new Scanner(System.in);
    System.out.println(myScanner.nextLine());
    i get some errors saying...
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:11: cannot resolve symbol
    symbol : class Scanner
    location: package util
    import java.util.Scanner;
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    D:\Java\Projects\JavaApplication12\src\javaapplication12\Main.java:19: cannot resolve symbol
    symbol : class Scanner
    location: class javaapplication12.EchoLine
    Scanner myScanner = new Scanner(System.in);
    3 errors
    BUILD FAILED (total time: 0 seconds)
    i also get same kind of error while compiling it in JCreator.
    Can anybody help me in this matter to expalin this knid of behavoiur??
    Thanking in advance!!

    after downloading JDK 5 update 7 from
    http://java.sun.com/j2se/1.5.0/download.jsp
    i still cannot use Scanner class.....
    Java doesn't like you sorry. It's hopeless. We try and talk to Java and make her understand that she shouldn't be so flighty but you know... it just isn't going to work out. She hopes you can remain friends but she's just not interested in a more intimate relationship at this time.

  • Avoiding attributes when using transform class

    Hi,
    One more help pls!!!!!
    When I use transform class and create an XML file, it creates with attributes for the nodes.
    For exapmle,
    <MessageOwner type="type" name="name">
    How do I avoid this type and name attributes?????
    Thanx and Regards,
    Gayathri.

    create a XSL that will not output the attibutes.

  • Scanner class refuses to work

    Hi, I am having a really big pain in the butt issue with java, (ive tried using eclipse, jgrasp and bluej, all giving me same error)
    I am trying to read from a .dat file (which can easily be opened with wordpad or notepad to reveal contents)
    I am using scanner class
    Scanner key = new Scanner (new File ("file.dat"));
    no matter what i do, i keep getting the same error message FileNotFound Exception, i have gotten java to print out the directory it is searching for, i have put the file into that directory and i am still getting nothing....ive have been at this for two days now, and it is driving me nuts, nothing is making sense and i have asked everyone i know, they say that is the code you need to use to get it to read.
    P.S i have also tried
    File abc = new File ("file.dat");
    Scanner key = new Scanner (abc); same result
    I even got a little hopeful and tried just plain old
    Scanner key = new Scanner ("file.dat); and i get nada, same error, im wondering if anyone has seen this before.

    public static void populate(){
    Scanner keyb= new Scanner(new File("city.dat"));
    for(int j=0;j<=18;j++){
         int x = keyb.nextInt();
         String abr=keyb.next();
         int h = convert(abr);
         String name=keyb.next();
         int pop=keyb.nextInt();
         int alt = keyb.nextInt();
         city[x]=new cities(name,pop,alt);
         }Error Message: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
         Unhandled exception type FileNotFoundException
         Unhandled exception type FileNotFoundException
         at Main.populate(Main.java:45) Line 45 is Scanner keyb= new Scanner(new File("city.dat"));
         at Main.main(Main.java:34) Line 34 is a call to the populate method.

Maybe you are looking for