How do I find a specific string on a bigger string? - java

I am trying to get rid of multiple specific strings. For instance, I have a string that prints:
1.jedi
2.sith
3.sith
4.sith
5.bounty hunter
6.jedi
7.sith
8.robot
My goal is to remove duplicates so that it prints:
jedi
sith
bounty hunter
robot
If I change one of the jedi to "something jedi.", it will not print "something jedi."
Output should be:
1.jedi
2.sith
3.bounty hunter
4.robot
5.something jedi
Right now I am using this code to achieve the task of removing duplicates.
if (department.contains(departmentList.get(empName))){
}
else{
department += j + ": " + departmentList.get(empName) + "\n";
j++;
}
I understand where the mistake is. Since I am using .contains(VARIABLE), when it checks "something jedi" it will find that the word JEDI is already there. therefore it returns true and it won't add it to the department.

Create a set to contain the full names of the departments already output. Each time you want to output a department, check if the set contains it already. If not, then output the department name and add it to the set.
For example:
Set<String> usedDepartments = new HashSet<String>();
Then in your loop:
if(!usedDepartments.contains(departmentList.get(empName))) {
department += j + ": " + departmentList.get(empName) + "\n";
j++;
usedDepartments.add(departmentList.get(empName));
}

As your department's value:
department += j + ": " + departmentList.get(empName) + "\n";
You may change your IF statement:
if (department.contains(": " + departmentList.get(empName) + "\n"))
SUPPOSE:
department = "1: something jedi.\n";
departmentList.get(empName) = "jedi.";
department.contains(": " + departmentList.get(empName) + "\n"); // will return false

Firstly, split your String into Link.
Secondly, make a Set from it, so it will delete all the repetitions.

department should be a Set<String>, not a String:
Set<String> departments = new HashSet<String>();
then every loop:
departments.add(departmentList.get(empName));
and after the loop:
int i = 0;
String output = "";
for (String s : departments)
output += i + ": " + s + "\n";

Related

I'm not getting the correct key for the value in my code using LinkedHashMap

