What should one change in the code so that instead of entering a string in console, one enters a text name (exmple.txt) to get to the text (where the frequences will be counted)?
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the Text: ");
String s = br.readLine();
System.out.println ("Enter suffix: ");
String sub = br.readLine();
int ind,count = 0;
for(int i = 0; i + sub.length() <= s.length(); i++)
{
ind = s.indexOf(sub, i);
if (ind >= 0)
{
count++;
i = ind;
ind = -1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
First of I will refactor your code like this in order to reuse the calculateOcurrences method. Then I would read the text file line by line and sum all the occurrences by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the file path: ");
final String filePath = br.readLine();
System.out.println ("Enter suffix: ");
final String suffix = br.readLine();
int count = 0;
Path path = FileSystems.getDefault().getPath(filePath);
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
count = count + calculateOcurrences(line,suffix);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
System.out.println("Occurence of '"+suffix+"' in String is "+count);
}
public static int calculateOcurrences(final String text, final String suffix) {
int ocurrences = 0;
for(int i = 0; i + suffix.length() <= text.length(); i++)
{
int indexOfOcurrence = text.indexOf(suffix, i);
if (indexOfOcurrence >= 0)
{
ocurrences++;
i = indexOfOcurrence;
}
}
return ocurrences;
}
}
Related
I am new to java and this might sound really stupid but !
Assume you have this txt file somewhere in your pc
The_txt.txt
Anthony
anthonyk#somewhere.com
01234567891
location
Maria
maria#somewhere.com
1234561234
location2
George
george#somewhere.com
1234512345
location3
What i want to do with this txt is that , I prompt the user to insert a Phone number so if for example the user provides Maria's phone number (1234561234) the program will output
Maria
maria#somewhere.com
1234561234
location2
My piece of code for this task :
private static void Search_Contact_By_Phone(File file_location){
Scanner To_Be_String = new Scanner(System.in);
String To_Be_Searched = To_Be_String.nextLine();
System.out.println("\n \n \n");
BufferedReader Search_Phone_reader;
try {
Search_Phone_reader = new BufferedReader(new FileReader (file_location));
String new_line = Search_Phone_reader.readLine();
while (new_line != null) {
if (To_Be_Searched.equals(new_line)){
for (int i=0;i<=3;i++){
System.out.println(new_line);
new_line = Search_Phone_reader.readLine();
}
break;
}
new_line = Search_Phone_reader.readLine();
}
Search_Phone_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you in advance!!!
package com.mycompany.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// For a small file
Path path = Paths.get("The_txt.txt");
String toBeSearched = "1234512345";
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Better performance if i starts at 2 and i += 4
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equals(toBeSearched)) {
System.out.println(lines.get(i - 2));
System.out.println(lines.get(i - 1));
System.out.println(lines.get(i));
System.out.println(lines.get(i + 1));
}
}
// Else
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line1;
while ((line1 = reader.readLine()) != null) {
String line2 = reader.readLine();
String line3 = reader.readLine();
if (line3.equals(toBeSearched)) {
// Found
System.out.println(line1);
System.out.println(line2);
System.out.println(line3);
System.out.println(reader.readLine());
break;
} else {
reader.readLine();
}
}
}
}
}
My goal for this program is to read a text file, print it normally, then print it flipped from left to right, and then flipped upside down. I can print the original, however I'm unsure of how to read the file so it will print in the other two formats, and how to print in these formats. I can only import the file once.
Here is an example output, if my description is inadequate.
The code as it is now:
import java.io.*;
import java.util.*;
public class Problem2
{
public static void main(String[] args) throws IOException
{
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext())
{
original = fileScan.nextLine();
System.out.println(original);
}
String lefttoright;
while (fileScan.hasNext())
{
lefttoright = fileScan.nextLine();
System.out.println(lefttoright);
}
String upsidedown;
while (fileScan.hasNext())
{
upsidedown = fileScan.nextLine();
System.out.println(upsidedown);
}
fileScan.close();
}
}
Try to use StringBuilder(element).reverse().toString(); where element is a string.
Example of working code:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\Documents\\test.txt");
List<String> listString = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//write as is
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
//write in reverse
while ((line = br.readLine()) != null) {
String result = new StringBuilder(line).reverse().toString();
System.out.println(result);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
listString.add(line);
}
//write down up
Collections.reverse(listString);
for (String element : listString) {
String result = new StringBuilder(element).reverse().toString();
System.out.println(result);
}
}
}
Test example:
test.txt file content:
alpha
tree
123
Output:
alpha
tree
123
ahpla
eert
321
321
eert
ahpla
You might consider as below. this will save you the hassle with reading 3 times from the file.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
System.out.println(original);
System.out.println();
System.out.print(flip(original));
System.out.println();
System.out.print(updsideDown(original));
}
public static String flip(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = 0; i < intermInput.length; i++) {
StringBuffer strBuff = new StringBuffer(intermInput[i]);
output.append(strBuff.reverse());
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
public static String updsideDown(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = intermInput.length - 1; i >= 0; i--) {
output.append(intermInput[i]);
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
}
Either use suggestion from YCF_L or use below solution.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
fileScan = new Scanner(marge);
String lefttoright;
while (fileScan.hasNext()) {
lefttoright = fileScan.nextLine();
StringBuffer sb = new StringBuffer(lefttoright);
System.out.println(sb.reverse());
}
fileScan = new Scanner(marge);
String upsidedown;
Stack<String> list = new Stack<String>();
while (fileScan.hasNext()) {
upsidedown = fileScan.nextLine();
list.push(upsidedown);
}
for (int i = 0; i <= list.size(); i++) {
System.out.println(list.pop());
}
fileScan.close();
}
}
What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}
The Text file:
9310,12,120,2,1
9333,12,120,2,1
PRINT
9533,5,45,0,0
8573,10,120,1,0
6343,6,18,170,0
PRINT
9311,12,120,2,1
3343,7,20,220,0
Code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
i mport java.util.Comparator;
import java.util.List;
public class FantasyPlayers {
int player_ID;
int total_score;
public FantasyPlayers(int player, int total) {
player_ID = player;
total_score = total;
}
public String toString() {
return player_ID + "," + total_score;
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
FileInputStream fstream = new FileInputStream("Stats.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String delims = "[,]";
List<FantasyPlayers> Stats = new ArrayList<FantasyPlayers>();
int a = 2;
int b = 1;
int c = 6;
int d = -1;
for (String line; (line = br.readLine()) != null;)
{
String[] parsedData = line.split(delims);
if (line != "PRINT")
{
int score = Integer.parseInt(parsedData[1])*a + Integer.parseInt(parsedData[2])*b + Integer.parseInt(parsedData[3])*c + Integer.parseInt(parsedData[4])*d ;
Stats.add(new FantasyPlayers(Integer.parseInt(parsedData[0]), score));
}
else
continue;
}
br.close();
System.out.println("Unordered");
for (FantasyPlayers str : Stats)
{
System.out.println(str);
}
Collections.sort(Stats, new Comparator<FantasyPlayers>()
{
public int compare(FantasyPlayers one, FantasyPlayers two)
{
if (one.total_score == two.total_score){
Integer playerOne = one.player_ID;
Integer playerTwo = two.player_ID;
return playerTwo.compareTo(playerOne);
}
Integer scoreOne = one.total_score;
Integer scoreTwo = two.total_score;
return scoreTwo.compareTo(scoreOne);
}
});
System.out.println("Ordered");
for (FantasyPlayers str : Stats)
{
System.out.println(str);
}
}
}
I Keep getting the Error ArrayIndexOutOfBoundsException:1 at the int score = location.
My question is how do I handle the PRINT statements in the code...I'm able to do what I want with the data but I need the logic to do something when I read in the print statement. Any suggestions?
You, my friend has fallen for the most common java mistakes....
try this
if (!line.equalsIgnoreCase("PRINT"))
Try to change this line
String delims = "[,]";
to
String delims = ",";
and this line
line != "PRINT"
to
!line.trim().equals("PRINT")
I have a problem in reading data from a text file and put it in 2 dimensional array. The sample of dataset is:
1,2,3,4,5,6
1.2,2.3,4.5,5.67,7.43,8
The problem of this code is that it just read the first line and does not read the next lines. Any suggestion is appreciated.
package test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1{
public static void main(String args[])throws FileNotFoundException, IOException{
try{
double[][] X = new double[2][6];
BufferedReader input = new BufferedReader(new FileReader(file));
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
int rowCounter = 0;
while ((line = input.readLine())!= null) {
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
}
}
}
Have you tried the Array utilities? Something like this:
while ((line = input.readLine())!= null) {
List<String> someList = Arrays.asList(line.split(","));
//do your conversion to double here
rowCounter++;
}
I think the blank line might be throwing your for loop off
The only place that your temp array is being assigned is before your while loop. You need to assign your temp array inside the loop, and don't read from the BufferedReader until the loop.
String[] temp;
String line;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine())!= null) {
temp = line.split(delims); // Moved inside the loop.
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
Try:
int rowCounter = 0;
while ((line = input.readLine())!= null) {
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
...
readLine expects a new line character at the end of the line. You should put a blank line to read the last line or use read instead.
I couldn't run the code, but one of your problems is that you were only splitting the first text line.
package Test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1 {
public static void main(String args[]) {
try {
double[][] X = new double[2][];
BufferedReader input = new BufferedReader(new FileReader(file));
String line = null;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine()) != null) {
String[] temp = line.split(delims);
for (int i = 0; i < temp.length; i++) {
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
I formatted your code to make it more readable.
I deferred setting the size of the second element of the two dimensional array until I knew how many numbers were on a line.