I am a beginner-novice and I am trying to figure out why the logic for finding the largest word doesn't work.
Sometimes the output will result in the correct longest word, the first word, or more than one word.
Thanks!!
PS
I do not really care about the cases if two words of the same length, which I will work later once I figure out why this doesn't work. And once again please note I am a beginner/novice. Thanks
import java.util.Scanner;
import java.util.ArrayList;
public class Word
{
public static String word(String str)
{
int longestCount=0;
int count=0;
int newWord=0;
String theWord="";
ArrayList <String> longestWord= new ArrayList <String>();
for (int i=0; i <str.length(); i++)
{
if (str.substring(i,i+1).equals(" "))
{
if (longestCount<count)
{
longestCount=count;
theWord="";
theWord=""+str.substring(newWord,i);
newWord=i+1;
count=0;
}
}
else
{
count++;
}
}
longestWord.add(theWord);
String output="";
for (int i=0; i<longestWord.size();i++)
output+=longestWord.get(i);
return output;
}
public static void main ()
{
Scanner scan= new Scanner(System.in);
String words= scan.nextLine();
System.out.println(word(words));
}
}
You are over thinking it. Just loop through the array list once, whenever you see a longer word, store the word/or its index:
ArrayList <String> words= new ArrayList <String>();
String currLongest = words.get(0);
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
If your words are being passed as a single String delimited by spaces, the procedure is the same. Just split them before looping:
String[] words = str.split(" ");
String currLongest = words.[0];
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
Note that there is no need to store the longest word into a list because at any point of time, there should only be one longest word.
It'll be easier to chop up the string using split first. then you can simplify your codes to the following.
I have commented as much as I can in the code below
public static List<String> word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
ArrayList <String> longestWord= new ArrayList <String>(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.clear(); //remove the old entries
longestWord.add(theWord); // add the new word in
longestWordLength = theWord.length(); update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.add(theWord); // add the new word in
}
}
return longestWord;
}
it returns a list instead of a String for the event when several words are the same length.
edit alternatively you can use a StringBuilder too.
public static String word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
StringBuilder longestWord= new StringBuilder(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.setLength(0); //remove the old entries
longestWord.append(theWord); // add the new word in
longestWordLength = theWord.length(); //update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.append(" "); //add a spacing between each word (or any delimiter that you like)
longestWord.add(theWord); // add the new word in
}
}
return longestWord.toString();
}
Related
This assignment ask to implement printWordRun so that it prints whatever word run it can find starting from the beginning of the input list words. The word run should be printed in reverse order, with each word on a separate line. PrintWordRun is a method which takes a parameter called words which is an ArrayList<String>. The word run is a series of words in the input list, where each word is longer in length than the previous. The word run ends once we either encounter the end of the list, or we encounter a word whose length is equal to or shorter than the previous word.
The array is:
I
am
cat
with
happy
dog
sitting
the result should be:
happy
with
cat
am
I
To get full credit for this assignment, I have to use a stack to print it as I have done, but I cannot get the word "happy" into the stack. My output is:
I
am
cat
with
public class Program {
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for(int i = 1; i < words.size(); i++) {
String str1 = words.get(i-1);
String str2 = words.get(i);
if(str2.length() < str1.length()) {
break;
}
if(str1.length() < str2.length()){
wordRun.push(str1);
}
System.out.println(wordRun);
}
}
public static void main(String[] args) {
Program program = new Program();
program.testPrintWordRun();
}
private void testPrintWordRun() {
ArrayList<String> words = new ArrayList<>();
words.add("I");
words.add("am");
words.add("cat");
words.add("with");
words.add("happy");
words.add("dog");
words.add("sitting");
System.out.println("Testing printWordRun...");
printWordRun(words);
System.out.println();
}
}
Here is one way to construct the printWordRun function:
Stack<String> wordRun = new Stack<>();
int maxLength = 0;
for(String s : words) {
if(s.length() > maxLength ) {
maxLength = s.length();
wordRun.add(s);
} else
break;
}
while(!wordRun.isEmpty())
System.out.println(wordRun.pop());
Just store a value of the current, maximum length and use this to compare your current string.
Output:
Testing printWordRun...
happy
with
cat
am
I
Start by adding the word to the stack with add(int index, E element) to insert the last item as first, and break the loop if the condition doesn't match afterwards.
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for (int i = 1; i < words.size(); i++) {
String str1 = words.get(i);
String str2 = words.get(i - 1);
wordRun.add(0, str2);
if(str2.length() >= str1.length()) {
break;
}
}
System.out.println(wordRun); // [happy, with, cat, am, I]
}
public class LongWord {
public static void main(String args[]) {
String text = "my brother is taller than me#1233334. I always a short man,but smart than him";
// Find the longest word in the String
String[] words = text.split("\\s");
String longestWord = "";
for (int i = 1; i < words.length; i++) {
int firstLen = words[i - 1].length();
int secondLen = words[i].length();
if (firstLen <= secondLen) {
longestWord = words[i];
}
}
System.out
.println("===================================================\nLongest Word:::: \n");
System.out.println(longestWord);
}
}
// This is the sample program to find the longest word in the statement. so the output should be "me#1233334" word. but I am getting "man,but" word as output. can anyone please help me what is wrong with program.
Your method doesn't find the largest string in an array of strings. It finds the last string in an array of strings which is larger than the string directly before it.
Your comparison (firstLen <= secondLen) doesn't compare either of the strings to the current longest string. Your main loop should be:
String longestWord = words[0];
for(String word : words) {
if(word.length() > longestWord.length()){
longestWord = word;
}
}
You can also use for(int i = 0; i < words.length(); i++) and use words[i] instead of (String word : words) and word
The logic for deciding the longest word is wrong.
You are comparing a "word" (in this context, word just means something separated by a white space) with the previous word, and if it is longer, that is now the longest.
man,but is selected because it is simply longer than its previous word (short). Note that nothing after man,but is selected because no words after that are longer than their previous word
You're doing it wrong. You aren't comparing if the secondLen is bigger than longestWord, it should actually be:
longestWord = words[0];
for (int i = 1; i < words.length; i++) {
int longestLen = longestWord.length();
int secondLen = words[i].length();
if (longestLen <= secondLen) {
longestWord = words[i];
}
}
I'm trying to find all permutations of a word and add that to an Arraylist and return the array list. But, I believe my recursion is right but, there is a problem with adding the results to the ArrayList.This is what I have so far. The parameters I passed were "eat" and "" and what is returned is "tea" three times
public static ArrayList<String> permutations(String word, String beginning)
{
int l = word.length();
ArrayList<String> temp = new ArrayList<String>();
if(l == 0)
temp.add(beginning + word);
else
{
char c = word.charAt(l-1);
String blah = (beginning + c);
word = word.substring(0, l-1);
for(int i = 0; i < l; i++)
{
permutations(word, blah);
temp.add(blah + word);
}
}
return temp;
}
Probably I didn't have the right idea of your approach to find an easy fix and by the time I got things working I ended up with this. I hope it isn't too much of a departure and that it's still helpful. The output is:
[tea, tae, eta, eat, ate, aet]
import java.util.ArrayList;
public class Perm {
public static void main(String[] args) {
ArrayList<String> perms = new ArrayList<String>();
permutations("tea", perms);
System.out.println(perms);
}
public static ArrayList<String> permutations(String word, ArrayList<String> perms)
{
int l = word.length();
// If the word has only a single character, there is only
// one permutation -- itself. So we add it to the list and return
if (l == 1) {
perms.add(word);
return perms;
}
// The word has more than one character.
// For each character in the word, make it the "beginning"
// and prepend it to all the permutations of the remaining
// characters found by calling this method recursively
for (int i=0; i<word.length(); ++i) {
char beginning = word.charAt(i);
// Create the remaining characters from everything before
// and everything after (but not including) the beginning char
String blah = word.substring(0,i)+word.substring(i+1);
// Get all the permutations of the remaining characters
// by calling recursively
ArrayList<String> tempArray = new ArrayList<String>();
permutations(blah, tempArray);
// Prepend the beginning character to each permutation and
// add to the list
for (String s : tempArray) {
perms.add(beginning + s);
}
}
return perms;
}
}
I'm trying to insert a word into an alphabetically sorted array of words. the code below converts the array to an arraylist and inserts the word into the right place. However, if the word to be inserted has to go at the very end, it doesn't get inserted. For the last for loop, I tried setting the condition to <= aList.size () but i get an a ArrayList.rangeCheck and ArrayList.get exception. Any help would be appreciated.
import java.util.*;
public class insertSort {
public static void main(String args []) {
String [] sortedArray = new String [] {"aa", "ball", "dog", "zebra", "zzz"};
ArrayList <String> aList = new ArrayList <String> (); //create new arraylist
for (int i=0; i < sortedArray.length; i++){
String temp = sortedArray [i];
aList.add(temp);
}
System.out.println(aList);
String word = "zzzz";
for (int i =0; i < aList.size();i++) {
String temp = aList.get(i);
int comparisonResult = word.compareTo(temp) ;
if (comparisonResult < 0 | comparisonResult == 0) {
aList.add(i , word);
break;}
}
System.out.println(aList);
}
}
Use a boolean to record whether you successfully inserted the word ahead of any others, and if not, add it to the end of the array:
boolean wasInserted = false;
for (int i =0; i < aList.size();i++) {
String temp = aList.get(i);
int comparisonResult = word.compareTo(temp) ;
if (comparisonResult < 0 || comparisonResult == 0) {
aList.add(i , word);
wasInserted = true;
break;
}
}
if(!wasInserted) {
aList.add(word);
}
The for loop will only add the new word to the List if the word comes alphabetically before another word or if it equals another word in your list. In the case of
String word = "zzzz";
This does come alphabetically before another or equal another word so it is not added.
You need to add some sort of check to see if the work was added and if not, call
aList.add(word)
to add the new word to the end of the list.
My teacher specifically requested that we split a sentence into words without using String.split(). I've done it using a Vector (which we haven't learned), a while-loop, and substrings. What are other ways of accomplishing this? (preferably without using Vectors/ArrayLists).
I believe that your teacher is asking you to process the string yourself (without using any other libraries to do it for you). Check to see if this is the case - if you can use them, there are things such as StringTokenizer, Pattern, and Scanner to facilitate string processing.
Otherwise...
You will need a list of word separators (such as space, tab, period, etc...) and then walk the array, building a string a character at a time until you hit the word separator. After finding a complete word (you have encountered a word separator character), save it the variable out into your structure (or whatever is required), reset the variable you are building the word in and continue.
Parsing the string character by character, copying each character into a new String, and stopping when you reach a white space character. Then start a new string and continue until you reach the end of the original string.
You can use java.util.StringTokenizer to split a text using desired delimiter. Default delimiter is SPACE/TAB/NEW_LINE.
String myTextToBeSplit = "This is the text to be split into words.";
StringTokenizer tokenizer = new StringTokenizer( myTextToBeSplit );
while ( tokinizer.hasMoreTokens()) {
String word = tokinizer.nextToken();
System.out.println( word ); // word you are looking in
}
As an alternate you can also use java.util.Scanner
Scanner s = new Scanner(myTextToBeSplit).useDelimiter("\\s");
while( s.hasNext() ) {
System.out.println(s.next());
}
s.close();
You can use java.util.Scanner.
import java.util.Arrays;
public class ReverseTheWords {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(ReverseTheWords.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
YOu can use StringTokenizer
http://www.java-samples.com/showtutorial.php?tutorialid=236
Or use a Pattern (also known as a regular expression) to try to match the words.
Use a Scanner with ctor (String)
regular expressions and match
StringTokenizer
iterating yourself char by char
recursive iteration
Without using a Vector/List (and without manually re-implementing their ability to re-size themselves for your function), you can take advantage of the simple observation that a string of length N cannot have more than (N+1)/2 words (in integer division). You can declare an array of strings of that size, populate it the same way you populated that Vector, and then copy the results to an array of the size of the number of words you found.
So:
String[] mySplit( String in ){
String[] bigArray = new String[ (in.length()+1)/2 ];
int numWords = 0;
// Populate bigArray with your while loop and keep
// track of the number of words
String[] result = new String[numWords];
// Copy results from bigArray to result
return result;
}
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class sha1 {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(sha1.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = c.length-1; i >= 0; i--) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
Simple touch.! Improve if you want to.
package com.asif.test;
public class SplitWithoutSplitMethod {
public static void main(String[] args) {
split('#',"asif#is#handsome");
}
static void split(char delimeter, String line){
String word = "";
String wordsArr[] = new String[3];
int k = 0;
for(int i = 0; i <line.length(); i++){
if(line.charAt(i) != delimeter){
word+= line.charAt(i);
}else{
wordsArr[k] = word;
word = "";
k++;
}
}
wordsArr[k] = word;
for(int j = 0; j <wordsArr.length; j++)
System.out.println(wordsArr[j]);
}
}
Please try this .
public static String[] mysplit(String mystring) {
String string=mystring+" "; //append " " bcz java string does not hava any ending character
int[] spacetracker=new int[string.length()];// to count no. of spaces in string
char[] array=new char[string.length()]; //store all non space character
String[] tokenArray=new String[string.length()];//to return token of words
int spaceIndex=0;
int parseIndex=0;
int arrayIndex=0;
int k=0;
while(parseIndex<string.length())
{
if(string.charAt(parseIndex)==' '||string.charAt(parseIndex)==' ')
{
spacetracker[spaceIndex]=parseIndex;
spaceIndex++;
parseIndex++;
}else
{
array[arrayIndex]=string.charAt(parseIndex);
arrayIndex++;
parseIndex++;
}
}
for(int i=0;i<spacetracker.length;i++)
{
String token="";
for(int j=k;j<(spacetracker[i])-i;j++)
{
token=token+array[j];
k++;
}
tokenArray[i]=token;
//System.out.println(token);
token="";
}
return tokenArray;
}
Hope this helps
import java.util.*;
class StringSplit {
public static void main(String[] args)
{
String s="splitting a string without using split()";
ArrayList<Integer> al=new ArrayList<Integer>(); //Instead you can also use a String
ArrayList<String> splitResult=new ArrayList<String>();
for(int i=0;i<s.length();i++)
if(s.charAt(i)==' ')
al.add(i);
al.add(0, 0);
al.add(al.size(),s.length());
String[] words=new String[al.size()];
for(int j=0;j<=words.length-2;j++)
splitResult.add(s.substring(al.get(j),al.get(j+1)).trim());
System.out.println(splitResult);
}
}
Time complexity: O(n)
You can use java Pattern to do it in easy way.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
You can also use String.substring or charAt[].