Counting number of words start with UpperCase letter in strings, java - java

I have tried to write a Java program that count number of words start with UpperCase in each line separately, like in a txt file, and print the line number next to the number of words start with UpperCase in that line.
I have only come out with how to count the number for a single line using:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine();
char ch;
int count = 0;
for (int i = 1; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
}
}
System.out.println("total number of words start with capital letters are :" + count);
I tried to do it on the way I want, but it keep showing me "File is empty":
FileInputStream in = new FileInputStream("io-02.txt");
Scanner inScanner = new Scanner(in);
FileOutputStream out = new FileOutputStream("io-02-out.txt");
PrintWriter pwr = new PrintWriter(out);
int linenumb=0;
String s="";
char c;
int count = 0;
inScanner.useDelimiter("");
for (int i = 1; i < s.length(); i++) {
s = " " + inScanner.nextLine().trim();
c = s.charAt(i);
if (Character.isUpperCase(c) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
} else if(s == "\n"){
if(linenumb == 0)
pwr.printf("%6s%35s%n", "Line#", "Number of Uppercase characters");
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
count = 0;
}
}
if(linenumb == 0)
System.out.println("Error: The input file is empty");
else{
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
System.out.println("The file output.txt has been created . . . ");
}
Please help.

Java 8 solution:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
final public class UppercaseWordCounter { // https://stackoverflow.com/questions/49193228/counting-number-of-words-start-with-uppercase-letter-in-strings-java
final private static File FILE_WORDS = new File("io-02.txt");
final private static File FILE_RESULTS = new File("io-02-out.txt");
public static void main(final String[] args) {
if (!FILE_WORDS.exists()) {
System.err.println("Input file does not exist: " + FILE_WORDS);
System.exit(1);
}
if (FILE_RESULTS.exists()) {
if (!FILE_RESULTS.delete()) {
System.err.println("Intended output file exists already and can't be deleted: " + FILE_RESULTS);
System.exit(2);
}
}
try (final BufferedReader br = Files.newBufferedReader(FILE_WORDS.toPath(), StandardCharsets.UTF_8);
final BufferedWriter bw = Files.newBufferedWriter(FILE_RESULTS.toPath(), StandardCharsets.UTF_8)) {
int lineCounter = 1;
String line;
while ((line = br.readLine()) != null) {
final int upperCaseWordsInThisLine = countUpperCaseWords(line);
bw.write("Line " + lineCounter + " has " + upperCaseWordsInThisLine + " upper case word" + (upperCaseWordsInThisLine == 1 ? "" : "s") + ".\n");
lineCounter++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private static int countUpperCaseWords(final String line) {
int ret = 0;
final int length = line.length();
boolean newWord = true;
for (int i = 0; i < length; i++) {
final char c = line.charAt(i);
if (" .,;/".indexOf(c) >= 0) {
newWord = true;
} else if (newWord) {
newWord = false;
if (Character.isUpperCase(c)) {
ret++;
}
}
}
return ret;
}
}

Why don't you use a method from Files class, which is available from java 1.7
List<String> lst = Files.readAllLines(Path path, Charset cs)
then you can loop over the lst List checking your condition

Related

How to find the longest sequence of strings in order, but not necessarily contiguous

I have a program that reads input from two text files:
answersA.txt
10
US Independence
French Revolution
WW I
Great Depression
WW II
Korean War
British Invasion
Vietnam War
Gulf War
Dot Com Era
myanswers1.txt
7
Korean War
British Invasion
WW I
Vietnam War
Great Depression
US Independence
French Revolution
The first line is the how many values there will be. I'm trying to find the longest pattern between the two files. For these cases, the longest pattern is "Korean War,British Invasion,Vietnam War" and the score from the grade() method would be 5, since there were 5 answers right. I'm trying to use the dynamic programming approach, and although I can figure out how to do this for a singular string, I am struggling to figure out how to do it for an array of strings (if that's even the best way to handle it).
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
public class Patterns {
public int grade;
public String LHP;
String[] answers = null;
String[] myAnswers = null;
public Patterns(String filename) {
List<String> readAnswers = new ArrayList<String>();
try {
FileInputStream newFile = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(newFile);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
if ((line.length() != 0)) {
readAnswers.add(line);
}
}
buffer.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(readAnswers);
answers = new String[readAnswers.size()];
answers = readAnswers.toArray(answers);
}
public int grade(String filename) {
List<String> readMyAnswers = new ArrayList<String>();
try {
FileInputStream newFile = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(newFile);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String line;
while ((line = buffer.readLine()) != null) {
if ((line.length() != 0)) {
readMyAnswers.add(line);
}
}
buffer.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(readMyAnswers);
myAnswers = new String[readMyAnswers.size()];
myAnswers = readMyAnswers.toArray(myAnswers);
grade = LCS(answers, myAnswers);
return grade;
}
public String pattern(String filename) {
return LHP;
}
public static int LCS(String[] A, String[] B) {
int[][] LCS = new int[A.length + 1][B.length + 1];
String[][] solution = new String[A.length + 1][B.length + 1];
for (int i = 0; i <= B.length; i++) {
LCS[0][i] = 0;
solution[0][i] = "0";
}
for (int i = 0; i <= A.length; i++) {
LCS[i][0] = 0;
solution[i][0] = "0";
}
for (int i = 1; i <= A.length; i++) {
for (int j = 1; j <= B.length; j++) {
if (A[i - 1] == B[j - 1]) {
LCS[i][j] = LCS[i - 1][j - 1] + 1;
} else {
LCS[i][j] = Math.max(LCS[i - 1][j], LCS[i][j - 1]);
}
}
}
return LCS[A.length][B.length];
}
public static void main(String[] args) {
Patterns test1 = new Patterns("answersA.txt");
System.out.println("The score is: " + test1.grade("myanswers1.txt"));
}
}

How do I provide null to BufferedReader's readLine() method using Eclipse

public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
String line;
try {
while( (line = in.readLine()) != null ) {
System.out.println(line);
lineCount++;
charCount += line.length();
String[] words = line.split("\\W");
wordCount += words.length;
}
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
} catch (IOException e) {
e.printStackTrace();
}
}
Straight to the point: How do I exit the above while-loop? I've read on another question that readLine() returns null when there is no more line left to read, but how do I do that using Eclipse's console?
The only way I can manage to break the loop is to add in cases, such as
if(line.length() == 2 || line.equals("exit")))
break;
if you just want to read a line, why do you need while loop?
or if you want multiple inputs to be taken then you should specify how many inputs are to be taken in first readline();
otherwise i hope below code will resolve your issue :)
public class TestRandomArray {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
String line = in.readLine();
lineCount++;
charCount += line.length();
String[] words = line.split(" ");
wordCount += words.length;
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

ArrayIndexOutOfBoundsException in word frequency calculation

This is my logic for word frequency. I'm not supposed to use HashMap to store the frequency of a word. I am getting an ArrayIndexoutofBoundsException, but can't figure out why.
Program:
package thirdassignments;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordFreq2 {
public void Working() {
try {
File file = new File("C:/Users/kishansr/Desktop/file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String sentence = stringBuffer.toString();
String [] words = sentence.split("\\s+"); // splits by whitespace
for (String word : words) {
System.out.println(word);
}
String word1[] = new String [100000];
int count[] = {0}, count1 = 0;
for (String word : words) {
count1 = count1 + 1;
}
System.out.println("COunt :" + count1);
for (String word : words) {
for (int i = 0 ; i < count1 ; i++) {
if (word1[i] != word) {
word1[i] = word;
count[i] = 1; // here the exception is oocuring
}
else if (word1[i] == word) {
count[i] = count[i] + 1;
}
}
}
for (int i = 0 ; i < count1 ; i++) {
System.out.println(count[i] + " : " + word1[i]);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String [] args) {
// TODO Auto-generated method stub
WordFreq2 wf = new WordFreq2();
long startruntime = System.nanoTime();
wf.Working();
long endruntime = System.nanoTime();
System.out.println( "start time: " + startruntime + " end time :" + endruntime + " diferrence: " + (endruntime - startruntime));
}
}
Output :
This
is
the
Hewlett
Packard
company
.
This
Company
is
spread
over
the
world
and
has
established
its
footprints
in
almost
all
countries
.
It
has
a
huge
employee
count
and
has
more
women
employees
than
male
employees
.
COunt :39
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
You've instantiated the count[] array with a size of 1. It needs to be at least as large as your array.
Try change this line
String word1[]=new String[100000];
int count[]={0},count1=0;
for (String word : words) {
count1=count1+1;
}
to
String word1[]=new String[100000];
int count1=0;
for (String word : words) {
count1=count1+1;
}
count[]= new int[count1];
Your count array :
int count[]={0};
has a single element
So you'll get an exception for count[i] for any i>0.
Perhaps you should initialize it to the same length as the word1 array :
int count[]= new int[100000];
In addition, replace word1[i]==word with word1[i].equals(word).

Scanner will take user input but will not find the file

This is a program to read a file and print out the file with some of the text edited. The code will compile the issue is that it will read the users input but will say file is not found when the file is there. I feel like I am missing something. I am brand new at this so go easy on me.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MainTest {
public static void main(String args[]) {
// if (args[0] != null)
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = "";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count;
} else if (ch == '}') {
out = out + " " + count;
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
You can use System.getProperty("user.dir") to find where Scanner looking to find your file. And you should be sure your file is located here.

"Cannot Find Symbol - method hasNextLine()" error in Java

I am trying to write a program that uses file I/O to score personality tests. However, when I get to this code:
while (f.hasNextLine()) {
I get the error described in the title. Here is the code in its entirety. I import all of the necessary I/O and utilities prior and I think I am declaring the file variable correctly. I know that this method exists, but what is the problem?
import java.io.*;
import java.util.*;
public class PersonalityTest {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String input = input();
String output = output();
results(input, output);
System.out.println("Your results are located in the file you requested.");
}
public static String input() throws IOException {
System.out.print("Input file name: ");
String file = input.nextLine();
File f = new File(file);
System.out.println();
while (!f.exists()) {
System.out.print("File not found. Try again: ");
file = input.nextLine();
f = new File(file);
System.out.println();
}
return file;
}
public static String output() {
System.out.print("Output file name: ");
String output = input.nextLine();
return output;
}
public static void results(String input, String output) throws IOException {
PrintStream write = new PrintStream(new File(output));
File f = new File(input);
while (f.hasNextLine()) {
String name = f.nextLine();
String type = "ESTJ";
String answers = f.nextLine();
char[] choices = new char[70];
for (int i = 0; i <= 69; i++) {
choices[i] = answers.charAt(i);
}
int aCount = 0;
int bCount = 0;
for (int i = 0; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount+=1;
}
}
int pct1 = (int)Math.round((bCount/(aCount+bCount))*100);
if (pct1 > 50) {
type.replace('E','I');
}
if (pct1 == 50) {
type.replace('E','X');
}
int aCount2 = 0;
int bCount2 = 0;
for (int i = 2; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount2+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount2+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount2+=1;
}
}
int pct2 = (int)Math.round((bCount2/(aCount2+bCount2))*100);
if (pct2 > 50) {
type.replace('S','N');
}
if (pct2 == 50) {
type.replace('S','X');
}
int aCount3 = 0;
int bCount3 = 0;
for (int i = 4; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount3+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount3+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount3+=1;
}
}
int pct3 = (int)Math.round((bCount3/(aCount3+bCount3))*100);
if (pct3 > 50) {
type.replace('T','F');
}
if (pct3 == 50) {
type.replace('T','X');
}
int aCount4 = 0;
int bCount4 = 0;
for (int i = 6; i <= 69; i+=7) {
if (choices[i].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i].toLowerCase == 'b') {
bCount4+=1;
}
if (choices[i+1].toLowerCase == 'a') {
aCount4+=1;
}
if (choices[i+1].toLowerCase == 'b') {
bCount4+=1;
}
}
int pct4 = (int)Math.round((bCount4/(aCount4+bCount4))*100);
if (pct4 > 50) {
type.replace('J','P');
}
if (pct4 == 50) {
type.replace('J','X');
}
write.println(name + ": [" + pct1 + ", " + pct2 + ", " + pct3 + ", " + pct4 + "] = " + type);
write.close();
}
}
}
java.io.File does not have a hasNextLine() method. That's a method that exists in java.util.Scanner. Scanner has a constructor that takes a File object as an argument and allows it to use the specified file for input - you should probably try using that one:
Scanner s = new Scanner(new File(input));
EDIT:
That said, Scanner can be a bit of a performance killer (a bit?). It is often faster to use a BufferedReader and its readLine() method to read a single line into a String object and then parse the String manually. You can get a BufferedReader from a File with a bit of trickery:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
instead of using hasNextLine() method, which is non-existent in a File object, an alternative would be to access your file using an inputstream class like FileInputStream and wrapped inside a decorator class like BufferedReader, which would allow you to read its contents per line, using readLine() method....

Categories

Resources