I need to do a simple program that counts the number of words and gives the total of the numbers in a text file. The program has to compute the sum and average of all the numbers. The average is the sum divided by the count.The file counts the numbers and words together. It just prints 34.
//CAT DOG BIRD FISH
//1 2 3 4 5
//TURTLE LIZARD SNAKE
//6 7 8 9 10
//FISH SHARK
//11 12 13 14 15
//SPIDER FLY GRASSHOPPER ANT SCORPION
//16 17 18 19 20
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class HomeWork8 {
public static void main(String[] args) throws IOException {
String words, numbers, message;
int numberWords = 0, countNumber = 0;
FileInputStream fis = new FileInputStream("/Users/ME/Documents/Words and Numbers.txt");
Scanner in = new Scanner(fis);
while (in.hasNext()) {
words = in.next();
numberWords++;
}
while (in.hasNext()) {
in.useDelimiter("");
numbers = in.next();
countNumber++;
}
in.close();
message = "The number of words read from the file was " + numberWords
+ "\nThe count of numbers read from the file was" + countNumber;
JOptionPane.showMessageDialog(null, message);
}
}
String pattern ="\\d";
String word="shdhdshk 46788 jikdjsk 9 dsd s90 dsds76";
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(word);
int count=0;
while (m.find()) {
count++;
}
System.out.println(count);
If you need to get the single number character count you can use \d . But If you are interested in whole number occurrence then you have to use \d+ instead of \d. Ex: 46788,9,90,76
You can even use regular expressions to filter the words and numbers as is shown below:
public static void main(String[] args) throws IOException {
String words, message;
int numberWords = 0, countNumber = 0;
FileInputStream fis = new FileInputStream("src/WordsandNumbers.txt");
Scanner in = new Scanner(fis);
String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Za-z].*";
while (in.hasNext()) {
words=in.next();
if (words.matches(alphaRegex)) {
numberWords++;
}
else if(words.matches(numRegex))
{
countNumber++;
}
}
in.close();
message = "The number of words read from the file was " + numberWords
+ "\nThe count of numbers read from the file was" + countNumber;
System.console().writer().println(message);
}
You need to have a single iteration through the content of the filerather than having 2 while loops.
Just before the second while (in.hasNext()) { you should reset the stream by adding the following code:
in = new Scanner(fis);
You should also revise your code for checking for numbers (I don't think you're checking for numbers anywhere).
Related
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
}
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 ints and decimal numbers are actually doubles.
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.
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();
}
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.");}
}
}
I'm trying to write a Java program to analyse each string in a string array from a text file and if the number parses to a double, the program prints the word previous to it and the word after. I can't seem to find out how to parse each element of a string array. Currently it will only print the first number and the following word but not the previous word. Hopefully somebody can help.
My text file is as follows:
Suppose 49 are slicing a cake to divide it between 5 people. I cut myself a big slice, consisting of 33.3 percent
of the whole cake. Now it is your turn to cut a slice of cake. Will you also cut a 33.3 percent slice? Or will you
be fairer and divide the remaining 66.6 percent of the cake into 4 even parts? How big a slice will you cut?
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class NumberSearch {
public static void main(String args[]) throws FileNotFoundException {
//creating File instance to reference text file in Java
// String filedirect = JOptionPane.showInputDialog(null, "Enter your file");
File text = new File("cakeQuestion2.txt");
//Creating Scanner instance to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
lineNumber++;
//Finding words
String[] sp = line.split(" +"); // "+" for multiple spaces
for (int i = 1; i < sp.length; i++)
{
{
double d = Double.parseDouble(sp[i]);
// System.out.println(+ d);
if (isDouble(sp[i]))
{
// have to check for ArrayIndexOutOfBoundsException
String surr = (i-2 > 0 ? " " + sp[i-2]+" " : "") +
sp[i] +
(i+1 < sp.length ? " "+sp[i+1] : "");
System.out.println(surr);
}
}}
}
}
public static boolean isDouble( String str )
{
try{
Double.parseDouble( str );
return true;
}
catch( Exception e ){
return false;
}}}
Mmmmm... your code seems too verbose and complex for the mission.
Check this snippet:
public static void main(String args[]) throws FileNotFoundException {
String line = "Suppose 49 are slicing a cake to divide it between 5 people. I cut myself a big slice, consisting of 33.3 percent of the whole cake. Now it is your turn to cut a slice of cake. Will you also cut a 33.3 percent slice? Or will you be fairer and divide the remaining 66.6 percent of the cake into 4 even parts? How big a slice will you cut?";
String[] sp = line.split(" +"); // "+" for multiple spaces
final String SPACE = " ";
// loop over the data
for (int i = 0; i < sp.length; i++) {
try {
// if exception is not raised, IS A DOUBLE!
Double.parseDouble(sp[i]);
// if is not first position print previous word (avoid negative index)
if (i > 0)
System.out.print(sp[i - 1] + SPACE);
// print number itself
System.out.print(sp[i] + SPACE);
// if is not last position print previous word (avoid IOOBE)
if (i < sp.length - 1)
System.out.print(sp[i + 1]);
// next line!
System.out.println();
} catch (NumberFormatException ex) {
// if is not a number, not our problem!
}
}
}
RESULT:
Suppose 49 are
between 5 people.
of 33.3 percent
a 33.3 percent
remaining 66.6 percent
into 4 even
I'm attempting to take an input from the user, then if it matches one of the existing files, read the file and put the words, letters, or number into an array. The "words", and "alphabet" files seem to work fine, but the "numbers" is giving me an issue. It finds the file, reads it, puts it into an array, and gives the summation of the numbers; however, the output of the array is every other number, as opposed to all numbers, like it should be doing.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class fileIO
{
public static void main (String[] args) throws FileNotFoundException
{
String filename;
System.out.println("Please enter name of file (alphabet,words,numbers): ");
Scanner input = new Scanner(System.in);
filename = input.nextLine();
if(filename.equals("numbers"))
{
int sum = 0;
Scanner reader = new Scanner(new File("/home/ninjew/workspace/FileIO/src/" + filename + ".txt"));
ArrayList<Integer> arr = new ArrayList<Integer>();
while(reader.hasNext())
{
arr.add(reader.nextInt());
sum = sum + reader.nextInt();
}
System.out.println(arr);
System.out.println("The summation is: " + sum);
reader.close();
}
else if(filename.equals("words") || filename.equals("alphabet"))
{
Scanner reader = new Scanner(new File("/home/ninjew/workspace/FileIO/src/" + filename + ".txt"));
// This is for words and letters within the file. Print words and letters.
ArrayList<String> arr = new ArrayList<String>();
while(reader.hasNext())
{
String line = reader.next();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNext()){
arr.add(scanner.next());
}
scanner.close();
}
System.out.println(arr);
reader.close();
}
}
}
In if(filename.equals("numbers")) you are doing two reads from your file in this block, which is why it is skipping numbers
while(reader.hasNext())
{
arr.add(reader.nextInt());
sum = sum + reader.nextInt();
}
Should be
while(reader.hasNext())
{
int val = reader.nextInt();
arr.add(val);
sum = sum + val;
}
Your numbers reader loop is adding first number to the array and the next number to the sum.
If input is 1 2 3 4 5 6, your array is [1, 3, 5] and your sum is 2 + 4 + 6 = 12.
You are reading next two integers in one go. Every time you call scanner.nextInt() it will read a next int. You need to store nextInt in a temp variable and use it in both the places.
while(reader.hasNext())
{
int next = reader.nextInt();
arr.add(next);
sum = sum + next;
}
So I'm pretty new to Java and I'm working on a code that is supposed to read a .txt file that the user inputs and then ask the user for a word to search for within the .txt file. I'm having trouble figuring out how to count the amount of times the inputted word shows up in the .txt file. Instead, the code I have is only counting the amount of lines the code shows up in. Can anyone help me figure out what to do to have my program count the amount of times the word shows up instead of the amount of lines the word shows up in? Thank you! Here's the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextSearch {
public static void main(String[] args) throws FileNotFoundException {
Scanner txt;
File file = null;
String Default = "/eng/home/tylorkun/workspace/09.1/src/Sample.txt";
try {
txt = new Scanner(System.in);
System.out.print("Please enter the text file name or type 'Default' for a default file. ");
file = new File(txt.nextLine());
txt = new Scanner(file);
while (txt.hasNextLine()) {
String line = txt.nextLine();
System.out.println(line);
}
txt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
txt = new Scanner(file);
Scanner in = new Scanner(System.in);
in.nextLine();
System.out.print("Please enter a string to search for. Please do not enter a string longer than 16 characters. ");
String wordInput = in.nextLine();
//If too long
if (wordInput.length() > 16) {
System.out.println("Please do not enter a string longer than 16 characters. Try again. ");
wordInput = in.nextLine();
}
//Search
int count = 0;
while (txt.hasNextLine()) //Should txt be in?
{
String line = txt.nextLine();
count++;
if (line.contains(wordInput)) //count > 0
{
System.out.println("'" + wordInput + "' was found " + count + " times in this document. ");
break;
}
//else
//{
// System.out.println("Word was not found. ");
//}
}
} catch (FileNotFoundException e) {
System.out.println("Word was not found. ");
}
} //main ends
} //TextSearch ends
Since the word doesn't have to be standalone, you can do an interesting for loop to count how many times your word appears in each line.
public static void main(String[] args) throws Exception {
String wordToSearch = "the";
String data = "the their father them therefore then";
int count = 0;
for (int index = data.indexOf(wordToSearch);
index != -1;
index = data.indexOf(wordToSearch, index + 1)) {
count++;
}
System.out.println(count);
}
Results:
6
So the searching segment of your code could look like:
//Search
int count = 0;
while (txt.hasNextLine())
{
String line = txt.nextLine();
for (int index = line.indexOf(wordInput);
index != -1;
index = line.indexOf(wordInput, index + 1)) {
count++;
}
}
System.out.println(count);
Your problem is that you are incrementing count on each line, regardless of whether the word is present. Also, you have no code to count multiple matches per line.
Instead, use a regex search to find the matches, and increment count for each match found:
//Search
int count = 0;
Pattern = Pattern.compile(wordInput, Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
while(txt.hasNextLine()){
Matcher m = pattern.matcher(txt.nextLine());
// Loop through all matches
while (m.find()) {
count++;
}
}
NOTE: Not sure what you are using this for, but if you just need the functionality you can combine the grep and wc (wordcount) command-line utilities. See this SO Answer for how to do that.
i have an input that consists of any 2 numbers on a single line and there can be an unlimited number of lines, ex.
30 60
81 22
38 18
I want to split each line into 2 tokens, first token is the number on the left and the second token is the number on the right. What should i do? All help is appreciated.
With Scanner and System.in:
public class SplitTest
{
public static void main (final String[] args)
{
try (Scanner in = new Scanner (System.in))
{
while (in.hasNext ())
{
System.out.println ("Part 1: " + in.nextDouble ());
if (in.hasNext ())
System.out.println ("Part 2: " + in.nextDouble ());
}
}
catch (final Throwable t)
{
t.printStackTrace ();
}
}
}
If the input is always setup like that, take a look into String.split()
// For just splitting into two strings separated by whitespace
String numString = "30 60";
String[] split = numString.split("\\s+");
// For converting the strings to integers
int[] splitInt = new int[split.length];
for(int i = 0; i < split.length; i++)
splitInt[i] = Integer.parseInt(split[i]);