I tried sorting strings using bubblesort, but I dont know whether it makes any sense but can someone just help me figure out how to sort strings and let me know if my logic is correct? i have converted the strings to character just to check if they are in alphabetical order..eg app ban acc will be sorted to acc app and ban..can anyone give the logic to this problem.
import java.io.*;
import java.util.*;
class sort
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the strings");
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str,",");
String s1=st.nextToken();
String s2=st.nextToken();
String s3=st.nextToken();
char ch1[]=s1.toCharArray();
char ch2[]=s2.toCharArray();
char ch3[]=s3.toCharArray();
if ((ch1[0]<ch2[0])&&(ch1[0]<ch3[0])&&(ch2[0]<ch3[0]))
for(int i=0;i<4;i++)
{
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
System.out.println(+ch3[i]);
}
else if((ch2[0]<ch1[0]&&ch2[0]<ch3[0]&&ch1[0]<ch3[0]) )
for(int i=0;i<4;i++)
{
System.out.println(+ch2[i]);
System.out.println(+ch1[i]);
System.out.println(+ch3[i]);
}
else if((ch3[0]<ch1[0])&&(ch3[0]<ch2[0])&&ch1[0]<ch2[0])
for(int i=0;i<4;i++)
{
System.out.println(+ch3[i]);
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
}
}
}
Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better. Wikipedia
The following is the sort-cut way to do so.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");//your sentence will be split into words.
Arrays.sort(strArr);
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
If you wish, you can apply your own logic as follows.
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");
String temp;
for(int i = 0; i<strArr.length - 1; i++)
{
for(int j = 0; j<strArr.length - 1; j++)
{
if(strArr[j].compareTo(strArr[j+1]) > 0)
{
temp = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = temp;
}
}
}
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
In both the cases, I have assumed spaces as word separator and not commas , that you're using in your example.
First you need to choose how do you want to sort strings ?
is it by length ? is it by alpha order ?
After you choose the appropriated method, you just need to sync it for the existing sorting method of bubblesort.
public static int[] bubble(String[] str_arr) {
for (int i = 0, temp; i < str_arr.length-1; i++) {
for(int j = 0; j < str_arr.length-1; j++) {
if (str_arr[j] < str_arr[j+1]) {
temp = str_arr[j];
str_arr[j] = str_arr[j+1];
str_arr[j+1] = temp;
}
}
}
return str_arr;
}
As i mentions theres couple of ways of comparing strings:
Length - length of a string
Lexicographically - explanation here
If we want to use one of the two method mentioned above, we should change the line:
if (str_arr[j] < str_arr[j+1])
to
if (str_arr[j].length < str_arr[j+1].length)
Or for the lexicographically order we will use:
if (str_arr[j].compareTo(str_arr[j+1].length) < 0)
compareTo is a java String method that checking lexicog.. order.
it returnes:
0 - strings are identical.
positive number - first string is bigger then second string.
negative number - first string is smaller then second string.
String implements interface Comparable (so overrides compareTo() method), thus you can compare two strings (>,<,>=,<=). That's why you don't have to compare every char element by element. Not worth trying even.
The solution: put Strings into array:
String[] stringArray = new String[]{"element1","element2"};
and then use default bubble-sort algorithm:
for (int x = 1; x < stringArray.length; x++) {
for (int y = 0; y < stringArray.length - x; y++) {
if (stringArray[y].compareTo(stringArray[y + 1]) > 0) {
temp = stringArray[y];
stringArray[y] = stringArray[y + 1];
stringArray[y + 1] = temp;
}
}
}
and you should receive sorted array.
Related
This question already has answers here:
How to sort String array by length using Arrays.sort()
(10 answers)
Closed 10 months ago.
INPUT: this is my string
OUTPUT: is my this string
I have to arrange words in a sentence according to their length and if two words have the same length then print them alphabetically (the first priority is length).
My incorrect code:
import java.util.Scanner;
class accordingtolength
{
void main()
{
String result="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
String arr[]=str.split(" ");
int l=arr.length;
for(int i=0;i<l-1;i++)
{
String temp=arr[i]+" ";
String temp1=arr[i+1]+" ";
int a=temp.length();
int b=temp1.length();
if(a==b)
{
int c=temp.compareTo(temp1);
if(c>0)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
else if(a>b)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
System.out.println(result);
}
}
I know my code is incorrect so there is no need to attach the output.
Please help.
Perhaps this is what you were looking for. Using minimal external classes, this simply sorts the array of words in ascending order based on their length first and then alphabetically if those lengths are equal It uses a variant of what is known as a selection sort. It is a basic sort and quite often used as an introduction to sorting. But it is not very efficient.
read in the string and split based on spaces (I modified your regex to allow 1 or more spaces).
then use nested loops to iterate thru the list, comparing lengths.
if the word indexed by the outer loop (i) is longer than the word indexed by the inner loop (j), swap the words.
else if equal length compare words to each other and sort alphabetically (the String class implements the Comparable interface).
when both loops are finished, the array will be sorted in
then you can just iterate over the result building a string of words separated by spaces.
public class AccordingToLength {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
String arr[] = str.split("\\s+");
for (int i = 0; i < arr.length-1; i++) {
int outer = arr[i].length();
for (int j = i + 1; j < arr.length; j++) {
int inner = arr[j].length();
if (outer > inner || outer == inner && arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
outer = inner; // outer has new length (what was just swapped)
}
}
}
String result = "";
for (String word : arr) {
result += word + " ";
}
System.out.println(result);
}
}
for input = "if a day now any easy when new test is done do den deed none"; this prints
a do if is any day den new now deed done easy none test when
There are multiple ways to solve this problem. The two most convenient ways are.
If you are allowed to use streams and comparator, then you can achieve it in a single line.
Arrays.stream(arr)
.sorted(Comparator
.comparing(String::length)
.thenComparing(Function.identity()))
.forEach(System.out::println);
Using Arrays.sort() to sort the actual array elements.
Arrays.sort(arr, (o1, o2) -> {
if (o1.length() > o2.length()) {
return 1;
} else if (o2.length() > o1.length()) {
return -1;
} else {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
If you don't want to use java provided APIs and data structures, you can implement a different version of bubble sort.
boolean isSwapped;
for (int i = 0; i < arr.length - 1; i++) {
isSwapped = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j].length() > arr[j + 1].length()
|| arr[j].length() == arr[j + 1].length() && arr[j].compareTo(arr[j + 1]) > 0) {
swap(arr, j, j + 1);
isSwapped = true;
}
}
if (!isSwapped)
break;
}
I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!
public class Test{
public static String reverse(String a){
int j = a.length();
char[] newWord = new char[j];
for(int i=0;i<a.length();i++)
{
newWord[j] = a.charAt(i);
j--;
}
return new String(newWord);
}
public static void main(String a[]){
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
You can use this to reverse the string, you don't need to use your own method
new StringBuilder(word).reverse().toString()
If you want to use your solution you must change int j = a.length() to int j = a.length() -1;
The fixed code is
public class Test {
public static String reverse(String a) {
int j = a.length();
char[] newWord = new char[j];
for (int i = 0; i < a.length(); i++) {
newWord[--j] = a.charAt(i);
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.
For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.
Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.
This is a common difficulty with new Java developers.
The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings
Here's an improved version to demonstrate.
public static String reverse(String a) {
char[] newWord = new char[a.length()];
for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
newWord[j] = a.charAt(i);
}
return new String(newWord);
}
You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.
Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.
So your for loop, because you're reversing the word, should begin at the end of the word being reversed (a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).
Try this and see if this makes sense to you:
public static String reverse(String a) {
String reversedWord = "";
for (int index = a.length() - 1; index >= 0; index --) {
reversedWord += a.charAt(index);
}
return reversedWord;
}
This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where index has gone beyond the character at index position 0 (the middle condition of index >= 0).
At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.
Hope this helps! Feel free to ask any other questions if you are stuck on this.
In your for loop, body must be as that
newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement j and then use it as array pointer.
public class Test {
public static String reverse(String a) {
int size= a.length();//size of string
char[] newWord = new char[size];//intialize
for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
static void reverse {
String word = "Hello World";
StringBuilder str = new StringBuilder(word);
str.reverse();
System.out.println(str);
}
or you could do
new StringBuilder(word).reverse().toString()
public static void main(String[] args) {
String input = "hello world";
String output = new String();
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
System.out.println(output);
}
package Reverse;
import java.util.*;
public class StringReverse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String original = input.nextLine();
String rev = "";// Initialize as Empty String
for(int i = original.length() - 1 ; i>=0 ; i--){
rev += original.charAt(i);
}
System.out.println("Reverse form: "+rev);
}
}
I have the below insertion sort function below, previously I was working with strictly an integer array and called the function below as a means of sorting it. Now in the below function, what I want to do is sort this function based on a file of arbitrary data. AM not entirely sure how to approach this. I tried writing the function and including the file path within the function but am guessing that is not entirely correct. Any suggestions on how to approach this correctly?
public static void InsertionSort(int filename[], int size) {
int index, count;
int temp;
index = 1;
Scanner sca = null;
try {
sca = new Scanner(new File(
"C:/Users/Frank/Downloads/wb1913_samp1040.txt"));
while (sca.hasNextLine()) {
while (index < size) {
temp = filename[index];
count = index;
while (count >= 0 && temp <= filename[count - 1]) {
filename[count] = filename[count - 1];
--count;
}
filename[count] = temp;
index++;
}
}
} catch (FileNotFoundException exception) {
} finally {
sca.close();
}
Updated Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner = null;
String file = "C:/Users/jdavis/Downloads/wb1913_samp1040.txt";
int count;
Word word = new Word();
LinkedList WordList = new LinkedList();
String[] f = {file};
try {
scanner = new Scanner(new File(
"C:/Users/jdavis/Downloads/wb1913_samp1040.txt"));
while (scanner.hasNextLine()) {
String[] Word = scanner.nextLine().split("\t");
word.setWord(Word[0]);
word.setPartsofSpeech(Word[1]);
word.setDefinition(Word[2]);
WordList.InsertAtBack(word);
WordList.Display();
System.out.println("Before sorting: " +Arrays.toString(f));
//sort array
InsertionSort(f);
System.out.println("After sorting: ");
printArray(f);
}
} catch (FileNotFoundException exception) {
} finally {
// scanner.close();
}
count = WordList.CountList();
System.out.println(count);
}
public static void InsertionSort(Comparable[] array) {
Comparable temp;
for(int i = 1; i < array.length; i++)
{
temp = array[i];
int j = 0;
for(j = i; j > 0; j--)
if(temp.compareTo(array[j - 1]) < 0)
array[j] = array[j - 1];
else
break;
array[j] = temp;
}
}
public static void printArray(String[] f){
System.out.println(Arrays.toString(f));
}
}
you can use the below sort method after you get your String
public static String[] dictionaryFormString(String[] s)
{
//
// Sort each individual string element by alphabetical order
//
for (int i = 0; i < s.length; i++)
{
String wordSt = s[i];
if(wordSt == null) continue;
char[] word = wordSt.toCharArray();
Arrays.sort(word);
s[i] = new String(word);
}
return s;
}
I'm assuming here that you are challenging yourself (or someone has challenged you) to write an insertion sort of your own, and that you want to insert each element as you read it from a file.
If you just want to read a file and end up with a sorted array, it would be simpler and more efficient to just slurp it into the array out-of-order, then use Arrays.sort(). Except as a learning exercise, programmers very seldom write sort algorithms nowadays.
You can make your programs much easier to understand by breaking them into more methods - each method does less, and so is easier to understand, but put together they are powerful.
So:
private void readIntoSortedArray(Scanner sca, String[] array) {
while (sca.hasNextLine()) {
insertInto(array, sca.nextLine());
}
}
private void insertInto(String[] array, String line) {
int index = findFirstElementGreaterThan(line);
shiftElementsByOne(array, index);
array[index] = line;
}
... and so on. Here I've given you the "middle" of your chain of methods. You will need to write a method higher in the stack, that prepares a Scanner and calls readIntoSortedArray. And you will need to write the methods called by insertInto(). Maybe those will call yet more methods.
This also means that you can write small programs to drive these sub-methods and check that they work as you expect, in isolation.
String[] testArray = new String[]{"Adam", "Brian", "Dave"};
int index = findFirstElementGreaterThan("Clive");
if(index != 2) {
throw new RuntimeException("Index should be 2 - was " + index);
}
This is a short step away from test-driven development, which is a good thing to adopt early in your studies, because it makes things much easier. (JUnit is a very popular tool that does essentially the same thing, nicer).
If, once you've done this, you feel your program has too many tiny methods, you can always "inline" your sub-methods -- but many feel that the right size for a method is absolutely tiny.
I guess you want an alphabetical sort. You can't compare strings with < and > -- you can use string1.compareTo(string2) (there are other, more flexible ways, but this is OK for now).
public static boolean doesKeyStringOccursEarlyInDict(String string,String key){
int i = Math.min(string.length(), key.length());
int j = 0;
while(j<i){
if(string.charAt(j) > key.charAt(j)){
return true;
}
j++;
}
//else return false as either both were equal or key does not come early in dictionary
return false;
}
public static void insertionSort(String[] s){
for(int i=1;i<s.length;i++){
String key = s[i];
int j = i-1;
while(j>=0 && doesKeyStringOccursEarlyInDict(s[j], key)){
s[j+1] = s[j];
j--;
}
s[j+1]=key;
}
}
public static void main(String[] args) {
//read the file each line
//split it and store it in an arraylist of string as it can grow..repeat it till u have read all the content
ArrayList<String> s = new ArrayList<>();
//get the complete string array
String[] stringarr = (String[]) s.toArray();
//example : String[] stringarr = {"def","xyz","abc","aaa"};
insertionSort(stringarr);
for(String words:stringarr)
System.out.println(words);
}
Above I have given the part that you are looking for.You are already able to read file.So just fill in the blanks in the above code.
Also I was not trying to challenge you rather was encouraging to think first then ask.
After incorporating the above I would encourage you to follow the approach mentioned by Slim and Nishanth.
If you have file that contains string and you want to sort it.
One approach could be to create a string array after reading file (assuming it isn't very big file) and then apply sorting.
// Read from file
String[] words = someFunctionThatReadFileAndReturnArrayOfString(file);
Arrays.sort(words); // or your sorting function
for (String word : words)
{
System.out.println(word);
}
If you want your insertionSort function to be more generic so that it will be independent of data type then you can ask for Comparable object from user as a additional parameter to your function and use it to compare objects in your code.
your method signature would be something like this-
public static void InsertionSort(Object list[],Comparator<Object> compare)
I participated in a coding challenge on hackerearth , and i was asked the following question .
Alice and Bob are playing a game in which Bob gives a string SS of length NN consisting of lowercase English alphabets to Alice and ask her to calculate the number of sub-strings of this string which contains exactly 3 vowels.
This is my code
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
for(int i=0;i<str.length();i++)
{
int ctr=0;
for(int j=1;j<str.length()-i;j++)
{
String subString = str.substring(i,i+j);
if(subString.length()<3)
{
continue;
}
if(subString.contains("a")||subString.contains("e")||subString.contains("i")||subString.contains("o")||subString.contains("u")
||subString.contains("A")||subString.contains("E")||subString.contains("I")||subString.contains("O")||subString.contains("U"))
{
ctr+=3;
}
}
if(ctr==3){
numberOfSubstring++;
}
}
return numberOfSubstring;
}
}
Iam getting time limit exceeded for the above code . Could any one help me out on how to optimise it .
Update1
Code as per #GhostCat logic , this needs to be tested and is not the final code.
class TestClass1{
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int N = Integer.parseInt(line);
String stringArray[]=new String[N];
for (int i = 0; i < N; i++) {
int len = Integer.parseInt(br.readLine());
stringArray[i]=br.readLine();
}
for (int i = 0; i < N; i++) {
System.out.println(determineNumberOfSubstring(stringArray[i]));
}
}
public static int determineNumberOfSubstring(String str)
{
int numberOfSubstring=0;
int ctr=0;
int subStringStart=0;
Stack<String> s = new Stack<String>();
for(int i=0;i<str.length();i++)
{
if(isVowel(str.charAt(i)))
ctr++;
if(ctr==3)
{
numberOfSubstring++;
ctr=0;
if(s.empty())
s.push(str.substring(0,i));
else
s.push(new String(s.peek().substring(1,i+1)));
i=str.indexOf(s.peek().charAt(1))-1;
}
}
return numberOfSubstring;
}
private static boolean isVowel(char c) {
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'
||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
return true;
return false;
}
}
Hint: your code is iterating the whole substring for each and any lower and upper case vowel there is. And that happens in a loop in a loop.
Instead: use ONE loop that goes over the characters of the input string. And then check each position if it is a vowel by checking against a set of characters (containing those valid vowels). The final thing you need: a simple "sliding" window; like: when you spot three vowels, you can increase your counter; to then "forget" about the first of the three vowels you just found; like in:
a x e y i --> vowels a/e/i give one substring
x e y i ... and you look out for the next substring e/i/... now
Actual implementation is left as exercise to the reader ...
Long story short: this count can be computed by processing your input ONCE. Your code is iterating countless times more than once. Well, not countless, but N * N * some more.
( the one thing to be careful with: when using a Set<Character> be precise when you turn a char value into aCharacter object; you want to minimize the instances of that happening, too; as that is a rather expensive operation )
HAPPY CODING ###### (if useful then upvote)
Que: count possible substring contain exactly 3 vowel in given string
my approach in O(n):
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
vector<long long int>idex;
idex.push_back(-1);
for(int i=0;i<n;i++)
{
if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u')
{
idex.push_back(i);
}
}
idex.push_back(n);
if(idex.size()<5)
{
cout<<0<<endl;
}
else
{
long long int ans=0;
for(int i=1;i<=idex.size()-4;i++)
{
ans+=(idex[i]-idex[i-1])*(idex[i+3]-idex[i+2]);
}
cout<<ans<<endl;
}
}
I am working on an assignment that wants me to create a program that accepts a text file with words in it, goes through every word, and then outputs the word with the most amount of double letters. So if a text file had 2 words, (past and progressive for example), it would output progressive. My problem is getting the program to compare each letter in a word. Specifically I cant seem to figure out how to split each word into its letters. Here is what I have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Doubles {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
///Prompts the user to give a file.
System.out.println("Enter the location of your file...");
String location = keyboard.next();
Scanner file = null;
List<String> list = new ArrayList<String>();
///If the the file location is wrong, give an error.
try {
file = new Scanner(new File(location));
} catch (FileNotFoundException e) {
System.out.println("Error: File not found");
System.exit(1);
}
while(file.hasNext()){
String word = file.nextLine();
list.add(word);
}
///System.out.println(list);
keyboard.close();
doublefinder(list);
}
private static void doublefinder(List<String> list) {
///Code to separate and compare letters.
}
}
I have tried many different approaches but I can't seem to find a solution. Any help would be much appreciated.
You can use the .toCharArray method to create a char array where each element is a letter of the word.
http://crunchify.com/java-simple-way-to-convert-string-to-char-array/
An example implementation is as follows:
public static boolean isDoubleword(String str){
char[] letters = str.toCharArray();
for(int i = 0; i< letters.length-1; i++){
if(letters[i] == letters[i+1])return true;
}
return false;
}
The above function takes a string and returns if the string is a double word.
The method could look like that
private String doubleFinder(List<String> list){
int maxDoubleLetters = 0;
int maxDoubleLettersID = 0; // the position of the word in your list
for(int n = 0; n < list.size(); n++){ // cycle throught each word
String word = list.get(n); // get a word from the list
char[] letters = word.toCharArray(); // split the word into letters
int doubleLetters = 0;
for(int i = 1; i < letters.length; i++){ // search for all double letters
if(letters[i] == letters[i-1]) doubleLetters++;
}
if(doubleLetters > maxDoubleLetters){
maxDoubleLetters = doubleLetters;
maxDoubleLettersID = n;
}
}
if(maxDoubleLetters > 0)
return list.get(maxDoubleLetters);
else
return null;
}
The method shown above will return the word with the highest number of double letters. If the file does not contain any words with double letters the method will return null.
Note: This will not work for words containing triple letters.
If you have any more questions fell free to ask in the comment section.
Arem,
The approach that I would use is to make a method that takes in a string and returns the number of double letters. This can be accomplished using the String.toCharArray(); function. You can then iterate through that array to compare the letters to see how many double letters there are in a string.
e.g.
public static int numDoubles(String str) {
int numDoubles = 0;
char[] blah = str.toCharArray()
for(int i = 0; i < str.length(); i++ {
//if the character == nextChar
numDoubles++;
}
return numDoubles;
}
Use that return value to compare your strings.