Hi so I'm stuck here please if someone could help me please I try to explain here the best I can.
Code is working fine but it's false.
So I highlighted down (in bold) in the example where the problem is and commented in yellow what should be right for my code.
The values of my LinkedHashMap:
(String, String)
cards.put("a", "1");
cards.put("b", "2");
cards.put("c", "3");
cards.put("d", "4");`
Code in action example:
Print the definition of "a"
input> 1
Correct answer
Print the definition of "b"
input> a
Wrong answer
Print the definition of "c"
input> 2
Wrong answer. The correct one is "3", you've just written the definition of "c"
//Here it should be "b" since input was 2 and 2 is the value of key b
in the map.
Print the definition of **"c"
//should be "b" here too then it goes all wrong it doesn't match the correct
key
input> 3
Correct answer
Print the definition of "d"
input> 1
Wrong answer. The correct one is "4", you've just written the definition of "d"
Print the definition of "d"
and here it prints "d" instead of "a"
and I tried a lot of things can't know how to fix this.
input> 1
Correct answer
And here is the code source:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedHashMap<String, String> cards = new LinkedHashMap<String, String>();
cards.put("a", "1");
cards.put("b", "2");
cards.put("c", "3");
cards.put("d", "4");
for (Map.Entry<String, String> entry : cards.entrySet()) {
String v = entry.getValue();
String k = entry.getKey();
System.out.println("Print the definition of " + "\"" + k + "\"");
String answer = in.nextLine();
if (answer.equals(v)) {
System.out.println("Correct answer");
} else if (!answer.equals(v) && !cards.containsValue(answer)) {
System.out.println("Wrong answer");
}
else if (!answer.equals(v) && cards.containsValue(answer)) {
System.out.println("Wrong answer. The correct one is " + "\"" + v + "\""
+ ", you've just written the definition of " + "\"" + k + "\"");
System.out.println("Print the definition of " + "\"" + k + "\"");
String answer2 = in.nextLine();
if (!answer2.equals(v) && !cards.containsValue(answer2)) {
System.out.println("Wrong answer. The correct one is " + "\"" + v + "\"");
} else {
System.out.println("Correct answer");
}
}
}
}
System.out.println("Wrong answer. The correct one is " + "\"" + v + "\""
+ ", you've just written the definition of " + "\"" + k + "\"");
instead of k, you shall get actual key for the entered value and print that.

Printing an array list with duplicate entries

Im storing names in a array list logcall and printing them out accordingly. But when there are duplicates how do I only print them once rather than however many times they're in the array list?
public static void displayHistory()
{
for(Call allCalls : logCall)
{
if(logCall!=null)
{
String name = allCalls.getName();
Long phone = allCalls.getPhoneNumber();
String type = allCalls.getType();
String time = allCalls.getTime();
String date = allCalls.getDate();
String phoneStr = Long.toString(phone);
if(name.equals("N/A"))
{
System.out.println( PhoneBook.formatNum(phoneStr) + " (" + type + ") " +date + " " + time);
}
else if(search(name) > 1)
{
System.out.println( name + " (" +search(name)+ ") " );
}
else
{
System.out.println( name + " (" + type + ") " + date + " " + time);
}
}
}
A quick thought I had would be to store your output in a string and use the string's .contains method to search for duplicates before adding a new entry. Then you would just print the output string at the very end.
Use a HashSet. This is far more efficient than checking it in a string as Logan Kulinski says, as checking in a string takes N operations, and the complexity will be N^2.
For example,
Collection<String> seen = new HashSet<String>();
for (.....) { //process the items here
//format the stuff and what not
if (!seen.contains(currentString)) {
seen.add(currentString);
print(currentString);
}

Counting most freq. user in an array

int totalEnrolled = studentEnrollments.size();
String mostFreqUser = "";
int count = 0;
System.out
.println("~~~~~~~~~~~~~~~Spring 2016 Enrollment~~~~~~~~~~~~~~~");
for (String userName : studentEnrollments.keySet()) {
System.out.println("Student: " + userName);
ArrayList<String> courses = studentEnrollments.get(userName);
String courseMessage = "Courses: ";
String seperator = "";
// looping through courses
for (String singleCourse : courses) {
// counting how many courses were enrolled
count++;
courseMessage += seperator += singleCourse;
System.out.println(courseMessage);
seperator = ",";
}
}
System.out.println("Total students enrolled: " + totalEnrolled);
System.out.println("Total courses enrolled: " + count);
System.out.println(mostFreqUser);
}
}
Hello, I was wondering how would I make a counter for the most frequent user. Everytime the for loop runs It would calculate who put there username the most. Also one more thing, how come the output prints multiple courses not just one for each name. For example instead of printing a course line for each courses it prints it twice.
for example the expected output looks like
Student: josh
Courses: cs170, cs180
but the output looks like
Student: josh
Courses:cs170
Courses:cs170,cs170
Thank you, please let me know if you need any more details.
Move the print statement outside the inner for loop.
Note: It's spelled "separator".
Don't do a chained +=.
NOTE: If you see the same course name listed multiple times for a student, then your studentEnrollments Map-List is likely wrong, not your displayed code.
The following code also shows how to find the student with the largest number of courses (aka the "mostFreqUser"). There can of course be more than one student with that many courses, but only the first is shown.
System.out.println("~~~~~~~~~~~~~~~Spring 2016 Enrollment~~~~~~~~~~~~~~~");
int courseTotal = 0;
int maxCourseCount = 0;
String maxCourseStudent = "";
for (String student : studentEnrollments.keySet()) {
System.out.println("Student: " + student);
ArrayList<String> courses = studentEnrollments.get(student);
String courseMessage = "Courses: ";
String separator = "";
for (String course : courses) {
courseMessage = courseMessage + separator + course;
separator = ",";
}
System.out.println(courseMessage);
courseTotal += courses.size();
if (courses.size() > maxCourseCount) {
maxCourseCount = courses.size();
maxCourseStudent = student;
}
}
System.out.println("Total students enrolled: " + studentEnrollments.size());
System.out.println("Total courses enrolled: " + count);
System.out.println("Most frequent student: " + maxCourseStudent + " (enrolled in " + maxCourseCount + " courses)");
For the first part you can use a Hashtable. Initialize your hashtable with a value of 1 whenever a user is seen for the first time. Subsequently, increment the hashtable count if a user is seen again. Finally, go through each element of the hashtable to find the largest value.
For the second part, you need to bring the second print statement outside of the for loop.
You are printing courseMessage in course loop. So it will print courseMessage for each course in course collection. That is why you're getting two inputs.
Also following statement will affect your output
courseMessage += seperator += singleCourse;
This should be written as
courseMessage += seperator + singleCourse;
DEMO FOR += PROBLEM
Suppose we have two courses in our list say cs150 and cs160.Initially,
courseMessage = "Courses : ";
separator = "";
For first course, cs150,
courseMessage += separator += singleCourse;
=>
couresMessage += separator = separator + "cs150";
=>
courseMessage += separator = "cs150";
=>
courseMessage += "cs150";
=> courseMessage = "Courses : cs150";
So after first iteration, courseMessage will be Courses : cs150 and separator will be cs150.
Here you modifies value of separator accidentally, which will reflect in consequent iteration and you will get unexpected output.

Recursion depth - tabs & dents in Java

I want to format my output of a Java program so that I can see "how deep" the recursion is. How to do it?
It is really important not to get lost in my recursion tree.
Example output (trivial recursion function for counting the nth number from 0):
This is the first recursive call. Input value: 3.
This is the second recursive call. Input value: 2.
This is the 3rd recursive call. Input value: 1.
Output value : 1.
This is again the second recursive call. Input value: 2.
Output value : 1 + 1.
This is again the first recursive call. Input value: 3.
Output value : 1 + 1 + 1.
You can use a variable (like level) that represents how deep you are. It starts at 1 and it increments at each recursive call.
public static void main(String[] args) {
function(3, 1);
}
public static String function(int input, int level) {
String tab = "";
for (int i = 0; i < level - 1; i++) {
tab += "\t";
}
System.out.println(tab + "This is the " + level + " recursive call. Input value: " + input);
if (input == 1) {
System.out.println(tab + "Output value: 1");
return "1";
}
String output = function(input - 1, level + 1);
System.out.println(tab + "This is again the " + level + " recursive call. Input value: " + input);
System.out.println(tab + "Output value: " + output + " + 1");
return output + " + 1";
}
Well, if you're using System.out.println, than you should be able to use "\tThis is the..." to indent the line on most java output windows. I don't understand if this is what you're asking for though.
If you don't know which recursion you're in, than you'd have to crawl Thread.currentThread().getStackTrace().
String s = "";
while(numRecursions --> 0) s += "\t";
System.out.println(s + "Something something something")
Again, if you don't have a numRecursions variable than you'd have to do something like this
int numRecursions = 0;
void a(){
int temp = ++ numRecursions;
String s = "";
while(temp --> 0) s += "\t";
System.out.println(s + "This is a recursion level");
//code
numRecursions--;
}
In your output function include a prefix string argument.
Every time you call your function pass in prefix + " ".
Example:
public void output(String prefix){
// Whenever you print, start with prefix
System.out.println(prefix + ...);
// When you call your recursive method
String childPrefix = prefix+" ";
output(childPrefix);
}

difficulty in List iteration and comparison in java

I have 2 list List<String> existingGuesses which contains characters and List<String> word = new ArrayList<String>(words) which contains words which is a copy of list words as shown in my code below. What I am trying to do is to iterate through all the words of List word and iterate through the characters of list existingGuesses. Then I want to compare the first character of List existingGuesses with all the words of List word one by one and if a match is found then I want to remove the word from the list. Then the same for next character and continue until there are no more words left to compare. Until now, I could only declare a iterator, it's not necessary to use iterator but I don't know any other ways. My code is as follows:
public List<String> getWordOptions(List<String> existingGuesses, String newGuess)
{
List<String> word = new ArrayList<String>(words);
String c = existingGuesses.get(0); //trying to get the first character
ListIterator<String> iterator = word.listIterator(); //iterator to iterate thorugh word list
while(iterator.hasNext())
{
if(word.contains(c)) //trying to compare
{
word.remove(c);
}
}
return null;
}
Can anybody help me out? The original List words is:
private List<String> words = new ArrayList<String>() {
{
// DO NOT CHANGE THESE WORDS!
String w =
"sentence\n"
+ "together\n"
+ "children\n"
+ "mountain\n"
+ "chipmunk\n"
+ "crashing\n"
+ "drinking\n"
+ "insisted\n"
+ "insulted\n"
+ "invented\n"
+ "squinted\n"
+ "standing\n"
+ "swishing\n"
+ "talented\n"
+ "whiplash\n"
+ "complain\n"
+ "granddad\n"
+ "sprinkle\n"
+ "surprise\n"
+ "umbrella\n"
+ "anything\n"
+ "anywhere\n"
+ "baseball\n"
+ "birthday\n"
+ "bluebird\n"
+ "cheerful\n"
+ "colorful\n"
+ "daylight\n"
+ "doghouse\n"
+ "driveway\n"
+ "everyone\n"
+ "faithful\n"
+ "flagpole\n"
+ "graceful\n"
+ "grateful\n"
+ "homemade\n"
+ "homework\n"
+ "housefly\n"
+ "kickball\n"
+ "kingfish\n"
+ "knockout\n"
+ "knothole\n"
+ "lipstick\n"
+ "lunchbox\n"
+ "newscast\n"
+ "nickname\n"
+ "peaceful\n"
+ "sailboat\n"
+ "saturday\n"
+ "shameful\n"
+ "sidewalk\n"
+ "snowball\n"
+ "splendid\n"
+ "suitcase\n"
+ "sunblock\n"
+ "sunshine\n"
+ "swimming\n"
+ "thankful\n"
+ "thinnest\n"
+ "thursday\n"
+ "whatever\n"
+ "whenever\n"
+ "windmill\n"
+ "american\n"
+ "possible\n"
+ "suddenly\n"
+ "airplane\n"
+ "alphabet\n"
+ "bathroom\n"
+ "favorite\n"
+ "medicine\n"
+ "december\n"
+ "dinosaur\n"
+ "elephant\n"
+ "February\n"
+ "football\n"
+ "forehead\n"
+ "headache\n"
+ "hospital\n"
+ "lollipop\n"
+ "november\n"
+ "outdoors\n"
+ "question\n"
+ "railroad\n"
+ "remember\n"
+ "sandwich\n"
+ "scissors\n"
+ "shoulder\n"
+ "softball\n"
+ "tomorrow\n"
+ "upstairs\n"
+ "vacation\n"
+ "restroom";
addAll(Arrays.asList(w.split("\\s+")));
}
};
Some points to consider:
String c = existingGuesses.get(0); //trying to get the first character
gets the first word in a list of words, not the first character.
To get the first character in a String you can do this:
char c = newguess.getCharAt(0);
Then you can search through the list for words starting with that character. Next you do not want to remove words that contain the character, you want to remove words that start with the character.
Also, you want to get each item from the iterator one at a time:
while(iterator.hasNext()){
String w = iterator.next(); //get the next word in the iterator here
//process w here
}
You seem to want to find if the characters correspond. That is, if the guess is "foo" then you want to remove all words that start with f, and all words that has the second character o and all words that have the third character o. That seem a little strange so you may want to check your logic.
Your method seem to be referring to some global variables and that could be causing you some confusion.

Categories