quicksort method exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to read names from a file into an String array and use binary search to find the name based on what the user types in but I keep getting a null pointer exception? I feel like it has something to do with the comparators when seeing if anything returns a null but i am not 100% sure if its that.
import java.util.*;
import java.io.*;
public class nameSearch{
static String names[];
int length;
public static void main(String[] args)throws IOException{
nameSearch sorter = new nameSearch();
File f = new File("names.txt");
Scanner scan = new Scanner(f);
Scanner input = new Scanner(System.in);
names = new String[65];
int counter = 0;
while(scan.hasNext()){
counter = counter + 1;
scan.next();
for(int i=0; i < counter; i=i+1){
names[i] = scan.next();
System.out.println(names[i].toString());
}
}
sorter.sort(names);
System.out.println(names.toString());
scan.close();
System.out.println("Enter a name you want to search: ");
String s = input.nextLine();
sorter.binarySearch(s, names);
}
public String toString(){
return "Name: "+ names;
}
void sort(String[] array) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
void binarySearch(String s, String[] ar){
String stringToFind = s;
int lowestIndex = 0;
int highestIndex = ar.length-1;
int middleIndex = 0;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(stringToFind.compareTo(ar[middleIndex]) > 0){
lowestIndex = middleIndex+1;
}else if(stringToFind.compareTo(ar[middleIndex]) < 0){
highestIndex = middleIndex - 1;
}else{
break;
}
}
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found at " + middleIndex);
}
}
}
The compiler is telling me that there is a null pointer exception on: sorter.sort(names) , quicksort(0, length-1), and starting at:
while (this.names[i].compareToIgnoreCase(pivot) < 0) {

In line 16 you have defined names as String[65] and probably there is no 65 names in your file. so some of names elements are null.
try using arrayList.
public class NameSearch{
static ArrayList<String> names;
int length;
public static void main(String[] args)throws IOException{
NameSearch sorter = new NameSearch();
File f = new File("src/names.txt");
Scanner scan = new Scanner(f);
Scanner input = new Scanner(System.in);
names = new ArrayList<>();
int counter = 0;
while(scan.hasNext()){
names.add(scan.next());
}
sorter.sort(names);
System.out.println(names.toString());
scan.close();
System.out.println("Enter a name you want to search: ");
String s = input.nextLine();
sorter.binarySearch(s, names);
}
public String toString(){
return "Name: "+ names;
}
void sort(ArrayList<String> array) {
if (array == null || array.size() == 0) {
return;
}
this.names = array;
this.length = array.size();
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names.get(lowerIndex + (higherIndex - lowerIndex) / 2);
while (i <= j) {
while (this.names.get(i).compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names.get(j).compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
Collections.swap(this.names, i, j);
}
void binarySearch(String s, ArrayList<String> ar){
String stringToFind = s;
int lowestIndex = 0;
int highestIndex = ar.size()-1;
int middleIndex = 0;
while(lowestIndex<=highestIndex){
middleIndex = (lowestIndex+highestIndex)/2;
if(stringToFind.compareTo(ar.get(middleIndex)) > 0){
lowestIndex = middleIndex+1;
}else if(stringToFind.compareTo(ar.get(middleIndex)) < 0){
highestIndex = middleIndex - 1;
}else{
break;
}
}
if(lowestIndex > highestIndex){
System.out.println("not found");
}else{
System.out.println("found at " + middleIndex);
}
}
}

Related

Trouble implementing quicksort recursion in java

I'm doing a project for school and I have to test the speeds of binary vs linear searches for a spellcheck implementation. We have to use this certain SpellCheck. The examples given by my professor for binary search using recursion were a few separate snippets of code designed for ints and he wants us to make it work for this implementation with strings. Any help would be appreciated, I am very stuck at the moment. SortedWordList is the class i need help on.
import java.util.Scanner;
public class Spellcheck {
private static WordList listOfWords;// The list of correctly spelled words.
public static void main(String[] args) {
long start = System.nanoTime();
listOfWords = new SortedWordList();
//listOfWords = new WordList();
long end = System.nanoTime();
long WL = (end-start);
//end = 0;
//start = 0;
long SW = 0;
Scanner in = new Scanner(System.in);
while (true) { // Get and process one word from the user.
System.out.println();
System.out.print("Enter a word to be cheched (press return to end): ");
String word = in.nextLine().trim().toLowerCase();
start = System.nanoTime();
if (word.length() == 0)
break;
if (listOfWords.contains(word)) {
System.out.println("'" + word + "' is a legal word.");
}
else {
System.out.println("'" + word + "' is not a legal word.");
System.out.println("If there are similar words, they are shown here:");
trySubstitute(word);
tryInsert(word);
tryDelete(word);
trySwap(word);
tryBreak(word);
end = System.nanoTime();
SW = (end-start);
}
System.out.println();
System.out.printf("Time to create word list: %,d nanoseconds.%n",(WL));
System.out.println();
System.out.printf("Time to test for similar words: %,d nanoseconds.%n",(SW));
System.out.println();
System.out.printf("Time to test total: %,d nanoseconds.%n",(SW + WL));
}
}
private static void trySubstitute(String word) {
for (int i = 0; i < word.length(); i++) {
String before = word.substring(0, i);
String after = word.substring(i+1);
for (char ch = 'a'; ch < 'z'; ch++) {
String newword = before + ch + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
}
private static void tryInsert(String word) {
for (int i = 0; i <= word.length(); i++) {
String before = word.substring(0,i);
String after = word.substring(i);
for (char ch = 'a'; ch < 'z'; ch++) {
String newword = before + ch + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
}
private static void tryDelete(String word) {
for (int i = 0; i < word.length(); i++) {
String before = word.substring(0, i);
String after = word.substring(i+1);
String newword = before + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
private static void trySwap(String word) {
for (int i = 0; i < word.length() - 1; i++) {
String before = word.substring(0, i);
char a = word.charAt(i);
char b = word.charAt(i+1);
String after = word.substring(i+2);
String newword = before + b + a + after;
if (listOfWords.contains(newword))
System.out.println(" " + newword);
}
}
private static void tryBreak(String word) {
for (int i = 1; i < word.length() - 1; i++) {
String before = word.substring(0, i);
String after = word.substring(i);
if (listOfWords.contains(before) && listOfWords.contains(after))
System.out.println(" " + before + " " + after);
}
}
} // end class Spellcheck
`
import java.util.ArrayList;
import java.util.Scanner;
import java.net.URL;
public class WordList {
protected final String[] words; // the list of words
public WordList() {
try {
URL listLocation = WordList.class.getClassLoader().getResource("unsorted_words.txt");
Scanner in = new Scanner( listLocation.openStream() );
ArrayList<String> wordList = new ArrayList<String>();
while (in.hasNextLine())
wordList.add(in.nextLine());
words = wordList.toArray(new String[] {});
in.close();
}
catch (Exception e) {
throw new IllegalStateException("Can't load list of words from file 'unsorted_words.txt'");
}
}
public boolean contains(String lowerCaseWord) {
for (String s : words) {
if (s.equals(lowerCaseWord))
return true;
}
return false;
}
public int size() {
return words.length;
}
public String get(int index) {
return words[index];
}
}
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class SortedWordList extends WordList {
public String [] words;
public SortedWordList() {
URL listLocation = SortedWordList.class.getClassLoader().getResource("unsorted_words.txt");
Scanner in = null;
try {
in = new Scanner( listLocation.openStream() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> wordList = new ArrayList<String>();
while (in.hasNextLine())
wordList.add(in.nextLine());
words = wordList.toArray(new String[] {});
in.close();
}
//public boolean contains(String lowerCaseWord) {
//}
static int binarySearch(String[] A, int loIndex, int hiIndex, String value) {
if (loIndex > hiIndex) {
return -1;
}
else {
int middle = (loIndex + hiIndex) / 2;
if (value == A[middle])
return middle;
else if ((A[middle].compareTo(value)) > 0)
return binarySearch(A, loIndex, middle - 1, value);
else // value must be > A[middle]
return binarySearch(A, middle + 1, hiIndex, value);
}
} // end binarySearch()
static int quicksortStep(String[] A, int lo, int hi) {
String pivot = A[lo]; // Get the pivot value.
while (hi > lo) {
while (hi > lo && ((pivot.compareTo(A[hi])) <= 0)) {
hi--;
}
if (hi == lo)
break;
A[lo] = A[hi];
lo++;
while (hi > lo && ((pivot.compareTo(A[lo])) >= 0)) {
lo++;
}
if (hi == lo)
break;
A[hi] = A[lo];
hi--;
} // end while
A[lo] = pivot;
return lo;
} // end QuicksortStep
static void quicksort(String[] A, int lo, int hi) {
if (hi <= lo) {
return;
}
else {
int pivotPosition = quicksortStep(A, lo, hi);
quicksort(A, lo, pivotPosition - 1);
quicksort(A, pivotPosition + 1, hi);
}
}
}
First, where do you need to call quicksort? Just guessing by the class's name of SortedWordList, it would seem to me that you would need to call this quicksort method inside the SortedWordList's constructor. Right now, the constructor appears to load an unsorted list of words.
If that doesn't solve the problem, I would then also look at your quicksortStep method inside the SortedWordList class again. This quicksortStep method is basically the partition method. (See https://www.programcreek.com/2012/11/quicksort-array-in-java/ for an example). I would try to follow the same code structure in the quicksortStep method as the partition method in the link above, and then modify it for strings, until it is something like:
public static int partition(String[] arr, int start, int end){
String pivot = arr[end];
for(int i=start; i<end; i++){
if((arr[i].compareTo(pivot)) < 0){
String temp= arr[start];
arr[start]=arr[i];
arr[i]=temp;
start++;
}
}
String temp = arr[start];
arr[start] = pivot;
arr[end] = temp;
return start;
}
Feel free to rename methods / variables.

I need help updating an array in main from a method

This is the Main.java
Scanner input = new Scanner(System.in);
String in="t";
String [] t=new String[15];
int c=0;
int p=0;
String n="p";
for(int i=0;i<15;i++){
System.out.print("Enter a topping (or type quit):");
n=input.nextLine();
if(n.equals("quit")){
i=16;
p=1;
}else
t[i]=n;
c++;
}
String [] q=new String[c];
if(t[c-1]==null){
q=new String[c-1];
for(int u=0;u<c-1;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c-1;o++){
System.out.println((o+1)+". "+q[o]);
}
}
else{
q=new String[c];
for(int u=0;u<c;u++){
q[u]=t[u];
}
Arrays.sort(q);
if(p==0){
System.out.println("No more toppings allowed.");
}
for(int o=0;o<c;o++){
System.out.println((o+1)+". "+q[o]);
}
}
BinarySearch bs = new BinarySearch();
System.out.println("\nWhat do you want to search for?");
String search = input.nextLine();
System.out.println("BinarySearch: "+bs.binarySearch(q, search));
This is the BinarySearch.java class
public void printTopping() {
}
public boolean addTopping(String top) {
}
public int binarySearch(String[] words, String key) {
int left = 0;
int right = words.length - 1;
int mid = 0;
while (left <= right) {
mid = (left + right) / 2;
if ((words[mid] + "").trim().compareTo(key.trim()) < 0) {
left = mid + 1;
} else if ((words[mid] + "").trim().compareTo(key.trim()) > 0) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
How do I use the addTopping method to add an topping into the q array in main without there being a String array parameter in the addTopping method? Can I get help writing this method? Then How would i do printTopping() method?
This is the direction :
In main:
String[] toppingStringArray = Arrays.copyOf(q, q.length + 1);
In addTopping:
toppingStringArray[toppingStringArray.length - 1] = top;

count repeat of every word

I want to write a code that count repeat of every word in a string,words separate each other with some character that input as a string...why my code don't work?
please answer soon!
public class repeat {
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
System.out.println("Please write a string:");
String s = ss.nextLine();
System.out.println("Please write a character:");
String w = ss.nextLine();
int i = 0;
int j = 0;
int k = 0;
int y=0;
for (i=0 ;i < s.length() ;i++) {
for (j = 0; j < w.length(); j++) {
if (w.charAt(j) == s.charAt(i) && i!=y && i!=0 && i!=s.length() -1 ) {
k += 1;
y=i+1;
}
}
}
i = 0;
j = 0;
y = 0;
int r = 0;
k++;
System.out.println(k);
String[] a = new String[k];
for (r=0 ;r < k-1 ;r++) {
for (j=1 ;j < s.length() ;j++) {
for (i = 1; i < w.length(); i++) {
if (w.charAt(i) == s.charAt(j)) {
a[r] = s.substring(y, j);
y = j+1;
}
}
}
System.out.println(a[r]);
}
a[k-1] = s.substring(y+1,s.length());
i = 0;
int[] b = new int[k];
while (i <k) {
b[i] = 0;
i++;
}
i = j = 0;
while (i < k) {
while (j != i && j < k) {
if (a[i] == a[j]) {
a[j] = null;
b[i]++;
}
j++;
}
i++;
}
i = j = 0;
while (i < k) {
if (a[i] != null) {
System.out.println(a[i] + " " + b[i]);
}
i++;
}
}
}
Looking through your code your taking a very long approach to this problem. The easiest thing to do is use regex https://docs.oracle.com/javase/tutorial/essential/regex/. Please see the methods below.
public Sentence(String sentanceString) {
this.fullSentence = sentanceString;
breakStringIntoWords(sentanceString);
}
private void breakStringIntoWords(String sentanceString) {
String[] wordsInString = sentanceString.split("\\W+");
for (String word : wordsInString) {
words.add(new Word(word));
}
}
In the second method I broke a sentence (delimited by [spaces]) into words. From here you would write code to compare each word (a class that has a to string method so treat it as a string) to every other word in the Words array list, be careful to avoid over counting.
ok this is now Java with Split instead of searching the string manually:
I don't exactly know if the copyarray is the best practice to make it larger but if your string is not megabytes large it won't be a problem:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello world this is a very good test to a world just that contains just more words than just hello";
String w = " ";
String[] foundwords = new String[0];
int[] wordcount = new int[0];
String[] splittext = s.split(w);
for (int i = 0; i< splittext.length; i++)
{
int IndexOfWord = getIndexOfWord(splittext[i], foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = splittext[i];
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}
(Wrong language i did it wrongly in c# - see next answer for java)
I suggest to use array and Split for this because it is very complicated work with substring to seach for the char. While w still is a String, c need to be a type char.
String[] foundwords = { };
Int32[] wordcount = { };
foreach (String word in s.Split(w))
{
int IndexOfWord = Array.IndexOf(foundwords, word);
if (IndexOfWord < 0)
{
Array.Resize(ref foundwords, foundwords.Length + 1);
Array.Resize(ref wordcount, wordcount.Length + 1);
foundwords[foundwords.GetUpperBound(0)] = word;
wordcount[foundwords.GetUpperBound(0)] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
for (int i = 0; i <= foundwords.GetUpperBound(0); i++)
{
Console.WriteLine(String.Format("Found word '{0}' {1} times.", foundwords[i], wordcount[i]));
}
be aware that it is case sensitive.
so if it is still on your list i made a code.
First - you where lost to just let it run in the main procedure only. You should start and seperate your work into single tasks instead of writing a strait start stop program. Using functions with a "good" name will make it easier to you in future.
First you need something to find the String in another.
Usually you may use
int dividerPosition = restString.indexOf(searchString);
this is a java build in function. If you want to write it yourself, you could create a function like this (that will do the same but you can "see" it working:)
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
and use this function in your code later on like:
int dividerPosition = indexOf(restString, searchString);
I will again use the function to find either a word is allready known
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
Third Task would be to Split and count the Words at the found position.
The easier way (only my opinion) would be just to cut of the found Words from the String - so write a function that will "save" the found word in a array or count the "counter"-Array if it is allready found.
This most important task to understand is important - ok we will just look for the position of the string we are searching. We need to check if it is not found (so the last word)
We will store the found word (that is the part before the found String) in a variable and do the "count or create new word" thing. And then we will return the String cut of the word and the Seach-String.
The Cut-Off is important because we replace the origin String by the one without the first word and just repeat this until the origin String is "".
For the last word we ensure the function will return "" by changing the dividerPosition to the length of the RestString - that is the last word now only - minus "searchString.length()" so it will fit to the return "restString.substring(dividerPosition+searchString.length());" to return ""
Look in the next part into the function named "getNextW("
you can run int with the self-written IndexOf function or the Java function by changing the commentlines in
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
Everything together
to get startet you will have very little code in the main procedure using the "cut" function until the String is empty - all together now:
public class repeat
{
public static void main(String[] args)
{
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
while (!(s = getNextW(s, w)).equals(""))
{
System.out.println(s);
}
System.out.println("");
for (int i = 0; i < foundwords.length; i++)
{
// Debuging test:
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
private static String getNextW(String restString, String searchString)
{
/// Index Of Search (better)
//int dividerPosition = restString.indexOf(searchString);
/// Manual Search (why make it more difficuilt - you should learn to make your work as easy as possible)
int dividerPosition = indexOf(restString, searchString);
String foundWord;
if (dividerPosition > 0)
{
foundWord = restString.substring(0, dividerPosition);
}
else
{
foundWord = restString;
dividerPosition = restString.length()-searchString.length();
}
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
// Debuging test:
System.out.println(String.format("Rest of String is '%s' positionnext is %d.", restString, dividerPosition));
return restString.substring(dividerPosition+searchString.length());
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static int indexOf(String restString, String searchString)
{
int dividerPosition = -1;
for (int i = 0; i < restString.length()-searchString.length(); i++)
{
// Debuging test:
System.out.println(String.format("search Pos %d in '%s' for length %d.", i, restString, searchString.length()));
if (restString.substring(i, i + searchString.length()).equals(searchString))
{
dividerPosition = i;
i = restString.length();
}
}
return dividerPosition;
}
}
Other variant with charAt and im am using your kind of "count words to size the array" what will result in a to big array (potentially far to big):
public class repeat
{
private static String[] foundwords;
private static int[] wordcount;
private static int counter;
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos = 0;
counter = 1; // counting total w-strings+1 for dim
while ((tempPos = findnext(s, w, tempPos)) >= 0)
{
tempPos = tempPos + w.length();
counter++;
}
foundwords = new String[counter];
wordcount = new int[counter];
counter = 0;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < counter; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
foundwords[counter] = foundWord;
wordcount[counter] = 1;
counter++;
}
else
{
wordcount[IndexOfWord]++;
}
}
}
i like this one:
public class repeat
{
private static String[] foundwords = new String[0];
private static int[] wordcount = new int[0];
public static void main(String[] args) {
String s = "Hello a world a this is a very good test to a a a a world just that contains just more words than just hello";
String w = " ";
int tempPos;
while ((tempPos = findnext(s, w, 0)) >= 0)
{
String foundWord = s.substring(0, tempPos);
s = s.substring(tempPos + w.length());
foundWordToArray(foundWord);
}
foundWordToArray(s);
for (int i = 0; i < foundwords.length; i++)
{
System.out.println(String.format("Found word '%s' %d times.", foundwords[i], wordcount[i]));
}
}
private static void foundWordToArray(String foundWord)
{
int IndexOfWord = getIndexOfWord(foundWord, foundwords);
if (IndexOfWord < 0)
{
String[] foundwordsTemp = new String[foundwords.length + 1];
int[] wordcountTemp = new int[foundwords.length + 1];
System.arraycopy(foundwords, 0, foundwordsTemp, 0, foundwords.length);
System.arraycopy(wordcount, 0, wordcountTemp, 0, foundwords.length);
foundwords = new String[foundwords.length + 1];
wordcount = new int[wordcount.length + 1];
System.arraycopy(foundwordsTemp, 0, foundwords, 0, foundwordsTemp.length);
System.arraycopy(wordcountTemp, 0, wordcount, 0, foundwordsTemp.length);
foundwords[foundwords.length-1] = foundWord;
wordcount[foundwords.length-1] = 1;
}
else
{
wordcount[IndexOfWord]++;
}
}
public static int findnext(String haystack, String needle, int startPos)
{
int hpos, npos;
for (hpos = startPos; hpos < haystack.length()-needle.length(); hpos++)
{
for (npos = 0; npos < needle.length(); npos++)
{
if (haystack.charAt(hpos+npos)!=needle.charAt(npos))
{
npos = needle.length()+1;
}
}
if (npos == needle.length())
{
return hpos;
}
}
return -1;
}
private static int getIndexOfWord(String word, String[] foundwords)
{
for (int i = 0; i < foundwords.length; i++)
{
if (word.equals(foundwords[i]))
{
return i;
}
}
return -1;
}
}

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa

Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}

Count Method Java

I have an input file called input.txt with a list of names. I have no problem displaying all the names and putting them in alphabetical order with both display and sort methods. But what I am currently struggling to do is create a method where I can count the recurrence of each name in the file. I would grealty appreciate if anyone could help me with this, and find a way to create this method.
public class Names {
public static void display(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
System.out.println(names.get(i));
}
}
public static int find(String s, ArrayList<String> a) {
for (int i = 0; i < a.size(); i = i + 1) {
String str = a.get(i);
if (str.equals(s)) {
return i;
}
}
return -1;
}
public static void capitalize(ArrayList<String> names) {
for (int i = 0; i < names.size(); i = i + 1) {
String name = names.get(i);
if (!name.isEmpty()) {
String firstLetter = "" + name.charAt(0);
names.set(i, firstLetter.toUpperCase() + name.substring(1).toLowerCase());
}
}
}
public static void sort(ArrayList<String> names) {
for (int i = 0; i < names.size() - 1; i = i + 1) {
int Min = i;
for (int j = i + 1; j < names.size(); j = j + 1) {
if (names.get(j).compareTo(names.get(Min)) < 0) {
Min = j;
}
}
String tmp = names.get(i);
names.set(i, names.get(Min));
names.set(Min, tmp);
}
}
public static void getNames(ArrayList<String> fn, ArrayList<String> ln) throws IOException {
Scanner kb = new Scanner(System.in);
System.out.println("What is the input flie?");
String names = kb.next();
File inpFile = new File(names);
Scanner in = new Scanner(inpFile);
while (in.hasNext()) {
String firstName = in.next();
String lastName = in.next();
fn.add(firstName);
ln.add(lastName);
}
}
private int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size; i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
public static void main(String[] args) throws IOException {
ArrayList<String> first = new ArrayList<>();
ArrayList<String> last = new ArrayList<>();
getNames(first, last);
capitalize(first);
capitalize(last);
ArrayList<String> allNames = new ArrayList<>();
for (int i = 0; i < first.size(); i++) {
allNames.add(last.get(i) + ", " + first.get(i));
}
System.out.println("*******All Names******");
sort(allNames);
display(allNames);
System.out.println("*****First Name Count***");
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}
System.out.println("****Last Name Count****");
sort(last);
display(last);
}
}
Use Map structure for those case:
Map<String, Integer> recurence = new HashMap<>();
int count;
for (String name : names) {
if (recurence.containsKey(name)) {
count = recurence.get(name) + 1;
} else {
count = 1;
}
recurence.put(name, count);
}
create a method that counts the occurences:
public static int countOccurence(String name, ArrayList<String> names){
int count = 0;
for(int i =0; i <= names.size(); i++){
if(name.equalsIgnoreCase(names.get(i))){
count++;
}
}
return count;
}
To use it, go through the loop in you Main ( or you can create another method)
for(int i =0; i <= first.size; i++){
int count = countOccurence(first.get(i), first);
System.out.println(first.get(i) + " occured " + count + " times.");
}

Categories