if / else "last resort" while in a loop - java

here is the scoop. I have a program that loops through an ArrayList and checks to see if the values are equal to an inputted keyword(inputArray[0])
I want to add a default action incase inputArray[0] is not equal to any of the values inside of the keyList
The else if is where I am having the problem. I want my loop to go through ALL of the values in keyList before it resorts the "last resort" - an else statement. Right now my problem is that in the first if statement it sees that inputArray[0] is not equal to keyList[x] and it goes to the else statement without going through another run of the loop.
As you can see, I tried using an else if statement, where if my loop's counter, x, is larger than the size of keyList then it will do the code inside, but that seemingly does not work. I also added continue;to the else statement to ensure that it is going through the loop, which according to the console, it is. (I know because of the System.out statement at the beginning of the loop.)
public static void wikiInit(ArrayList keyList, ArrayList nameList, ArrayList domainList, ArrayList softwareList, String[] inputArray, EntityPlayer player)
{
System.out.println("These are the current lists:");
System.out.println("Key List: " + keyList);
System.out.println("Name List: " + nameList);
System.out.println("Domain List: " + domainList);
System.out.println("Software List: " + softwareList);
// KEY PARSER
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the loop");
if((keyList.get(x)).equals(inputArray[0]))
{
//getWikiName = wikiNameArray[x]
//getWikiDomain = wikiDomainArray[x]
//getWikiSoftware = wikiSoftwareArray[x]
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++)
{
hyperlinkBuilder.append(inputArray[y] + " ");
}
if((softwareList.get(x)).equals("MEDIAWIKI"))
{
String hyperlink = "http://" + domainList.get(x) + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
break;
}
}
else if(x > keyList.size())
{//LAST RESORT
}
else
{
continue;
}
}
}

instead of loop use
if(keyList.contains(inputArray[0])){
int x = keyList.indexOf(inputArray[0]);
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++)
...
}
else { // last resort code
}

If the default action should only happen after all elements have been checked, it should happen outside the loop. You can do this by using a variable to signal when this happens:
boolean found = false;
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the loop");
if((keyList.get(x)).equals(inputArray[0]))
{
found = true;
...
}
}
if (!found) {
//The value was never found, do something special.
}
Having said that, in this case it would be much easier to use keyList.contains, as in bellabax's answer.

One way is to simply set a found variable to false before the loop and set it to true inside the loop if you find a key match.
Then after the loop:
if (!found)
complainBitterly();

Try using a boolean. Set it to false before the for loop, and if inputArray[0] is equal to keyList[x], set the boolean to true (in your if statement).
Then have an if statement after the for loop that will do your last case resort if the bool is still false.

The good news is you can make this a lot simpler by making 2 changes.
First, extract those 4 separate lists that you reference and combine them as a list of objects with fields for each list, 'ParameterTuplein the code. Second, you can track loop exit status with another variable,foundMediaWikiKey` in the code.
/**
* Not sure of a better name for this class, you'll need to look at in the larger sense.
* Also, in production you probably want to use getters for these, rather than final
* public and the constructor
*/
public class ParameterTuple {
public ParameterTuple(String key, String name, String domain, String software) {
this.key = key;
this.name = name;
this.domain = domain;
this.software = software;
}
public final String key;
public final String name;
public final String domain;
public final String software;
}
public static void wikiInit(ArrayList<ParameterTuple> paramList, String[] inputArray, EntityPlayer player) {
System.out.println("These are the current lists:");
System.out.println("List: " + paramList);
// Variable to keep track of how we exited the loop.
boolean foundMediaWikiKey = false;
// KEY PARSER
for(ParameterTuple param : paramList)
{
System.out.println("Starting the loop");
if(param.key.equals(inputArray[0])) {
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int y = 1; y < inputArray.length; y++) {
hyperlinkBuilder.append(inputArray[y] + " ");
}
if(param.software.equals("MEDIAWIKI")) {
String hyperlink = "http://" + param.domain + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + param.name;
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + param.name;
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
// Keep track of how we exited the loop
foundMediaWikiKey = true;
break;
}
}
}
// When we exit, check to see how we did so.
if (!foundMediaWikiKey) {
// Last Resort
}
}

