I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two
Related
I am trying to sort an array of names alphabetically by using compareTo() and a method String addSort(String name) but I get an error when compiling at the line "return name", saying that my "variable "name" may not be initialized" when it already is.
I've made the method and the code for sorting alphabetically which I think should be correct when using compareTo() as a way of sorting the array. (The array "moreFriends" is a new array which doubles the size of the original array "friends" when it gets full) (Note this is not all of the code)
public class SimpleDataStructure{
private String [] friends;
private String [] moreFriends;
private int counter;
public SimpleDataStructure()
{
friends= new String[5];
counter=0;
}
public String addSort(){
String name;
for(int i = 0; i < moreFriends.length; i++){
for(int j = i + 1; j < moreFriends.length; j++){
if(moreFriends[i].compareTo(moreFriends[j]) > 0){
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
System.out.println("Names in sorted order:");
for(int i = 0; i < moreFriends.length -1; i++){
System.out.println(moreFriends[i]);
}
return name;
}
public static void main( String [] arg){
SimpleDataStructure sortedfriends = new SimpleDataStructure();
System.out.println(sortedfriends.addSort(name));
}
This is the error message I get when i try to compile the program:
SimpleDataStructure.java:85: error: variable name might not have been initialized
return name;
^
1 error
When I expect the output to eventually be:
(unsorted)
Kalle
Bob
Carl
Alice
Lewis
(sorted)
Alice
Bob
Carl
Kalle
Lewis
You need declare youre function like this:
public String addSort(String name){
and delete the string declaration:
String name;
and you don't put value for name.
You can solved your problem using this:
String [] a="a","v","b";
Arrays.sort(a);
The reason that you are getting the compile error is because you never set a value to the String name before trying to use it.
You should be passing in the value like you have in your description addSort(String name). This will remove that error.
I do not see a reason why you are returning the String in your function.
This function does not appear to add the passed in name either.
Hope this helps!
import java.util.*;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
public static void main(String[] arg) {
Scanner input=new Scanner(System.in);
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name =new String[5];
System.out.println("Enter name(s): ");
for (int i = 0; i < name.length; i++) {
name[i]=input.nextLine();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}
And if you want the names to print out line by line, just create a for loop instead of Arrays.toString
Or you could even use Arrays.sort , which is much simpler
import java.util.Arrays;
class SimpleDataStructure {
public String[] addSort(String moreFriends []) {
for (int i = 0; i < moreFriends.length; i++)
Arrays.sort(moreFriends);
return moreFriends;
}
public static void main(String[] arg) {
SimpleDataStructure sortedFriends = new SimpleDataStructure();
String [] name ={"Kalle", "Bob","Carl","Alice", "Lewis"};
System.out.println("Unsorted:");
System.out.println(Arrays.toString(name));
System.out.println("Sorted:");
System.out.println(Arrays.toString(sortedFriends.addSort(name)));
}
}
I changed my arrays "friends" and "moreFriends" to static in my class.
Now my code looks something like this when im calling my method in my main:
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort()));
And this is my method:
public String[] addSort() {
for (int i = 0; i < moreFriends.length; i++) {
for (int j = i + 1; j < moreFriends.length; j++) {
if (moreFriends[i].compareTo(moreFriends[j]) > 0) {
String temp = moreFriends[i];
moreFriends[i] = moreFriends[j];
moreFriends[j] = temp;
}
}
}
return moreFriends;
}
However i get this error message now:
Unsorted:
Kalle Bob Carl Alice Lewis
Sorted:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at SimpleDataStructure.addSort(SimpleDataStructure.java:75)
at SimpleDataStructure.main(SimpleDataStructure.java:108)
You need to include your variable name, that holds the names, inside addSort
SimpleDataStructure sorted = new SimpleDataStructure();
System.out.println("Sorted:");
System.out.println(Arrays.toString(sorted.addSort(**HERE**)));
I've been working on this question for a while and I'm still stumped.
I'm supposed to write a method stutter that takes an ArrayList<String> as a parameter and that replaces every string with two of that string. For example, if the list stores the values {"how", "are", "you?"} before the method is called, it should store the values {"how", "how", "are", "are", "you?", "you?"} after the method finishes executing.
But despite my best efforts I still can't seem to get rid of the empty elements that are in my code.
Any help would be greatly appreciated.
public static ArrayList<String> stutter(ArrayList<String> lst) {
ArrayList<String> list = new ArrayList<String>();
int size = lst.size();
int intSize = lst.size();
int inSize = lst.size();
int size4 = list.size();
if (lst.size() == 0) {
lst.clear();
} else {
for (int x = 0; x < size; x++) {
for (int i = 0; i < 2; i++) {
lst.add(lst.get(x));
}
}
for (int x = 0; x < intSize ; x++) {
lst.set(x,"");
}
for (int x = inSize - 1; x < size; x++) {
String oldInfo = lst.get(x);
list.add(oldInfo);
}
list.removeAll("",null);
}
return list;
}
Try this approach:
public void duplicate(final List<String> inputList) {
final List<String> temp = new ArrayList<>();
inputList.forEach(element -> {
temp.add(element);
temp.add(element);
});
inputList.clear();
inputList.addAll(temp);
}
Basically what I am doing here: another list called temp is used to store each element from your initial list 2 times. After that I just clean the initial list and add new stuff.
Instead of clear and addAll you can just return temp - it contains data as you need. But don't forget to change method return type from void to List<String> in that case.
Happy Coding :)
Try this
public static ArrayList<String> stutter(ArrayList<String> lst) {
ArrayList<String> list = new ArrayList<String>();
if (!lst.isEmpty()) {
for (String string : lst) {
list.add(string);
list.add(string);
}
}
return list;
}
}
this could do what you need , its basically checks list if not empty and duplicate the strings in the list
Following up on already good answers, here is my example with keeping the original sample method signature:
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Stutter {
public static List<String> stutter(final List<String> words) {
// Create the response array.
List<String> response = new ArrayList<>();
// Check for valid arguments. If not, return empty array of words.
if (words == null || words.size() <= 0) {
return response;
}
// Iterate over the words that were passed in.
for (final String word : words) {
// Add the words twice to the response.
response.add(word);
response.add(word);
}
// The stutter response.
return response;
}
public static void main(final String[] args) {
final String[] myWords = { "hello", "world" };
final List<String> myStutterWords = stutter(new ArrayList<>(Arrays.asList(myWords)));
for (final String s : myStutterWords) {
System.out.println(s);
}
}
}
I've recently begun taking a Computer Science course to understand programming more and seem to have hit a roadblock with our lab on ArrayLists. The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.
Ex:Zebra, Deer, Giraffe
Deer
Result:Giraffe, Zebra, Deer
I've looked around online and found a few examples using ArrayList comparators but our professor wants us to do it by filtering out the largest word, printing it, removing it and then continue that loop until all words are printed out.
Here is my code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = 0;
String longest = "";
String currentWord = "";
ArrayList <String> DescendArray = new ArrayList<String>();
System.out.println("What would you like to add to the list?");
String userInput = input.next();
while(!userInput.equals("d"))
{
DescendArray.add(userInput);
userInput = input.next();
}
for (int i=0; i < DescendArray.size(); i++)
{
if (DescendArray.get(i).length() > longest.length())
{
currentWord = DescendArray.get(i);
if (currentWord.length() > longest.length())
{
longest = currentWord;
length = longest.length();
}
}
for (int j=1; j < DescendArray.size() -1 ; j++)
{
if (DescendArray.get(j - 1).length() > longest.length())
{
DescendArray.remove(j - 1);
}
System.out.println(longest + " " + length);
}
}
}
}
I'm assuming my error is somewhere in the inner loop but I can't seem to get it to work no matter how many different variations I use.
This is basically what you gotta do:
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
while(!zoo.isEmpty()) {
String bigger = "";
for(String animal : zoo) {
if(animal.length() > bigger.length()) {
bigger = animal;
}
}
System.out.println(bigger);
while(zoo.contains(bigger)) {
zoo.remove(bigger);
}
}
}
}
I'm amazed at the verbosity of other solutions. A much simpler method would be to use a stream:
List<String> original = Arrays.asList("s1", "String 2", "ss3", "s");
List<String> sorted = original.stream()
.sorted((s1, s2) -> s2.length() - s1.length())
.collect(Collectors.toList());
System.out.println(sorted);
Replace "original" with your ArrayList.
Try this, it works for me.
List<String> sorted = list.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
This seems to work. If you don't want to remove repeating animals then remove distinct() method. I omitted creation of the list.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = Arrays.asList("Zebra", "Deer", "Giraffe", "Deer");
String output = zoo.stream()
.distinct()
.sorted((x, y) -> Integer.compare(y.length(), x.length()))
.collect(Collectors.joining(","));
System.out.println(output);
}
}
Under the assumption that duplicate words need not be removed at the same time, such that a duplicate word will be removed in order, and that the list need not be done in alphabetical order (one could sort the list first), and that thread safety is not important, I would avoid using the integer counters and checking the size. Instead, I would run the output loop until everything has been removed.
As an example:
public void doRemove()
{
while (! descendArray.isEmpty()) {
String longest = "";
for (String s : descendArray) {
if (s.length() > longest.length()) {
longest = s;
}
}
if (longest.length() > 0) {
if (descendArray.remove(longest)) {
System.out.println(longest + " (" + longest.length() + ")");
}
}
} // while we stil have things to process
}
When you say descending order are you referring to the length of the string or an alphabetical comparison?
Check out how the QuickSort algorithm can be used for string sorting. You can find information on QuickSort here
The problem seems to be that for each iteration in your for loop, you arrive at Giraffe as your longest word, then you're checking the rest of the list to see if it is longer than Giraffe. Instead of what you have now, I would write something like:
for (int i=0; i < DescendArray.size(); i++)
{
longest = "";
length = longest.length();
int longestIndex = 0;
for (int j=1; j < DescendArray.size() -1 ; j++)
{
currentWord = DescendArray.get(j);
if (currentWord.length() > longest.length())
{
longestIndex = j;
longest = currentWord;
length = longest.length();
}
}
DescendArray.remove(longestIndex);
System.out.println(longest + " " + length);
}
This nested for loop should find the longest word first, store the index and print and remove the entry at that index before it finds the next longest entry.
Here is another variation which can be used, but involves an extra array list:
ArrayList<String> DescendArray = new ArrayList<>();
DescendArray.add("Monkey");
DescendArray.add("Giraffe");
DescendArray.add("Hippo");
DescendArray.add("Zebra");
DescendArray.add("Monkey");
List<String> copy = new ArrayList<>(DescendArray);
for (int i=0; i<DescendArray.size(); i++) {
String longest = "";
for (int j=0; j<copy.size(); j++) {
String current = copy.get(j);
if (current.length() > longest.length()) {
longest = current;
}
}
System.out.println(longest);
while(copy.contains(longest)) {
copy.remove(longest);
}
}
When you need to remove element from the list, iterator is a better way. See below for the code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
Collections.sort(zoo,new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
Iterator<String> iterator=zoo.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
iterator.remove();
}
}
}
To sort an ArrayList based on it's each String length, you can try:
private ArrayList SortwithStrlength(ArrayList templist) {
for(int i=0;i<templist.size();i++)
{
for(int j=0;j<templist.size();j++)
{
String temp;
if(templist.get(i).toString().length()<templist.get(j).toString().length())
{
temp=templist.get(i).toString();
templist.set(i, templist.get(j).toString());
templist.set(j,temp);
}
}
}
return templist;
}
I am creating a method compareTo(AltString altStr2) that sorts strings by their length (shortest to longest).
However, I would like to go the extra mile and check for strings that are of the same length. In that case, I figure it is best to sort the strings lexicographically, so that they are sorted in the same way they would appear in the dictionary. So far my code is below.
public class AltString {
String internalStr;
public AltString(String str) {
internalStr = str;
}
public String toString() {
return internalStr;
}
public int compareTo(AltString altStr2) {
if (this.internalStr.length() < altStr2.internalStr.length()) {
return -1;
} else if (this.internalStr.length() > altStr2.internalStr.length()) {
return 1;
} else {
int idx = 0;
while (this.internalStr.charAt(idx) != altStr2.internalStr.charAt(idx)) {
if (this.internalStr.charAt(idx) < altStr2.internalStr.charAt(idx)) {
return -1;
}else if (this.internalStr.charAt(idx) > altStr2.internalStr.charAt(idx)) {
return 1;
} else {
idx += 1;
public static void main(String[] args) {
// some test code for the AltString class
String [] list = {"fortran", "java", "perl", "python", "php", "javascrip", "c", "c++", "c#", "ruby"};
AltString [] alist = new AltString[list.length];
for (int i=0; i<alist.length; i++) {
alist[i] = new AltString(list[i]);
}
Arrays.sort(list);
Arrays.sort(alist);
System.out.println("String sort:");
for (int i=0; i<list.length; i++) {
System.out.println(list[i]);
}
System.out.println("\nAltString sort:");
for (int i=0; i<alist.length; i++) {
System.out.println(alist[i]);
}
}
The part I am must stuck on is comparing the strings lexicographically. Currently, I have my code setup so that I enter a while-loop and compare each char.
My question is, is this the most efficient way to do this, or is there a better way to compare each string lexicographically in the cases where the strings are the same length?
Following the suggestions of Tunaki and JB Nizet, you can use Integer.compare and String.compareTo. Using String.compareTo does not count as recursion. Recursion is when you call a method from itself, but String.compareTo is a different method from AltString.compareTo.
public int compareTo(AltString altStr2) {
int temp = Integer.compare(this.internalStr.length(), altStr2.internalStr.length());
return temp != 0 ? temp : this.internalStr.compareTo(altStr2.internalStr);
}
I am trying to create a dictionary out of a .txt file.The problem I think is in my addToDict method. I am trying to resize th array when its full because I am reading from a text file of unknown size but I can only use arrays. I get an out of bounds exception when I am printing the array. I have no idea whats wrong and I have been working on the project for days now. I am also having trouble with my else statement in my addToDict method. It is also and out of bounds exception
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict {
static String dict[] = new String[20];
static int index = 0;
public static void main(String args[]) {
readIn();
}
public static void readIn() {
File inFile = new File("alice.txt");
try {
Scanner scan = new Scanner(inFile);
while (scan.hasNext()) {
String word = scan.next();
if (!Character.isUpperCase(word.charAt(0))) {
checkRegex(word);
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void addToDict(String word) {
if (index == dict.length) {
String newAr[] = new String[index * 2];
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
dict = newAr;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
} else {
dict[index] = word;
index++;
}
}
public static void checkRegex(String word) {
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if (!regexMatcher.find()) {
addToDict(word);
}
}
}
You haven't assigned the new array to dict.
if (index == dict.length) {
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
// Assign dict to the new array.
dict = newAr;
} else {
dict[index] = word;
index++;
}
The value of index is 0 when the following statement is executed.
String newAr[] = new String[index*2];
Try revisiting your logic. index should be given a positive value before this method is called. That's why you are getting OutOfBounds.
EDIT: Did you mean to write index+2?
You have
static int index = 0;
You need to change the value of this variable, based on your file, otherwise you will always have an error in this line
String newAr[] = new String[index*2];
Instead of using a array use a arraylist for when you don't know the size of your array. It will save you a lot of trouble. I find they are much easier to work with in general then normal arrays.
ArrayList<String> dict = new ArrayList<>();
dict.add(word);
//displaying values
for( int i = 0; i < dict.size(); i++ ){
System.out.println(dict.get(i));
}