difficulty in List iteration and comparison in java - 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.

Related

How can I insert data from multiple Access rows into a single, multi-lined string in Java

I am trying to get data from a result set into my java application so that I can display it to the user. Something I'd like to implement is a partial search function that displays multiple rows of data based on an input string. If that string appears in any serial number in the database, it pulls that entire row and adds it to a string.
res is the ResultSet
public String searchToString() {
String temp = "";
try {
while(res.next()) {
temp = res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
} catch (SQLException se) {
System.out.println(se);
}
return temp;
}
I have tried changing the queries I use and figured out that the LIKE query was the best one. However, if I try outputting the string to a text area I only see one output where many more are supposed to be. I am definitely missing something from my code to tell it to continue adding the rest of the rows to the string, but I haven't come across anything on the Internet that can tell me what it is.
You are overwriting temp
//try +=
temp += res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}
//or temp = temp +
temp = temp + res.getString("ProductCode") + " " + res.getString("SerialNum") + " "
+ res.getString("DateSold") + " " + res.getString("SoldTo") + " " + res.getString("Notes") + "\n";
}

how to delete empty line and rest of the character in java

I want to delete empty line and rest of the character from my string, I would like to parse particular value alone from the string.
I want this value alone 23243232 from my string, after product price I've have empty line space and again I've some character so I'm using that empty line as delimiter and trying to get product price alone. But I'm getting other values also along with 23243232. Can someone help me to get only 23243232 from this string
String actualResponse = "--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String productPrice = actualResponse.substring(actualResponse.lastIndexOf("Product-Price:") + 15);
System.out.println("Printing product price ..." + productPrice);
String finalString = productPrice.replaceAll(" .*", "");
This is the output I'm getting:
Printing product price ...23243232
%dsafdfw32.323efaeed
#$#####
But I want only 23243232 - this value alone.
Apply Regular Expression for more flexibility.
String content = "--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String re1 = "\\bProduct-Price:\\s"; // Word 1
String re2 = "(\\d+)"; // Integer Number 1
Pattern p = Pattern.compile(re1 + re2, Pattern.DOTALL);
Matcher m = p.matcher(content);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
System.out.println(String.format("Group=%d | Value=%s",i, m.group(i)));
}
}
It will print out:
Group=0 | Value=Product-Price: 23243232
Group=1 | Value=23243232
first solution came in my mind. its not the best but will solve your problem.
StringBuilder finalString =new StringBuilder();
for (Character c : productPrice.toCharArray()) {
if(Character.isDigit(c)){
finalString.append(c);
}else{
break;
}
}
This is because you are printing the entire sub-string right from index: actualResponse.lastIndexOf("Product-Price:") + 15 to the end of the string.
You need to provide the end index too as a second parameter in substring method.
You need to use this:
int start = actualResponse.lastIndexOf("Product-Price:") + 15;
int end = actualResponse.indexOf("\r\n", start); // The first "\r\n" from the index `start`
String productPrice = actualResponse.substring(start, end);
This will give your final ans...
String actualResponse ="--sGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArwzoF_yDmmW5DfupJDtuHlh20LL2SAbWZb8a3exzoF_y DmmW5DfupJDtuHlh20LL2SAbWZb8a3exsGEFoZV85Qnkco_QAU5b6B3Tt1OrOOFkArw\r\n"
+ "Product-Discription: form-name; productName=\"iPhone\"\r\n" + "Product-Type: Mobile\r\n"
+ "Product-Price: 23243232\r\n" + "\r\n" + "%dsafdfw32.323efaeed\r\n" + "#$#####";
String productPrice = actualResponse.substring(actualResponse.lastIndexOf("Product-Price:") + 15);
System.out.println("Printing content lenght..." + productPrice.split("\r\n")[0]);

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);
}

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

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";

Putting user created variables inside of an array

I want to put what the use puts in for x to be stored in the yourNumbers array, how would I do that? Edit: How would I clean up the println parts at the bottom, using loops.
import java.util.Scanner;
public class array {
public class SS_Un8As1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] yourNumbers = new int[10];
for (int counter=0; counter < yourNumbers.length; counter++){
System.out.print("Enter your number: ");
yourNumbers[counter] = scan.nextInt();
}
System.out.println("Original numbers: " + yourNumbers[0] + "," + yourNumbers[1] + "," + yourNumbers[2] + "," + yourNumbers[3] + "," + yourNumbers[4] + "," + yourNumbers[5] + "," + yourNumbers[6] + "," + yourNumbers[7] + "," + yourNumbers[8] + "," + yourNumbers[9]);
System.out.println("Original numbers multiplied by five: " + yourNumbers[0]*5 + "," + yourNumbers[1]*5 + "," + yourNumbers[2]*5 + "," + yourNumbers[3]*5 + "," + yourNumbers[4]*5 + "," + yourNumbers[5]*5 + "," + yourNumbers[6]*5 + "," + yourNumbers[7]*5 + "," + yourNumbers[8]*5 + "," + yourNumbers[9]*5);
System.out.println("Original numbers minus the next number: " + (yourNumbers[0]-yourNumbers[1]) + "," + (yourNumbers[1]-yourNumbers[2]) + "," + (yourNumbers[2]-yourNumbers[3]) + "," + (yourNumbers[3]-yourNumbers[4]) + "," + (yourNumbers[4]-yourNumbers[5]) + "," + (yourNumbers[5]-yourNumbers[6]) + "," + (yourNumbers[6]-yourNumbers[7]) + "," + (yourNumbers[7]-yourNumbers[8]) + "," + (yourNumbers[8]-yourNumbers[9]) + "," + (yourNumbers[9]-yourNumbers[0]));
}
}
Like this:
yourNumbers[counter] = x;
The above code is stating: store the value of x in the array yourNumbers in the index (position) counter. Because counter is the iteration variable of a for loop, each time the loop advances the counter the next value of x will be stored in the next available position in the array.
You must make sure that the length of the array is the same as the value of counter. In your code, do this:
int[] yourNumbers = new int[10];
Why? because counter goes from 0 to 9, so the array must be of length 10.
replace this
int x = scan.nextInt();
with
yourNumbers[counter] = scan.nextInt();
also, the condition should be counter<9, or better counter<yourNumbers.length
Simply pass the input into the next element of the array, while inside the for loop:
yourNumbers[counter] = x;
I should also point out, however, that you should validate that your input is actually an integer before assigning x the value. If the value isn't an integer, your program will crash.

Categories