Use of array list and String comparison [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to read the names from a array list and compare them using loops and print the values from the array in the list
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
int wordcount = 0;
Scanner input = new Scanner(new FileReader("Names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
}
}
System.out.println(wordcount);
}
}

Here is what you want:
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(new FileReader("Names.txt"));
Set<String> uniqueNames = new HashSet<String>();
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
uniqueNames.add(str[i]);
}
}
System.out.println(wordcount);
System.out.println(uniqueNames);
}
}
Using a set, it only adds the value you pass if it doesn't already exist in it.
Then you can print it out with println(uniqueNames); which will print out each element like so: "[name1, name2, name3, ..., nameN]"
To get rid of the brackets and commas, you can use this:
String str = uniqueNames.toString();
str = str.replace('[', '');
str = str.replace(']', '');
str = str.replace(',', '');
If you want to get each one on a new line, you can change replace(',', '') to: replace(',', '\n');

here you go, try to learn something from it :)
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(new FileReader("names.txt"));
// this is the arraylist to keep all the names from your file
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
// since some of the names have spaces at the end, we pass them
// trough a cleanup method to remove the spaces
String line = clearSpaces(input.nextLine());
// add the cleaned up names to the arraylist
names.add(line);
}
// loop through all the names in the array for comparisson
for (int c = 0; c < names.size(); c++) {
// set each name to be unique until proven otherwise
boolean unique = true;
// take the name out of the array to test
String testString = names.get(c);
// loop through all the other names in the array for comparisson
for (int i = 0; i < names.size(); i++) {
// only if the indexes are different the comparisson makes sense
if (i != c) {
// take the name out of the array to test against
String tempString = names.get(i);
// test the names against each other
if (testString.equals(tempString)) {
// if they are the same then it's not unique
unique = false;
// break the loop cause we already know it's not unique
break;
}
}
}
// only if the unique boolean value is still true
// after testing against all other names
if (unique)
// print the name of that unique name
System.out.println(testString);
}
}
// returns a string clean of spaces
private static String clearSpaces(String withSpaces) {
// string builder for the string output
StringBuilder withoutSpaces = new StringBuilder();
char[] chars = withSpaces.toCharArray();
// loop the array of characters
for (char c : chars) {
// if it's not equal to 32 which corresponds to space char
if (c != 32) {
// append it to the string builder
withoutSpaces.append(c);
}
}
// return all the chars as string
return withoutSpaces.toString();
}

Related

Inject character between substring of a string in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a list of words stored in a list, words.
private String[] words = new String[]{"world", "you"};
I then have a string, helloWorld
private String helloWorld = "Hello world how are you?";
I would like to create a function that will take a string (in this case, helloWorld) and it will look case-insensitively to see if any of the strings in the words list are present. If there is, it will put a * character in between each letter of the matching string.
E.g. the output would be
Hello w*o*r*l*d how are y*o*u? since both world and you are in the list.
Passing "Hello" would simply return back the unmodified string "Hello" because there is nothing in the string that is inside words.
How would I go about doing this? I have tried hardcoding a .replaceAll() call on the string for each word, but then I lose the casing of the string. E.g. "Hello world how are you?" became "hello w*o*r*l*d how are y*o*u?"
This code:
private static String[] words = new String[]{"world", "you"};
private static String helloWorld = "Hello world how are you?";
public static String getHello() {
String s = helloWorld;
for (String word : words) {
int index = s.toLowerCase().indexOf(word.toLowerCase());
if (index >= 0) {
String w = s.substring(index, index + word.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, index));
for (int i = 0; i < w.length(); i++) {
sb.append(w.charAt(i));
if (i < w.length() - 1)
sb.append("*");
}
sb.append(s.substring(index + w.length()));
s = sb.toString();
}
}
return s;
}
public static void main(String[] args) {
System.out.println(getHello());
}
prints:
Hello w*o*r*l*d how are y*o*u?
String helloWorld = "hello world how are you ";
String[] words = new String[]{"world", "you"};
String newWord = "";
String words1[]= helloWorld.split(" ");
for (int i = 0;i< words.length;i++){
for (int j=0;j<words1.length;j++){
if (words1[j].equals(words[i])){
for (int k = 0 ; k < words1[j].length(); k++){
char character = words1[j].charAt(k);
newWord+=character;
newWord += "*";
}
words1[j] = newWord;
newWord= "";
}
}
}
String str = Arrays.toString(words1);
System.out.println(str);
}

Array not accepting fourth input?

