count character occurrences in a string in Java - java

I'm trying to get this to print how many letter "a" there are.
It keeps giving me 0...any help?
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
String word = in.nextLine();
int counter = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}

A simpler (one line) way of counting occurrences of a char is:
int count = word.replaceAll("[^a]", "").length();
This replaces every character that's not an "a" with a blank - effectively deleting it - leaving you with a string containing just the "a" characters of the original string, then you get the length of that.

Beyond any issues reading the file, also try using the StringUtils countMatches. It's already in the common lang, mind as well use that instead.
For example
int count = StringUtils.countMatches(word, "a");

JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
int counter = 0;
while(in.hasNextLine()){
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}

Related

Split lines with "," and do a trim on every element [duplicate]

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Counting number of words start with UpperCase letter in strings, 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

Accessing indexes that may not exist Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code

I am working on a program that checks the spelling of a txt file using a given dictionary in java. I am not getting the right outputs

I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}

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.

Categories

Resources