简体   繁体   中英

How to count how many natural and decimal numbers there are in a text file

I want to count how many words, line, characters, and how many natural number and how many decimal numbers there are. The words, lines and character is easy, but how many natural and decimal number is the hard part, and I can't figure it out because I can't use hasNextInt , because there are words in the file that we need to read from.

The problem:

Write a java code that Print out some information about a document and put them in a file called Counts.txt.
✓ number of Rows
✓ number of Words (in general)
✓ number of Characters
✓ number of Natural numbers
✓ number of decimal numbers

The source file:

1   2   3   4   5   6   7   8   9   10  
2   4   6   8   10  12  14  16  18  20  
3   6   9   12  15  18  21  24  27  30  
4   8   12  16  20  24  28  32  36  40  
5   10  15  20  25  30  35  40  45  50  
6   12  18  24  30  36  42  48  54  60  
7   14  21  28  35  42  49  56  63  70  
8   16  24  32  40  48  56  64  72  80  
9   18  27  36  45  54  63  72  81  90  
10  20  30  40  50  60  70  80  90  100 

The sum of the second diagonal is: 220

The sum of the odd elements from the 0th line is: 25
The sum of the odd elements from the 1th line is: 110
The sum of the odd elements from the 2th line is: 75
The sum of the odd elements from the 3th line is: 220
The sum of the odd elements from the 4th line is: 125
The sum of the odd elements from the 5th line is: 330
The sum of the odd elements from the 6th line is: 175
The sum of the odd elements from the 7th line is: 440
The sum of the odd elements from the 8th line is: 225
The sum of the odd elements from the 9th line is: 550

16.2 to 23.5    change = 7.300000000000001
23.5 to 19.1    change = -4.399999999999999
19.1 to 7.4 change = -11.700000000000001
7.4 to 22.8 change = 15.4
22.8 to 18.5    change = -4.300000000000001
18.5 to -1.8    change = -20.3
-1.8 to 14.9    change = 16.7

The Highest Temperature is: 23.5
The Lowest Temperature is: -1.8

My code so far:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class Exercice4 {

   public static void main(String[] args) {
      // n3arif counters
      int countline = 0;
      int countchar = 0;
      int countword = 0;
      int countnum = 0;
      int countdec = 0;

      File file = new File("Document.txt");

      // count of lines
      try {
         Scanner input = new Scanner(file);
         while (input.hasNextLine()) {
            input.nextLine();
            countline++;
         }
         System.out.println("the count of Lines is:\t\t" + countline);
         input.close();
      } catch (Exception e) {
         System.err.println("File not found");
      }

      // count of characters
      try {
         Scanner input = new Scanner(file);
         while (input.hasNextLine()) {
            String str = input.nextLine();
            for (int i = 0; i < str.length(); i++) {
               if(str.charAt(i) != ' '){
                  countchar++;
               }
            }
         }
         System.out.println("the count of Characters is:\t" + countchar);
         input.close();
      } catch (Exception e) {
         System.err.println("File not found");
      }

      // count of words
      try {
         Scanner input = new Scanner(file);
         while (input.hasNextLine()) {
            input.next();
            countword++;
         }
         System.out.println("the count of Words is:\t\t" + countword);
         input.close();
      } catch (Exception e) {
         System.err.println("File not found for count Words");
      }
      /*
      // count of numbers
      try {
         Scanner input = new Scanner(file);
         while (input.hasNextLine()) {
            input.next();
                  countnum++;
         }
         System.out.println("the count of numbers is:\t" + countnum);
         input.close();
      } catch (Exception e) {
         System.err.println("File not found");
      }*/
/*
      // count of decimals
      try {
         Scanner input = new Scanner(file);
         while (input.hasNextLine()) {
            input.nextDouble();
            countdec++;
         }
         System.out.println("the count of Decimal is:\t" + countdec);
      } catch (Exception e) {
         System.err.println("File not found");
      }
*/
      // Print to a counts.txt
      try {
         PrintStream output = new PrintStream(new File("Counts.txt"));
         output.println("Total Number of Lines:\t\t" + countline);
         output.println("the count of Characters is:\t" + countchar);
         output.println("the count of Words is:\t\t" + countword);
         output.println("the count of numbers is:\t" + countnum);
         output.println("the count of Decimal is:\t" + countdec);
      } catch (FileNotFoundException e) {
         System.err.println("File not found");
      }
   }
}

You can determine if an input is an integer or a double:

String str = input.next();
    float number  = Float.parseFloat(str);
    if(number % 1 == 0){
        //is an integer
    } else {
        //is not an integer
    }

Scanner next() will return String variable. By getting the variable, you can parse it to Double or Integer. If it can be parsed into an integer, then it is a natural number, or if the variable can be parsed into a double, then it is a decimal number.