We usually do it like this where we search first and then put the code to handle the found one later.
I also lifted the one part out of the loop, since it didn't need to be in there. It could also go down in the "found" part of the code but I liked getting it out of the way to make the code more readable.
Also, the test for MEDIAWIKI is left in the loop (unlike my earlier version of this). Thanks to #paxdiablo for that. It is also a failing of some other answers here (as of right now).
StringBuilder hyperlinkBuilder = new StringBuilder(); // lift this out of the loop
for(int y = 1; y < inputArray.length; y++) {
hyperlinkBuilder.append(inputArray[y] + " ");
}
int found = -1;
for(int x = 0; x < keyList.size(); x++)
{
System.out.println("Starting the inside of the loop");
if((keyList.get(x)).equals(inputArray[0])) {
if((softwareList.get(x)).equals("MEDIAWIKI"))
found = x;
break;
}
}
}
if (found >= 0) {
int x = found;
//getWikiName = wikiNameArray[x]
//getWikiDomain = wikiDomainArray[x]
//getWikiSoftware = wikiSoftwareArray[x]
String hyperlink = "http://" + domainList.get(x) + "/index.php?search=" + hyperlinkBuilder.toString();
System.out.println("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
player.addChatMessage("Searching for " + hyperlinkBuilder.toString() + " on the " + nameList.get(x));
BrowserHandler.browserInit(hyperlink.replace(" ", "+"), player);
System.out.println("Opening " + hyperlink.replace(" ", "+"));
} else {
//LAST RESORT ... fill in 'not found' code
}

I want my loop to go through ALL of the values in keyList before it
resorts the "last resort" - an else statement
else if(some condition)
{
if(x!=keylist.size()-1) // USE IT HERE
{ continue; }
//LAST RESORT
}

Related

Return with a for loop

The code I am using is below. As far as I am aware the logic of the code is fine but when the return is after the print for the char B then the I within the for loop wont increment. If I remove the return statement then the for loop will increment as I wanted it too, however I need the method to end if the B/W is printed so I need the return to be present. Any help is greatly appreciated I've been trying to work out whats wrong for hours now.
if(currentCodeString.contains("" + currentGuessChar)) {
for (int i = 0; i < codeLength; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
return;
}
}
System.out.print("W");
return;
}
Use break instead of return in your for loop.
if(currentCodeString.contains("" + currentGuessChar)) {
for (int i = 0; i < codeLength; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
break;
}
}
System.out.print("W");
return;
}
return means - "end method", break means - "end loop"
You should replace the return statement with break after you print "B".
why you doesn’t use "Break" Instead of "Return"?
when the B print , Break it!
the use of return in Thread programming.
This is my solution (without break, which i don't like)
if(currentCodeString.contains("" + currentGuessChar)) {
bool found = false;
for (int i = 0; i < codeLength && !found; i++) {
System.out.println("" + i);
//System.out.println(currentGuess[i] + " - " + currentCode[i]);
if(checkPins(currentGuess[i], currentCode[i])) {
System.out.print("B");
found = true;
}
}
if (!found) {
System.out.print("W");
}
}

Listing all the combinations of the elements of a set

Among elements of a set, I want to list all the 3-combinations of this set.
Is there a way to do it?
If it was a list;
for(int i=0; i<list.size()-2; i++)
for(int j=i+1; j<list.size()-1; j++)
for(int k=j+1; k<list.size(); k++)
System.out.println(list.get(i) + " " + list.get(j) + " " + list.get(k));
But how to do this with a set without converting it to a list?
Converting to a list and using the logic from your code would be my first choice. If you want to do it without converting to list, you can do it with iterators, like this:
Set<String> set = ...;
for (String a : set) {
boolean bGo = false;
for (String b : set) {
if (bGo) {
boolean cGo = false;
for (String c : set) {
if (cGo) {
System.out.println(a + " " + b + " " + c);
} else if (b.equals(c)) {
cGo = true;
}
}
} else if (a.equals(b)) {
bGo = true;
}
}
}
The logic above freely iterates the set in the outer loop. When it starts iterating the set in the first nested loop, it skips elements until the current element of the outer loop is found (i.e. until a.equals(b)). After that, it runs the third nested loop, which skips all data in the set until b, at which point it starts producing the combinations output.
Here is a demo on ideone.
Is your set a SortedSet ? If so, you can do this:
for (V x: mySet) {
for (V y: mySet.tailSet(x, false)) {
for (V z: mySet.tailSet(y, false)) {
System.out.println(x + " " + y + " " + z);
}
}
}

List with Int as first argument and String as second (Java)

I'm trying to write a method that returns an int index as the first argument and a string as the second. The method should insert the string into a list by order of the index's. If the Int is negative or leaves a gap, it should throw IllegalArgumentException. Here's what I've done:
public MitchList() {
data = new String[2];
size = 0;
}
public int size() {
return size;
}
public void add(int index, String s){
if (data.length == size) {
String[] newArray = new String[data.length*2];
for (int i=0; i < data.length; i++) {
newArray[i] = data[i];
}
data = newArray;
}
if (index > 0 || index <size){
throw new IllegalArgumentException();
}
if (data[index] != ""){
for (int i = 0; i <size; i++){
s = data[index];
}
}
data[index] = s;
size++;
}
The JUnit test is saying it is failing. It should return a list like:
1, Cat
2, Dog
3, Squirrel
So on..
Any ideas on a solution?
UPDATE
Here's what I have now.
/**
<P>{#code java MitchList}</P>
**/
public class MitchList {
private String[] asData;
private int iSize;
public static final void main(String[] igno_red) {
MitchList ml = new MitchList();
test(ml, 0, "hello");
test(ml, 1, "goodbye");
}
public static final void test(MitchList m_l, int i_ndex, String s_tring) {
m_l.add(i_ndex, s_tring);
System.out.print(s_tring + ", ");
}
public MitchList() {
asData = new String[2];
iSize = 2;
}
public int iSize() {
return iSize;
}
public void add(int index, String s){
System.out.println("asData.length=" + asData.length + ", iSize=" + iSize + "");
if (asData.length == iSize) {
System.out.println("1");
String[] newArray = new String[asData.length*2];
for (int i=0; i < asData.length; i++) {
newArray[i] = asData[i];
}
asData = newArray;
}
if (index > 0 || index <iSize){
System.out.println("2");
throw new IllegalArgumentException("index (" + index + ") must be greater than zero and less than size (" + iSize + ")");
}
System.out.println("asData[" + index + "]=" + asData[index] + "");
if (asData[index] != ""){
System.out.println("3");
for (int i = 0; i <iSize; i++){
System.out.println("i=" + i + ", setting s to ");
s = asData[index];
}
}
asData[index] = s;
iSize++;
}
I took your code and changed a bit. Now it just gives back
asData.length=2, iSize=2
1
2
Exception in thread "main" java.lang.IllegalArgumentException: index (0) must be greaterthan zero and less than size (2)
at MitchList.add(MitchList.java:42)
at MitchList.test(MitchList.java:14)
at MitchList.main(MitchList.java:10)
Any ideas?
It is very hard to get out what you are doing, with as little information you are giving us here, but this is what I've figured so far. Below is your code with some debugging statements in it.
I strongly recommend you add some information to your no-message exception. That is, change
throw new IllegalArgumentException();
to
throw new IllegalArgumentException("index (" + index + ") must be greater than zero and less than size (" + iSize + ")");
When I run this code, this is the output
[R:\jeffy\programming\sandbox\xbnjava]java MitchList
asData.length=2, iSize=0
asData[0]=null
3
hello,
asData.length=2, iSize=1
2
Exception in thread "main" java.lang.IllegalArgumentException: index (1) must be greater than zero and less than
size (1)
at MitchList.add(MitchList.java:41)
at MitchList.test(MitchList.java:14)
at MitchList.main(MitchList.java:11)
You were hiding some very valuable information: Greater than zero and less than one is impossible
Also
You're doubling the size of the array with data.length*2, yet you're only increasing size by one: size++;.
You're overwriting the value of s with every value in the array (the s = data[index]; in the for-loop), causing it to always equal the last element. Then you're just re-inserting the current value of the last element over-top itself. In other words, the s parameter is being ignored, and the array is never changing.
One more thought: I think if(data[index] == "") should be if(data[index] == null). String arrays are initialized to null, not the empty-string.
Consider using the below code, with all its debugging statements, as a starting point for fixing the above issues, and discovering whatever others there may be. Good luck!
import org.apache.commons.lang.StringUtils;
/**
<P>{#code java MitchList}</P>
**/
public class MitchList {
private String[] asData;
private int iSize;
public static final void main(String[] igno_red) {
MitchList ml = new MitchList();
test(ml, 0, "hello");
test(ml, 1, "goodbye");
}
public static final void test(MitchList m_l, int i_ndex, String s_tring) {
m_l.add(i_ndex, s_tring);
//Print the array at the last index in asData
System.out.println(StringUtils.join(m_l.asData, ", "));
//If you don't have `commons.lang` installed, use this:
//
// for(String s : asData) {
// System.out.print(s + ", ");
// }
}
public MitchList() {
asData = new String[2];
iSize = 0;
}
public int iSize() {
return iSize;
}
public void add(int index, String s){
System.out.println("asData.length=" + asData.length + ", iSize=" + iSize + "");
if (asData.length == iSize) {
System.out.println("1");
String[] newArray = new String[asData.length*2];
for (int i=0; i < asData.length; i++) {
newArray[i] = asData[i];
}
asData = newArray;
}
if (index > 0 || index <iSize){
System.out.println("2");
throw new IllegalArgumentException("index (" + index + ") must be greater than zero and less than size (" + iSize + ")");
}
System.out.println("asData[" + index + "]=" + asData[index] + "");
if (asData[index] != ""){
System.out.println("3");
for (int i = 0; i <iSize; i++){
System.out.println("i=" + i + ", setting s to ");
s = asData[index];
}
}
asData[index] = s;
iSize++;
}
}
EDIT: Additional comment regarding if (index > 0 || index <iSize). Aside from the or/and issue mentioned below, why must the index be above zero? Zero is a valid array index.
This is what I get when I run your updated code:
asData.length=2, iSize=2
1
2
asData[0]=null
3
i=0, setting s to
i=1, setting s to
hello, asData.length=4, iSize=3
2
asData[1]=null
3
i=0, setting s to
i=1, setting s to
i=2, setting s to
goodbye,
All of those i=0, setting s to is a problem. Why are you setting s to anything, let alone setting it repeatedly? And then you set that value into the array, which makes no sense, because that's where it just came from. To emphasize: The parameter s is being over-written before you ever use it, and the array never changes.
This code:
if(index > 0 || index <iSize){
throw new IllegalArgumentException("index (" + index + ") must be greater than zero and less than size iSize + ")");
}
Think about it. || is "or", yet the error message says "and"
You still haven't fixed the doubling-the-array-yet-only-incrementing-size problem, nor the asData[index] != "" issue, as mentioned in my original answer.

Entering an If statement with a hashmap conditions

for (int i = 0; i < pac.length; i++)
{
for (int j=0;j<mem.length;j++)
{
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++)
{
if (words[k].equals(pac[i])
{ //done system.out.println here and it's right
if (!members.containsKey(pac[i])) //won't enter this if correctly
{
members.put(pac[i], " " + words[0]);
}
else
{
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
}
}
else
{
members.put(pac[i], "");
}
}
}
}
I need the code to take an array pac which contains a list of organizations and then a list of people's names with their organizations after. I have to put them into a hashmap of members. I cant seem to get it to enter the if statement correctly though. It reaches there correctly. I've used the printing to see what should go into it and that part is correct. Members is an empty hashmap yet all but only one iteration of the loops will go into the first if statement when most should go into it.
use label you can solve your problem. because any one iteration of 2nd loop can empty your member. try this
for (int i = 0; i < pac.length; i++) {
action:
for (int j = 0; j < mem.length; j++) {
String[] words = mem[j].split(" ");
for (int k = 1; k < words.length; k++) {
//System.out.println(words[0] + "ttt");
if (words[k].equals(pac[i])) {
System.out.println(words[k]);
if (!members.containsKey(pac[i]))
{
members.put(pac[i], " " + words[0]);
break action;
} else {
String old = members.get(pac[i]);
members.put(pac[i], old + " " + words[0]);
break action;
}
} else {
members.put(pac[i], "");
}
}
}
}
and use persons as a key for members instead of organization. because a org have more number of persons.

i want to search for particular word with white space from statement Android

I want to search in list i get by firing an api.
I'm currently using indexof () to search but if i provide space after word it's searching but list is not properly updated.
example:
I'e two record in list 1. Qtlist and Uses 2. android
If i search for "and " then it has to show only 1. but it showing 1. & 2. both.
my function for this
private ArrayList<BusinessDetails> GetSearchAdapterData(String searchKeyword) {
final ArrayList<BusinessDetails> listData = new ArrayList<BusinessDetails>();
String searchWith = "";
Log.i("BusinessArray ", "size is "
+ sitesList.getBusinessArray().size());
list.clear();
if (sitesList.getBusinessArray() != null
&& sitesList.getBusinessArray().size() > 0) {
for (int i = 0; i < sitesList.getBusinessArray().size(); i++) {
// String searchWith = "";
searchWith += sitesList.getBusinessArray().get(i).busName;
Log.i("businessName ", "Bus_Name is "
+ sitesList.getBusinessArray().get(i).busName
+ " startwith " + startsWith);
if (searchWith.toLowerCase().indexOf(searchKeyword.toLowerCase()) != -1) {
listData.add(sitesList.getBusinessArray().get(i));
}
}
Log.i("List data is inside loop call", "Listdata" + listData.size());
} else {
Log.i("sitesList.getBusinessArray() is zero", "size Zero");
}
return listData;
}
Changes I'e been done to my function are:
private ArrayList<BusinessDetails> GetSearchAdapterData(String searchKeyword) {
final ArrayList<BusinessDetails> listData = new ArrayList<BusinessDetails>();
String searchWith = "";
Log.i("BusinessArray ", "size is "
+ sitesList.getBusinessArray().size());
if (sitesList.getBusinessArray() != null
&& sitesList.getBusinessArray().size() > 0) {
for (int i = 0; i < sitesList.getBusinessArray().size(); i++) {
searchWith += sitesList.getBusinessArray().get(i).busName;
}
for (int i = 0; i < sitesList.getBusinessArray().size(); i++) {
if (searchWith.matches(".*\\b" + searchKeyword + "\\b.*")) {
listData.add(sitesList.getBusinessArray().get(i));
Log.i("Match Word fromList", "" + listData.get(i).busName);
}
}
Log.i("List data is inside loop call", "Listdata" + listData.size());
} else {
Log.i("sitesList.getBusinessArray() is zero", "size Zero");
}
return listData;
}
Any help will be appreciated so, please... help
If I understand the problem correctly
sitesList.getBusinessArray().size() == 2
sitesList.getBusinessArray().get(0).busName == "Qtlist and Uses"
sitesList.getBusinessArray().get(1).busName == "android"
The first value of searchWith will be "Qtlist and Uses" and the second value of searchWith will be "Qtlist and Usesandroid" since you append the busName to searchWith. Hence it is correct that both matches the indexof test.
Isn't it sufficient to omit the '+' and use
searchWith = sitesList.getBusinessArray().get(i).busName;
You can use the string matches method and reg ex to match the whole word. Following is thew small example that u can use for your problem.
String[] ss={"Qtlist and Uses","android"};
for(String s:ss){
System.out.println("s is "+s+" and it matches with "+s.matches(".*\\band\\b.*"));
}
following is the out put of the program:
s is Qtlist and Uses and it matches with true
s is android and it matches with false
here \b has been used mark the word boundary. Hope it solves you issue.
EDIT 1: Try replacing following code:
if (searchWith.toLowerCase().indexOf(searchKeyword.toLowerCase()) != -1) {
listData.add(sitesList.getBusinessArray().get(i));
}
with
if (sitesList.getBusinessArray().get(i).busName.matches(".*\\band\\b.*")){
listData.add(sitesList.getBusinessArray().get(i));
}
Any word can be matched using the following regex
".*\\banyword\\b.*"

Categories