problem is that the code print the letters twice - java

i'm writing a code that read from a file then print the frequency of each alphabetic letter
that is my code
BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"));
String str = "";
str = read.readLine();
str = str.toUpperCase();
while ((str = read.readLine()) != null) {
int[] count = new int[26];
str = str.toUpperCase();
for (int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
count[str.charAt(i) - 'A']++;
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] >= 0) {
write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
write.newLine();
}
}
}
but the problem is that the code print the letters twice even i convert the letters to uppercase.
how can i fix this problem?
thank you so much guys

If your input file has two lines, then the frequencies will be printed "twice" because your file writer is inside the for-each-line loop.
If you're trying to print the character frequencies for the entire file, then try this
try (BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"))) {
// counts for file
int[] count = new int[26];
// read whole file
String str;
while ((str = read.readLine()) != null) {
str = str.toUpperCase();
for (int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
count[str.charAt(i) - 'A']++;
}
}
}
// loop counts and write frequencies to output file
for (int i = 0; i < count.length; i++) {
if (count[i] >= 0) {
write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
write.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
}
For large files, you may want a long[] count

Related

Java mapping issue

Basically the program is supposed to search through a text file and find the amount of occurrences of different words and store them in an array and then display the word and the amount of times to the user. I tried using the map class but that was not successful due to the fact that it won't display the results. So I was wondering if anyone knows any other ways I could fix this file:
public class WordStats {
public static void main(String[] args) {
File textFile = new File("words.txt");
FileReader in;
BufferedReader readFile;
char charInFile;
String newWord = "";
String map=new String();
String existingMap=new String();
int wordIndex, index = 0;
ArrayList wordList = new ArrayList();
/* navigating the file */
try{
in = new FileReader(textFile);
readFile = new BufferedReader(in);
do{
charInFile = (char)readFile.read();
if(charInFile >= 'a' && charInFile <= 'z'){
while(charInFile >= 'a' && charInFile <= 'z'){
newWord += charInFile;
charInFile = (char)readFile.read();
}//end of while
wordIndex = wordList.indexOf(map);
if(wordIndex > -1){
existingMap = (String) wordList.get(wordIndex);
//existingMap.addOccurrence();
wordList.set(wordIndex, existingMap);
} else {
index = 0;
}
if(wordList.size() > 0){
do{
existingMap = (String) wordList.get(index);
index += 1;
}while(existingMap.compareTo(map) <= 0 && index <
wordList.size());
wordList.add(index-1, map);
}else{
wordList.add(map);
}
}//end of if
newWord = "";
}while(charInFile != (char)-1);
System.out.println("Word\t\tOccurrences");
for(Object Word : wordList){
System.out.println(Word);
}
readFile.close();
in.close();
}catch(FileNotFoundException e){
System.out.println("file could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
}catch(IOException e){
System.out.println("problem reading the file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

When reading file with Java Scanner, it hangs after the last line has been processed

My method is able to read all the lines of the file but then it gets stuck at the last line and never reaches scanner.close() and onwards. I'm not sure why? I invoke scanner.nextLine() so surely it should detect this and scanner.hasNextLine() should return false when the file ends. Is there a quick fix that I have overlooked here?
private int[] GetNumberOfRowsAndColumns(BufferedReader br) {
Scanner scanner = new Scanner(br);
String line = "";
int column_max = 0;
int total_rows = 0;
int[] result = new int[1];
try {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.length() > column_max) {
column_max = line.length();
}
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
}
scanner.close();
result[0] = column_max;
result[1] = total_rows;
return result;
}
The file in question:
+++++++++++++++++
+0A +
+AA ++++
+ +
+ ++A+
+ +a+
+++++++++++++++++
EDIT:
public SearchClient(BufferedReader serverMessages) throws Exception {
Map<Character, String> colors = new HashMap<Character, String>();
String line, color;
int agentCol = -1, agentRow = -1;
int colorLines = 0, levelLines = 0;
// Read lines specifying colors
while ((line = serverMessages.readLine())
.matches("^[a-z]+:\\s*[0-9A-Z](,\\s*[0-9A-Z])*\\s*$")) {
line = line.replaceAll("\\s", "");
String[] colonSplit = line.split(":");
color = colonSplit[0].trim();
for (String id : colonSplit[1].split(",")) {
colors.put(id.trim().charAt(0), color);
}
colorLines++;
}
if (colorLines > 0) {
error("Box colors not supported");
}
int[] result = getNumberOfRowsAndColumns(serverMessages);
System.err.println("MAX COLUMNS = " + result[0]);
System.err.println("MAX ROWS = " + result[1]);
initialState = new Node(null);
while (!line.equals("")) {
for (int i = 0; i < line.length(); i++) {
char chr = line.charAt(i);
if ('+' == chr) { // Walls
initialState.walls[levelLines][i] = true;
} else if ('0' <= chr && chr <= '9') { // Agents
if (agentCol != -1 || agentRow != -1) {
error("Not a single agent level");
}
initialState.agentRow = levelLines;
initialState.agentCol = i;
} else if ('A' <= chr && chr <= 'Z') { // Boxes
initialState.boxes[levelLines][i] = chr;
} else if ('a' <= chr && chr <= 'z') { // Goal cells
initialState.goals[levelLines][i] = chr;
}
}
line = serverMessages.readLine();
levelLines++;
}
}
By convention, Java methods start with a lower case letter. Next, your array can only hold one value (length of 1) and you don't need a Scanner (use your BufferedReader). Finally, you can make an anonymous array. Something like,
private int[] getNumberOfRowsAndColumns(BufferedReader br) {
int column_max = 0;
int total_rows = 0;
try {
String line;
while ((line = br.readLine()) != null) {
// if (line.length() > column_max) {
// column_max = line.length();
// }
column_max = Math.max(column_max, line.length());
total_rows++;
}
} catch (Exception e) {
System.err.println(e);
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new int[] { column_max, total_rows };
}

Encrypt/Decrypt file. ASCII +1 for encryption/decryption

I'm trying to read in a file of text, and "encrypt"/convert each letter to +1 from the ASCII table (I also want to "decrypt" so -1 for that). So "a" will become "b", "b" to "c" and so forth. I only need to convert alphabetic letters (Ignore everything else, print them as is). I'm having troubles with this part of the code:
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
I've figured out how to +1 the char, but I'm not sure how to add that back in to an array or print it out correctly (Since "morewords.add(ch)" is only going to add the char, instead of converting all the chars an adding a string). The "words.get(i).length()" takes the entire length of the array "words", when I just want the length of the string # position "i" in the array, so it throws an error since the length of the array is longer than the string word. I've been stuck on this for hours and I cannot figure it out. I'm thinking maybe I shouldn't read them in as strings and should have read them in as chars and this might have all been simpler?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Character> morewords = new ArrayList<Character>();
String fileName = ""; //Replace Test with this
File f;
Scanner fileIn;
System.out.println("Please enter a file name for encryption: ");
//fileName = in.nextLine();
fileName = "Test.txt";
try
{
//Build the file and attach a scanner to it
f = new File (fileName);
fileIn = new Scanner (f);
System.out.println(f.exists()); //For errors
int counting = 0;
//Reads in indvidual strings.
for(counting =0; fileIn.hasNext(); counting++)
{
words.add(fileIn.next());
System.out.println(words);
}
PrintWriter fileOut = new PrintWriter ("Backwards.txt");
for(int i = 0; i <= words.size(); i++)
{
for(int j = 0; j <= words.get(i).length(); j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch += 1;
morewords.add(ch);
}
fileOut.print(morewords.get(i) + " ");
}
fileOut.close();
}
catch(FileNotFoundException e)
{
System.out.println("Couldn't find file");
}
}
First in a for loops is right to do
for (int i = 0; i <= words.size()-1; i++){}
if you'r starting at 0 you end at length-1
what i have changed is
PrintWriter fileOut = new PrintWriter("C:/Backwards.txt");
for (int i = 0; i <= words.size()-1; i++)
{
for (int j = 0; j <= words.get(i).length()-1; j++)
{
char ch = ' ';
ch = words.get(i).charAt(j);
ch ++; // +=1
morewords.add(ch);
fileOut.print(ch);
}
fileOut.print(" ");
}
fileOut.close();
and it output right if i have understood right =)
this is my code
public static void main(String[] args) throws Exception
{
BufferedReader inChannel = new BufferedReader(new FileReader("C:/script.txt"));
BufferedWriter outChannel = new BufferedWriter(new FileWriter("C:/output.txt"));
String toParse = "";
while ( (toParse = inChannel.readLine()) != null )
{
String toWrite = "";
for(int i=0; i!=toParse.length();i++)
{
char c = toParse.charAt(i);
if(true) //check if must be encoded or not
{
c++;
toWrite += c;
}
}
outChannel.write(toWrite);
outChannel.newLine();
}
inChannel.close();
outChannel.close();
}
hope helped

Split file having Integers and string into strings only

i have the file which has data stored as " Integer-> \t(tab)-> String ->couple of space-> ".
Am I doing Wrong?
What I am doing is.
Trie t = new Trie();
BufferedReader bReader = new BufferedReader(new FileReader(
"H:\\100kfound.txt"));
String line;
String[] s = null;
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
}
int i;
for (i = 0; i < s.length; i++) {
System.out.println(s[i]);
if (!(s[i].matches("\\d+"))) {
t.addWord(s[i]);
System.out.println(s[i]);
}
}
What I can see by debugging it is going properly till while loop but in for loop it just stores two strings and prints the same.
You might want to and a ^[0-9]+$ for the expressions so you just get complete integers. Without the ^ and $ you could be matching other characters like tt55gh would match.
if (!(s[i].matches("^[0-9]+$"))) {
}
Per the comment above you need to move the for loop inside the while loop.
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
for (int i = 0; i < s.length; i++) {
System.out.println("Value "+i+": "+s[i]);
if (!(s[i].matches("^[0-9]+$"))) {
t.addWord(s[i]);
System.out.println("Integer "+i+": "+s[i]);
}
}
}

Java Reading 2D array in from file, numbers separated by comma

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.

Categories