I'm getting an ArrayIndexOutOfBoundsException with this program and I can't figure out what the problem is. It allows the user to type 3 inputs but then just gives the error!
If anyone can see where I'm going wrong (I believe it's with the 'parts' after the .split(), but I need the delimiter) ...
public class SplittingStrings
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
//Sample input(not sorted the validation yet) "Chelsea : Arsenal : 2 : 1"
Scanner sc = new Scanner(System.in);
String results = sc.nextLine();
int count = -1;
String str = null;
String[] parts = new String[100];
parts = results.split(":");
String home_team = parts[0];
String away_team = parts[1];
String home_score = parts[2];
String away_score = parts[3];
String[] refinedArray = new String[parts.length];
for (int i = 0;i < 100; i++){
results= sc.nextLine();
for(String s : parts) {
if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
refinedArray[++count] = s; // Increments count and sets a value in the refined array
}
}
if(sc.equals("stop")) {
Arrays.stream(parts, 0, i).forEach(System.out::println);
}
parts[i] = str;
}
}
It is because of this statement: parts[i] = str. You change value of variable parts in this statement: parts = results.split(":"); so you change size of this array (possibly lesser than 100) and in the for loop you access to an element of this array which is not existed.
Creating an array of 100 elements was pointless
String[] parts = new String[100];
You overwrote it with an array of only 4 (?)
parts = results.split(":");
Your loop goes up to 100, but parts[4] throws the exception
It's not really clear what results is supposed to be, either

Converting an String array into char array to compare it with another text file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Given two files
random_letters.txt
AABBBBB
FLOWERS
BACKGFD
TOBEACH
dictionary.txt
flowers
to
beach
back
I need to check each combination of the random_letters with dictionary to see if there is anything common. it can be a word with at least 6 characters or two words that equal at least 6 characters. Which would make it FLOWERS or TOBEACH.
I am having a tough time figuring out what I need to do. I can get it to work for words with 7 characters because I used strings. I understand I need to use char in order for it to work.
what I have so far:
public static void compare() {
private static String stringToWrite2 = "";
private static String[] allWords = new String[2187];
private static String[] diction = new String[79765];
private static char[][] test = new char[2187][7];
private static char[][] test2 = new char[79765][7];
public static void main(String args[])
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords[i] = file1.next();
test[i] = allWords[i].toCharArray();
}
for(int i = 0; i < 79765; i++) {
diction[i] = file2.next();
diction[i] = diction[i].toUpperCase();
test2[i] = diction[i].toCharArray();
}
for(int i = 0; i < 2187; i++) {
for (int j = 0; j < 79765; j++) {
if(allWords[i].equals(diction[j])) {
stringToWrite2 += diction[j];
}
}
}
} catch (IOException e) {
System.out.println("could not find file");
}
System.out.println("-------------------");
System.out.println(stringToWrite2);
for(int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++)
System.out.println(test2[i][j]);
}
}}
You have two somewhat distinct tasks here: determining if there are any words in dictionary that are also in random_letters (of length >= 6), and determining if there are any sets of two words in dictionary such that their union is a word in random_letters.
Instead of using an array, let's use HashSets for storage, because the single most used operation here will probably be .contains(...). It also gives us access to .retainAll(...), which is very useful for finding intersections.
For the second half of the task, my initial thought was to create a data structure with all of the pairwise permutations of words in diction, and intersect that with allWords. I quickly realized how big that would (likely) become. Instead I used an uglier but more space efficient solution.
private static HashSet<String> allWords = new HashSet<String>();
private static HashSet<String> diction = new HashSet<String>();
public static void compare() {
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords.add(file1.next());
}
for(int i = 0; i < 79765; i++) {
diction.add(file2.next().toUpperCase());
}
//Compile set of words that are in both
HashSet<String> intersect = new HashSet<String>();
intersect.addAll(allWords);
intersect.retainAll(diction);
for (String s : intersect){
System.out.println(s);
}
//For every word in random_letters, see if there is a word in diction that is the start of it
HashSet<String> couplesIntersect = new HashSet<String>();
for(String s : allWords){
for(String d : diction){
if(s.startsWith(d)){
//If so, check every word in diction again to see if there is a word that is the remainder
String remainder = s.subString(d.length());
for(String d2 : diction){
if(d2.equals(remainder))
//If so, store this word
couplesIntersect.add(s);
}
}
}
}
//Print those results
for (String s : couplesIntersect){
System.out.println(s);
}
} catch (IOException e) {
System.out.println("could not find file");
}
}
}

