I want to find the longest words in a given String.
The following code checks for the longest word, but I want every other word with the same length as well.
try (BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
String longestWord = "";
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWord.length()) {
longestWord = sentence[i];
}
}
System.out.println(longestWord);
}
Then you have to use a collection of these longestWords, e.g.
ArrayList<String> longestWords = new ArrayList<String>();
int longestWordLength = 0;
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWordLength) { // longer
longestWordLength = sentence[i].length();
longestWords.clear();
longestWords.add(sentence[i]);
}
else if (sentence[i].length() == longestWordLength) { // same length
longestWords.add(sentence[i]);
}
}
for (int i = 0; i < longestWords.size(); ++i)
System.out.println(longestWords.get(i));
try(BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
ArrayList<String> longestWord = new ArrayList<>();
int maxLength = 1;
for(int i = 0; i < sentence.length; i++){
if(sentence[i].length() > maxLength){
longestword.clear();
longestWord.add(sentence[i]);
maxLength=sentece[i].length();
}
else if(sentence[i].length() == maxLength)
{
longestWord.add(sentence[i]);
}
}
System.out.println(longestWord);
}
Related
Could you help me to add an additional check to this code that would help me to find the number of words from each paragraph?
enter code here
String path = "C:/CT_AQA - Copy/src/main/resources/file.txt";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
String line = " ";
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int countNotLetter = 0;
int letterCount = 0;
int wordInParagraph = 0;
while ((line = br.readLine()) != null) {
if (line.equals("")) {
paragraphCount++;
} else {
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
String[] letterList = line.split("[^a-zA-Z]+");
countNotLetter += letterList.length;
}
letterCount = characterCount - countNotLetter;
}
br.close();
System.out.println("The amount of words are " + countWord);
System.out.println("The amount of sentences are " + sentenceCount);
System.out.println("The amount of paragraphs are " + paragraphCount);
System.out.println("The amount of letters are " + letterCount);
}
java
The total count of words in paragraphs should be the same as the total count of words wordCount from all lines.
If the number of words per paragraph has to be counted, then wordsInParagraph should be the list of integers List<Integer> wordsPerParagraph which may be counted like this:
int wordInParagraph = 0;
List<Integer> wordsPerParagraph = new ArrayList<>();
while ((line = br.readLine()) != null) {
if (line.equals("")) {
paragraphCount++;
wordsPerParagraph.add(wordInParagraph);
wordInParagraph = 0;
} else {
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
wordInParagraph += wordList.length; // !!!
String[] sentenceList = line.split("[!?.:]+");
sentenceCount += sentenceList.length;
String[] letterList = line.split("[^a-zA-Z]+");
countNotLetter += letterList.length;
}
letterCount = characterCount - countNotLetter;
}
// in case the last paragraph does not have trailing empty line
if (wordInParagraph != 0) {
wordsPerParagraph.add(wordInParagraph);
}
I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}
My problem statement:
There will be given set of words in a file (>5000 words). We need return a list of anagrams separated by comma(,) in each string(set of anagrams)
Eg: [alter,later, part,trap, elbow,below, listen,silent , tensil ]
Exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:265)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)
at java.util.ArrayList.add(ArrayList.java:462)
at FindAnagrams01.anagramsList(FindAnagrams01.java:25)
at FindAnagrams01.main(FindAnagrams01.java:7)
My code is :
public static List<String> anagramsList(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String str = br.readLine();
List<List<String>> result = new ArrayList<List<String>>(10000);
HashMap<String, ArrayList<String>> map = new HashMap<String,ArrayList<String>>(10000);
while(str != null) {
char[] arr = new char[26];
for(int i = 0; i < str.length(); i++) {
arr[str.charAt(i) - 'a']++;
}
String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(str);
} else {
ArrayList<String> al = new ArrayList<String>(10000);
al.add(str);
map.put(ns, al);
}
}
br.close();
result.addAll(map.values());
String res[] = new String[10000];
for(int i = 0; i < result.size(); i++) {
int isIntial = 0;
for(String j : result.get(i)) {
if ((result.get(i).size()) > 1) {
if (isIntial == 0) {
res[i] = j;
isIntial = 1;
}
else
res[i] += "," + j;
}
}
}
List<String> angrms = new ArrayList<String>(10000);
for (int i = 0; i < res.length; i++) {
if (res[i] != null)
angrms.add(res[i]);
}
return angrms;
}
The problem is that this is an infinite loop:
while(str != null) {
char[] arr = new char[26];
for(int i = 0; i < str.length(); i++) {
arr[str.charAt(i) - 'a']++;
}
String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(str);
} else {
ArrayList<String> al = new ArrayList<String>(10000);
al.add(str);
map.put(ns, al);
}
}
because str is not altered within the loop body. As a result, you end up repeatedly adding strings to an array list until you eventually run out of memory.
There are other problems with your code ... but this explains your OOME.
I have :
String1[] having Number,Quantity,Unit of Measure,Find Number parameters
String2[] having Action,Level,Number,Organization ID,Container,Revision,View,Quantity,Unit of Measure,Reference Designators,Trace Code,Find Number,Line Number,Component Reference,Quantity Option,Inclusion Option,Type
this parameters I have compare both the strings split them by commas using for loop. I want string1 found in string2 at which index. I want to store those index in one integer.
Please give any idea.
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
// String[] columns = header.split(",");
int[] indices = new int[20];
for (int i = 0; i < two.length; i++) {
for (int j = 0; j < col.length; j++) {
if(two[i].equals(col[j])){
System.out.println("("+i+","+j+")");
indices[i]=i;
}
}
Thanks in Advance
You can use the list.indexOf(Object o) method. Example:
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
int[] indices = new int[col.length];
for(int j = 0; j < col.length; j++){
indices[j]=Arrays.asList(two).indexOf(col[j]);
}
System.out.println(Arrays.toString(indices));
}
I want to search in an arraylist from a user input but my if condition doesn't seem to work. Using boolean and .contains() doesn't work for my programme either. This is the coding:
String phone;
phone=this.text1.getText();
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\data.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<String[]>();
while ((indata = line.readLine()) != null) {
String[] club = new String[2];
String[] value = indata.split(",", 2);
//for (int i = 0; i < 2; i++) {
int n = Math.min(value.length, club.length);
for (int i = 0; i < n; i++) {
club[i] = value[i];
}
boolean aa = dataArr.contains(this.text1.getText());
if(aa==true)
text2.setText("The data is found.");
else
text2.setText("The data is not found.");
dataArr.add(club);
}
for (int i = 0; i < dataArr.size(); i++) {
for (int x = 0; x < dataArr.get(i).length; x++) {
System.out.printf("dataArr[%d][%d]: ", i, x);
System.out.println(dataArr.get(i)[x]);
}
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
Your dataArr is a list of String[], and you are searching for a String. The two are different kind of objects.
I don't really know how the content of the club array looks like, but you should either change dataArr in order to hold plain String, or to write a method which looks iteratively in dataArr for a String[] containing the output of this.text1.getText().
There is a lot wrong with the program. I assume you want to read a textfile and store each line in the arraylist. To do this you have to split each line of the textfile and store that array in the arrayList.
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
Now you have the contents of the file in the arrayList.
Next you want to compare the userinput with each element of the arraylist.
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) { // i am assuming here that the phone number is the 2nd element of the String[] array, since i dont know how the textfile looks.
System.out.println("Found number.");
club[j++] = phoneData[1];
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
Edit:
As requested:
String phone;
phone = "38495";
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("list.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[2];
String[] value;// = indata.split(",", 2);
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) {
System.out.println("Found number.");
club[j++] = phoneData[1];
break;
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
I hope this makes sense now.