My TextView to display an array isn't working? - java

In my app I have a method that is designed to put a new string into a string array in the first empty index. It is then designed to display that array in a textbox that has ten lines. For some reason, this is not working. I have used a Log to display the array contents in Logcat, but this is not appearing. So I thought I'd come here and ask if anyone can see any obvious errors that would cause it not to work? If you need any more details, such as the class from which the array is used, let me know! :)
The method:
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
thePlayer.setPlayerInv("Torch", i);
Log.i(tag,thePlayer.getPlayerInv(1));
playerInvTemp = thePlayer.getPlayerInv();
Log.i(tag,playerInvTemp[1]);
StringBuilder builder = new StringBuilder();
for (String s : playerInvTemp) {
builder.append(s + " ");
invText.setText(builder.toString());
}
break;
}
}

It is a very bad practice to change the array you are iterating on inside loop.
Probably, you have an array of empty strings, in that case you condition:
((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
remains false. Maybe you meant:
(!(playerInvTemp[i].isEmpty() || playerInvTemp[i] == null))

Related

can't get length of string array

I am getting output in string format then I split it and want to do further processing, here is my code snippet,
if(str != null && !str.isEmpty()){
String[] splitLine = str.split("~");
String splitData[];
int i=0;
for( i=0;i<splitLine.length;i++){
splitData = splitLine[i].split("#");
if(Long.parseLong(splitData[0]) == oid)
isParent = true;
break;
}
}
But, the problem is that I am unable to get length of splitLine String array and also eclipse shows a warning as a dead code for i++ inside for loop, I am cant able to understand why this happen does anybody have idea about it.
The break is the problem. It belongs to the preceeding if but that has no curly braces. Change it to this:
if(Long.parseLong(splitData[0]) == oid) {
isParent = true;
break;
}

Changing the value inside an Array List?

for(int i = 0; i <= gameWord.length()-1; i++)
{
if(guessLetter.charAt(0) == (gameWord.charAt(i)))
{
hideword[i] = guessLetter.charAt(0);
}
else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
{
System.out.print("_" + " ");
}
}
I am making a hangman game and I have created an array list called hideword. Hideword prints an underscore for each letter that is in the word used for the game. I am trying to right a method that will swap the underscore with a letter the user guesses. However this code
hideword[i] = guessLetter.charAt(0);
Doesn't work. It gives me "array required, but java.util.ArrayList found
Anyone help?
Then, hideword must be an arraylist. Use hideword.set(index, character) for assignment instead of accessing it like an array.
An ArrayList is not an array, it's a List implementation (however, its implementation is backed by an array - hence the name).
Declare hideword as an array of char:
private char[] hideword;
and initialize it before use:
hideword = new char[gameword.length];
You code, without changing its basic intention, can be simplified greatly:
There's no need to subtract 1 from the length, just change the comparison operator
There's no need to have your if in the else - we already know it's not equal because we're in the else block
Rather than do useless print, assign an underscore to the array slot
Do one print at the end
Like this:
for (int i = 0; i < gameWord.length(); i++) {
if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
hideword[i] = guessLetter.charAt(0);
} else {
hideword[i] = '_';
}
}
// print hideword
You code would be simpler still if hideword didn't exist and you simply System.out.print() each character as you test it instead.

linear search Arrays check values

I need to get inputs to fill an array. My problem is I also need to check if the value I input does not exist already in the array. If exists I need to show a message that says bad grade. I believe I get stuck on the search loop I and Im not able no assign the value to the array If is not already there.
String[] course = new String[9];
int index = 0;
if (menu == 1) {
boolean found = true;
do {
value = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
int pos = 0;
while (pos< course.length&& !found) {
if (value == course[index]) {
found = true;
} else {
pos++;
}
} // while
if(found == true) {
course[index] = value;
} else {
course[index]="";
}
if (course[index].equals("")) {
JOptionPane.showMessageDialog(null, "Bad Course Name");
} else{
course[index] = (JOptionPane.showInputDialog("Enter course " + (index + 1)));
}
} while(course[index].equals("")); //last
}
The problem with your implementation is that once found is set to true, you never reset it back to false: it's a one-way street. That is why entering the first duplicate value prevents other non-duplicated values from being entered.
You can fix this by moving the declaration/initialization of found inside your do/while loop. However, a better approach would be defining a helper method that searches the array for you up to the specific position, and returns true if a duplicate is found:
private static boolean isDuplicate(String[] course, int maxIndex, String entry) {
...
}
Now the loop searching for duplicates would be hidden, along with the variable indicating the result. The code becomes more readable, too, because the name of the method tells the reader what happens inside.
Of course, you need to fix your string comparison: your code uses ==, which is not the way it is done in Java.

How to compare two strings, of different length to find identical substring

The problem is:
Client accounts are filed under a classification system using codes eg MA400. I need a method that will reset the original MA400 to an updated code such as MA400.4. If the new code has 5 characters to which the original is reset then the method returns true. Not the best wording but that is all I have right now.
It hasn't been specified if the characters need to be in the same order, eg.
String str = "abc123";
String newStr = "xyz123abc";
I am assuming they need to be in the same order. So the above strings would only have 3 like characters.
char[]array = str.toCharArray();
char[]array2 = newStr.toCharArray();
I am thinking now to use a compareTo method on the two arrays, but I am not sure how this would work exactly. Perhaps I could use a for loop to stop comparing after the final element in the shortest string but not entirely sure if I can do much with that.
I feel like I am going about this in the wrong way and there is a less complicated way to check for like characters in a string?
From what I understand something like this will work. Remember this will only count unique characters. Order does not matter
public static boolean matchingChar(final String st1, final String st2) {
if(st1 == null || st2 == null || st1.length() < 5 || st2.length() < 5) {
return false;
}
//This is if you wish unique characters to be counted only
//Otherwise you can use simple int count = 0
HashSet<Character> found = new HashSet<Character>();
//found.size() < 5 so the loop break as soon as the condition is met
for(int i = 0; i < st1.length() && found.size() < 5; i++) {
if(st2.indexOf(st1.charAt(i)) != -1) {
found.add(st1.charAt(i));
}
}
return found.size() >= 5;
}

Comparing arrays

I have String Array of a good couple hundred lines of code. I have two other String Arrays, one with values I want to replace, and the other with the value I want it to replace to. I need to go through each line of the original code and check each line if it contains anything that I need to replace, and if it does, replace it. I want to replace it to a totally different String Array, so that the original is still left unchanged. This is what I have, but it's not exactly working.
for(int i=0; i<originalCode.length; i++) {
if( originalCode[i].contains("| "+listOfThingsToReplace[i]) ) {
newCode[i]=originalCode[i].replaceAll(("| "+listOfThingsToReplace[i]), ("| "+listOfReplacingThings[i]));
}
}
Obviously I need more counting variables somewhere (especially because originalCode.length !=listOfThingsToReplace.length), but I can't figure out where. Would I need more for loops? I tired doing that... but "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"... Any help please?
I think this should do the trick if I'm understanding the problem correctly
// New Code Array
String[] newCode = new String[originalCode.length];
for (int i=0; i<originalCode.length; i++) {
// New Code Line
String newCodeLine = originalCode[i];
// Iterate through all words that need to be replaced
for (int j=0; j<listOfThingsToReplace.length; j++) {
// String to replace
String strToReplace = listOfThingsToReplace[j];
// String to replace with
String strToReplaceWith = (j >= listOfReplacingThings.length) ? "" : listOfReplacingStrings[j];
// If there is a string to replace with
if (strToReplaceWith != "") {
// then replace all instances of that string
newCodeLine = newCodeLine.replaceAll(strToReplace, strToReplaceWith);
}
}
// Assign the new code line to our new code array
newCode[i] = newCodeLine;
}

Categories

Resources