Java program to print repeating characters in a string without duplicates in output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to Java. Today I was trying to do a Java program to print duplicate characters in a string in which output also should not have duplicates.
for example if string input is: "aabacdceefeg"
output should not have repeating characters
ie output should be: "ace" and should not not "aacee"
public class programclass {
private static Scanner s;
public static void main(String [] args) {
String n, a[];
int i,j,l;
System.out.println("Enter the string: ");
s= new Scanner(System.in);
n=s.nextLine();
a=n.split("");
l = a.length;
for(i=0; i<l; i++){
for(j=i+1; j<l; j++){
if(a[i].equals(a[j])) {
System.out.println(a[i]);
}
}
}
}
}
Please help me to correct this out.
Thanks in advance.
Here's a solution that sorts the string and then uses a regular expression to remove the duplicates:
String string = "aabacdceefeg";
char[] chars = string.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
String result = sorted.replaceAll("(.)\\1+", "$1");
I think a better strategy here would be to save each used character in a set and then check to see if the letter is in the set.
public class programclass {
private static Scanner s;
public static void main(String [] args) {
String n, a[];
int i,j,k,l;
Set<String> set = new HashSet<String>();
System.out.println("Enter the string: ");
s= new Scanner(System.in);
n=s.nextLine();
a=n.split("");
l = a.length;
for(i=0; i<l; i++){
if(set.contains(a[i])){
System.out.println(a[i]);
}
set.add(a[i]);
}
}
}
If you only want a repeated character to print out once, add another set to keep track of letters which have already been printed.
You may want to use a Set for this to get the job done.
here you go:
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class Sample {
private static Scanner s;
public static void main(String[] args) {
String n, a[];
int i, j, k, l;
System.out.println("Enter the string: ");
s = new Scanner(System.in);
n = s.nextLine();
a = n.split("");
l = a.length;
Set<String> noDupes = new LinkedHashSet<>();
StringBuilder sb = new StringBuilder();
for (i = 0; i < l; i++) {
noDupes.add(a[i]);
}
for (Iterator<String> it = noDupes.iterator(); it.hasNext();) {
String f = it.next();
sb.append(f);
}
System.out.println(sb.toString());
}
}

is binary search more relevant while searching for a word in dictionary? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have written a algorithm that searches for a word in dictionary. But it searches only with 1 or 2 letters of a specified length of word.
Ex search:-
A**
result should be:-
Aid, Aim,
I have used linear search algorithm to find the words that matches my criteria. But i want to know if Binary search can be used instead of linear search? if so then can any one please give me some hint about it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Cse221LabAssignment1 {
/**
* #param args the command line arguments
*/
public static final String wordListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\WordList.txt";
public static final String searchListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\SearchList.txt";
public static void main(String[] args) {
// TODO code application logic here
String wordList, searchList;
wordList = ReadFile(wordListFileName); //Reading wordlist
searchList = ReadFile(searchListFileName); //Reading searchList
String[] w = wordList.split("\\,"); //Spliting wordlist and putting it into an array
String[] s = searchList.split("\\,"); //Spliting searchList and putting it into an array
for (int c = 0; c < s.length; c++) { //iterating through the searchList array
// String [] refinedList=new String[w.length]; //array containing the list of words that matches with the lenght of search word.
// int refinedCounter=0; //counter for the refinedList array
for (int i = 0; i < w.length; i++) { //iterating through the wordList array
if (s[c].length() == w[i].length()) {
// refinedList[refinedCounter]=w[i];
// refinedCounter++;
if (LetterMatch(w[i], s[c])) {
System.out.print(w[i]);
if (i < w.length - 1) {
System.out.print(",");
} else {
System.out.println(";");
}
}
}
}
}
}
public static String ReadFile(String fileName) {
Scanner k = null;
try {
k = new Scanner(new File(fileName));
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
String rt = k.nextLine();
while (k.hasNextLine()) {
rt = rt + "," + k.nextLine(); //Words seperated by Comma
}
return rt;
}
public static boolean LetterMatch(String m, String s) {
char[] letters = m.toCharArray();
char[] searchLetters = s.toCharArray();
boolean match = false;
int c = 0;
for (; c < s.length(); c++) {
if (searchLetters[c] != '*') {
if (searchLetters[c] == letters[c]) {
match = true;
} else {
match = false;
}
}
}
if (c != s.length()) {
return false;
} else {
return match;
}
}
}
I would recommend using an alternative data structure to help you do some of the heavy lifting. Try a radix tree http://en.wikipedia.org/wiki/Radix_tree. This will let you complete the words as you traverse the tree opposed to having to do linear list searches.

Categories