This is a method in a spell checker. As the header explains, it should return true if and only if all the words added to the arraylist are found in the parent array, words. Otherwise it should return a false value. I've been fighting with this for a few hours and this is my current situation...
/**
* This method returns true if (and only if) all words in the
* given wordList are found in the dictionary.
*/
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size(); index++)
{
if(words.contains(!wordList.contains(index)))
{
result = false;
}
result = true;
}
return result;
}
All I really need is a way to turn out a yes or no, but I'm lost.
Please try and work with the code given as this is an exercise to teach that code.
Thanks!
Your problem is here:
if(words.contains(!wordList.contains(index)))
!wordList.contains(index) is a boolean expression, so it always evaluates to either true or false. So you're actually checking if the words list contains true or false, not the word like you want. Replace it with if(!words.contains(wordList.get(index)) to check if the current word is found in the dictionary.
I would suggest a following solution: iterate wordList word by word, and for each word check if it's found in the dictionary. If not so, return false immediately. If you reach the end of the loop, return true.
Here could be another solution:
public static boolean allKnown(List<String> parent, List<String> child) {
List<String> temp = new ArrayList<String>(child);
temp.removeAll(parent);
return temp.isEmpty();
}
For example:
List<String> parent = Arrays.asList("w1", "w2", "w3", "w4");
List<String> childOk = Arrays.asList("w1", "w4");
List<String> childKo = Arrays.asList("w1", "xx");
System.out.println(allKnown(parent, childOk));
System.out.println(allKnown(parent, childKo));
Prints:
true
false
Take out result = true; - you don't want to reset the value to true at every step in the loop.
Also change wordList.contains to wordList.get (because you want to get the word at a specific index, not check if it's contained in wordList) and move the ! out (because you can't 'not' a string).
And you can also optimize by checking result's value in the for-loop condition (or simply returning directly in the if-statement).
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size() && result; index++)
{
if(!words.contains(wordList.get(index)))
{
result = false;
}
}
return result;
}
If words really is an array and not an ArrayList, it doesn't have a contains method, you'll have to either have a double for-loop, or convert it to a list:
List<String> parentWords = Arrays.asList(words);
...
if (parentWords.contains(...))
Don't reset result to true after your if. Because like this the whole function will always return true.
A few tips:
Don't use ArrayList as a method parameter, always use the more abstract List (none of your code depends on ArrayList, so you can change the implementation later, if you like).
Iterate over List objects using the simplified syntax shown below.
You only need one word to be not in the words list to return false, so do exactly that (as shown below).
public boolean allKnown(List<String> wordList) {
for (String word : wordList) {
if (!words.contains(word)) {
return false;
}
}
return true;
}
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(String word : wordList)
{
if(!words.contains(word))
{
result = false;
}
}
return result;
}
Here is a simpler version :
public boolean allKnown(List<String> wordList) {
List<String> wordListCopy = new ArrayList<String>(wordList);
return !wordListCopy.retainAll(words);
}
PS : retainAll() removes from you wordList all of its elements that are not contained in you dictionnary. This method return true if your wordList changed as a result of the call (after removing the non existing element), in other word, this method return false when all your wordList elements exists in you dictionnary.
Related
trying to check if the letters of the word are sorted alphabetically.but i don't get any return from the method.
import java.util.Scanner;
public class A284 {
//Write a Java program to check
// if each letter of a given word (Abecadrian word) is less than the one before it.
public static boolean abecidarianWord(String word){
int index=word.length()-1;
for(int i=0;i<index;i++){
if (word.charAt(i)<=word.charAt(i+1)){
return true;
}else return false;
}
return true;
}
public static void main(String[] args) {
String entry;
System.out.println("input a word: ");
Scanner s1=new Scanner(System.in);
entry=s1.next();
abecidarianWord(entry);
}
}
You have two problems here.
First, you're not using the value returned from abecidarianWord, you're just calling it and ignoring the result, so you have no way of knowing what the method will return. So you should assign the return value to a variable and do something with it. For example, at the end of your main a naive implementation would do something like:
boolean isOrdered = abecidarianWord(entry);
if (isOrdered) {
System.out.println("String is ordered");
} else {
System.out.println("String is not ordered");
}
Second, in abecidarianWord you're returning immediately after the first iteration of the loop, which will only tell you if your condition holds true for the first two characters.
Instead you may want to return false as soon as you find a pair that doesn't respect the condition and return true if you reach the end of the loop without "accidents", so something like:
public static boolean abecidarianWord(String word) {
for (int i=0; i < word.length -1; i++) {
if (word.charAt(i) > word.charAt(i+1)) {
return false;
}
}
return true;
}
You have successfully returned the value.
import java.util.Scanner;
public class A284 {
public static boolean abecidarianWord(String word){
//you are getting length of "word" here
int index=word.length()-1;
for(int i=0;i<index;i++){
if (word.charAt(i)<=word.charAt(i+1)){
//If condition are correct return true.
return true;
}else{
//If condition are incorrect return false
return false;
}
}
return true;
}
public static void main(String[] args) {
String entry;
//Printing a text
System.out.println("input a word: ");
//getting values from user
Scanner s1=new Scanner(System.in);
entry=s1.next();
//calling a class
abecidarianWord(entry);
//You have get the value. But, you are actually trying to say that why it's not printing in output. When you return something you have to put them in another function to print-out
System.out.println(abecidarianWord(entry));
//If you don't wanna do it than you have to write SOUT instead of return. Than you can output the way you wrote
}
}
You are returning true on first comparison, so your loop only runs once. Instead, change your if condition inside for loop as below.
if (word.charAt(i)>word.charAt(i+1)){
return false;
}
#Istiak is perfectly right.
But just for optimizing your code to do what I think you would ideally want, I just wanted to say that the if statement -> if (word.charAt(i)<=word.charAt(i+1)) iterates for every two charecters in the word and you don't want to return true if just two letters are in order, Ideally replace return true; with just an empty ; otherwise your function will stop immediately after it finds a pair of two consecutive correctly placed letters.
I have an unexpected issue when using a conditional operator in java.
The code is supposed to check if the ArrayList contains a specific string, then it returns true or false. It is not the first time I do this, but for some reason there's something wrong.
This is my code so far:
public boolean isDone() {
ArrayList<String> al = new ArrayList<String>(); //Defining ArrayList
al.add(d1.getText()); // Adding the text from JLabels.
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
if(al.contains(".")) {
return false;
} else {
return true;
}
The issue is that when running the debugger, it should return falseand instead of that, it returnstrue. For some reason the conditional is not "reading" the content of the ArrayList, or stuff like that.
As you see, the ArrayList contains the . that needs the conditional to return false, but instead of that, it returns true. What is wrong in my code?
Try this:
public boolean isDone() {
ArrayList<String> al = new ArrayList<String>();
al.add(d1.getText());
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
for (String str : al)
if (str != null && str.contains("."))
return false;
return true;
}
You have to check each string individually, the contains() method in ArrayList will return true only if the exact string "." is present in the list, not if one of the strings in the list contains a dot.
When you use a1.contains(...), you are checking if any sting in array is ".". This is different from your intention to check if any string in array "a1" contains '.' char as I understand.
If you need to check if any string in array contains "." text it can be like this:
for(String text : a1) {
if(text != null && text.indexOf(".") >= 0) {
return false;
}
}
return true;
Your List<String> does not contain the String that equals ".". You have a String that contains a . but that is not the same thing. You can do that with String.contains(CharSequence),
public boolean isDone() {
List<String> al = new ArrayList<String>(); // <-- I would use the Interface type
al.add(d1.getText());
al.add(d2.getText());
al.add(d3.getText());
al.add(d4.getText());
al.add(d5.getText());
// If any String in al contains a '.' return false, else true.
for (String str : al) {
if (str.contains(".")) {
return false;
}
}
return true;
}
I have an issue where I am trying to compare an object's name (String) to another String, and I've tried using .equals() as well as == but neither seem to work in my case.
The code I have right now is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
else
{
return false;
}
}
}
The program always returns false, even if the name that has been set to product[i] is the same as the parameter given. I've tried looking at other questions relating to .equals() and == and other String references but I have not had any luck in finding something that relates to my problem.
I have seen people use compareTo(), but I'm not sure if that is necessary in my code, and I'm not completely sure on how to use it.
EDIT: As said by Houssni in the comments, I have just realised that the return statement ends the loop and method. Is it possible to check each product's name without having the method terminated after the first check, and have it return a boolean value?
EDIT 2: I have modified the code to how the answers that have been provided say, which is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
I still get the same issue with the product[i].getName() not being equal to checkName and the method returning false, even though they should equal. Any possibilities on why this is happening, because I've looked through my code and I'm not sure.
Edit 3: The only other code that relates to the block of code above is the input of the parameter from another class, which is:
String checkName = JOptionPane.showInputDialog("Enter the name: ");
while (storingProducts.checkingObjectName(checkName) == false) //assume for storingProducts
{
JOptionPane.showMessageDialog(null, "No products were found. Please re-input name.");
checkName = JOptionPane.showInputDialog("Enter the name: ");
storingProducts.checkingObjectName(checkName);
}
if (storingProducts.checkingObjectName(checkName) == true)
//extra code
So, that's all the code relating to my issue. I'm still not sure why the method returns false, though both values are receiving the same String value.
Edit 4: The product and count are coming from the class with the checkingObjectName method:
public class Store
{
private Product[] product; //Product is another class that just sets and gets
private int count=3;
public Store()
{
product = new Product[count];
for (int i=0; i<count; i++)
{
product[i] = new Product();
}
//extra code
SOLUTION
I fixed the issue: instead of using .equals(), I tried using .equalsIgnoreCase() and it worked.
The method is returning as soon as it hits count 0 and it doesn't find a match. If you want to loop through your array until you find a matching name, your code should look like this:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
There are two ways to compare strings:
The first is to compare via addresses of the string. Such as: string blue = string red.
The second way to compare strings is through values. This can be done by using the string.equals("StringValue").
Since you have a return statement that will be reached on every posible situation (if condition is true or false), the method will always exit on the first iteration.
What can you do? If you want to return true if the name exists in the array and false otherwise, you can do:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName))
return true;
}
return false; // if after all elements has been checked
// and none was equal to 'checkName', return 'false'
}
How about collecting the names into a List (or Set) and check if checkName matches?
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName());
}
return productNames.contains(checkName);
}
Note that this will only work if you're comparing case-sensitive strings. Alternatively,
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName().toLowerCase());
}
return productNames.contains(checkName.toLowerCase());
}
If you do not like this approach, you can use the ones given already, and replace equals with equalsIgnoreCase.
I'm writing a code that looks through a given array list named values and returns True if found i've gotten it to work for a for-loop and a while-loop but can't figure out how to get the for-each loop to work. Here is what i have that'd giving me the error.
EDIT: the error says "java.lang.IndexOutOfBoundsException: Index:642327, Size 30590 (in java.util.ArrayList)
public String twoforEachFoundIt(ArrayList<Integer> values, int number){
for(int i:values) {
if (values.get(i)== number){
return "True";
}
}
return null;
}
When you're iterating over the list, you're putting the contents of the list into i. Then you're using that i as an index into the list.
You can just compare i directly:
if (i == number)
return "True";
As a note, you may want to change your function to return a boolean rather than a String...
The variable 'i' has the value of the element and not the index. Correct way is :
if ( i== number)
return "true"
Since foreach is iterating over the elements of the ArrayList values, you must compare number with the actual element:
for (int i : values) {
if (i == number){
return "True";
}
}
If you want to use indexes, use a simple for:
for(int i = 0; i < values.size(); i++) {
if (values.get(i) == number){
return "True";
}
}
The foraech give you the content of the array values and not the index. You can simply compare:
if (i == number){
return "True";
}
I'm trying to use a method to compare t2o different lists. Basically I want to pass two different lists to a method which will return true or false if the elements of one array list are contained in the other using .contains. Right now it only returns true - and I'm not sure why. I'd like it to return false. If someone could help me figure this out, that would be great.
public class ArrayListTest {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("cat");
list1.add("dog");
list1.add("zebra");
list1.add("lion");
list1.add("mouse");
//Test Values
//list2.add("cat");
list2.add("lizard");
boolean doesitcontain = contains(list1, list2);
System.out.println(doesitcontain);
}
public static boolean contains (List<String>list1, List<String>list2){
boolean yesitcontains;
for(int i = 0; i < list1.size(); i++){
if(list2.contains(list1.get(i))){
System.out.println("Duplicate: "+list1.get(i));
yesitcontains = true;
System.out.println(yesitcontains);
}else{
yesitcontains = false;
System.out.println(yesitcontains);
}
}
if (yesitcontains = true){
return true;
}else
return false;
}
}
You have inadvertently used the assignment operator where you intended the equality operator. In your specific case you should rewrite all this:
if (yesitcontains = true){
return true;
}else
return false;
}
to just
return yesitcontains;
and avoid any chance of confusion.
Furthermore, your algorithm will not work because you should return true immediately when you see a duplicate. Instead you go on with the loop and "forget" your finding. You can expect this to always return false except if the very last elements coincide.
In a wider context, I should also give you the following general advice:
Avoid indexed iteration over lists. Not all lists are ArrayLists and may show O(n) complexity for get(i). Instead use the enhanced for loop, which is safer, more concise, and more obvious;
Know the library: if you're just after confirming there are no duplicates, just Collections.disjoint(list1, list2) would give you what you need;
Be aware of algorithmic complexity: checking for duplicates in two lists is O(n2), but if you turn one of them into a HashSet, you'll get O(n).
Taking everything said above into account, the following would be an appropriate implementation:
static boolean disjoint(Collection<?> c1, Collection<?> c2) {
for(Object o : c1)
if (c2.contains(o))
return true;
return false;
}
If you look at Collections.disjoint, you'll find this exact same loop, preceded by a piece of code which optimizes the usage of sets for reasons described above.
Seems to me your method should be rewritten to:
public static boolean contains(List<String>list1, List<String>list2) {
return list2.containsAll(list1);
}
The code you currently have actually only checks if the last element of list1 is also in list2.
If you're actually looking for a contains any, this simple solution will do:
public static boolean contains(List<String>list1, List<String>list2) {
for (String str : list1) {
if (list2.contains(str)) {
return true;
}
}
return false;
}
if (yesitcontains = true){
should be
if (yesitcontains == true){
== is for comparison and = is for assignment.
if (yesitcontains = true){
will always evaluate to if(true) which causing return true;
EDIT:
(OR)
simply return yesitcontains; as commented.
if (yesitcontains == true) { } // use `==` here
or just
if (yesitcontains) { }
The below code assigns true to yesitcontains , and the expression will always be true.
if (yesitcontains = true) { }
There is no point of if() in your code , you can simple return yesitcontains;