You can modify your code by adding this:

String word = input.next();
try {
    int number = Integer.parseInt(word);
    countNumber++;
} catch (NumberFormatException ex){
    ex.printStackTrace();
}

and

String word = input.next();
try {
    double number = Double.parseDouble(word);
    countDouble++;
} catch (NumberFormatException ex){
    ex.printStackTrace();
}

Rather than scan the entire file separately for each different thing that you need to count, you can scan the file once only and update all the counts. See below code. Explanations after the code.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Counters {
    private static void display(int count, String unit) {
        String plural = count == 1 ? "" : "s";
        String verb = count == 1 ? "is" : "are";
        System.out.printf("There %s %d %s%s.%n", verb, count, unit, plural);
    }

    private static boolean isDecimalNumber(String word) {
        boolean isDouble = false;
        try {
            Double.parseDouble(word);
            isDouble = true;
        }
        catch (NumberFormatException x) {
            // Ignore.
        }
        return isDouble;
    }

    private static boolean isNaturalNumber(String word) {
        boolean isInt = false;
        try {
            Integer.parseInt(word);
            isInt = true;
        }
        catch (NumberFormatException x) {
            // Ignore.
        }
        return isInt;
    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("srctexts.txt"))) {
            int chars = 0;
            int lines = 0;
            int wordCount = 0;
            int naturalNumbers = 0;
            int decimals = 0;
            String line;
            String[] words;
            while (scanner.hasNextLine()) {
                line = scanner.nextLine().replace(':', ' ').replace('=', ' ').trim();
                lines++;
                chars += line.length();
                words = line.split("\\s+");
                if (words.length > 0  &&  words[0].length() > 0) {
                    for (String word : words) {
                        wordCount++;
                        if (isNaturalNumber(word)) {
                            naturalNumbers++;
                        }
                        else if (isDecimalNumber(word)) {
                            decimals++;
                        }
                    }
                }
            }
            display(lines, "line");
            display(chars, "character");
            display(wordCount, "word");
            display(naturalNumbers, "natural number");
            display(decimals, "decimal number");
        }
        catch (FileNotFoundException xFileNotfound) {
            xFileNotfound.printStackTrace();
        }
    }
}
  • I wrote a file named srctexts.txt that contains your sample data.
  • The file contains colon character ( : ) and equals sign ( = ) which I assumed are not considered words but are considered characters.
  • Words are delimited by spaces. That's why I replaced the colon characters and equals signs with spaces.
  • Note that method split() creates a single element array that contains an empty string for an empty line. Hence empty lines are counted as lines but not added to the word count.
  • I assumed that natural numbers are actually int s and decimal numbers are actually double s.

Here is the output I get when I run the above code:

There are 34 lines.
There are 1262 characters.
There are 273 words.
There are 111 natural numbers.
There are 23 decimal numbers.
import java.io .*; // for File
import java.util .*; // for Scanner
public class ex03_ {

    public static void main(String[] args) {
        Scanner input;
        PrintStream output;
        try {
            output = new PrintStream (new File ("Countsssssssssss.txt"));
            input = new Scanner( new File("Document.txt"));
            String myLine;
            int CountLines=0, CountChar=0, CountWords=0,CountNumeral=0,CountDecimal=0;
            while(input.hasNextLine()){
                myLine=input.nextLine();
                CountLines+=1;
                CountChar+=myLine.length();
                if(!myLine.isEmpty())
                    CountWords++;
                for(int i=0;i<myLine.length();++i)
                  {
                    
                   if(myLine.charAt(i)==' ' || myLine.charAt(i)=='\t')
                       CountWords++;
                  }
                
                
            }
            
            //input.close();
            input = new Scanner( new File("Document.txt"));
            while(input.hasNextLine()){
                
                if(input.hasNextInt())
                    CountNumeral++;
                if(input.hasNextDouble())
                    CountDecimal++;
                myLine=input.next();//next string or number ...
                                    //When we reach the end of line it go to the next line
        }
            String data;
            data= "the count of Lines is:       "+CountLines;
            System.out.println(data);
            output.print(data);
            data= "\nthe count of Characters is:    "+CountChar;
            System.out.println(data);
            output.print(data);
            data = "\nthe count of Words is:        "+CountWords;
            System.out.println(data);
            output.print(data);
            data = "\nthe count of numbers is:  "+CountNumeral;
            System.out.println(data);
            output.print(data);
            data = "\nthe count of Decimal is:  "+(CountDecimal-CountNumeral);
            System.out.println(data);
            output.print(data);
            
        }catch (FileNotFoundException e ){
            System.out.println ("File not found.");}
        

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM