can't get length of string array - java

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

Related

My TextView to display an array isn't working?

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

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

stripping input causing null pointer

I am trying to create a method that strips a string of whitespace and punctuation to check if it is a palindrome. When filling a char array of stripped chars I get a null pointer exception. To me it makes perfect sense, i am filling the array of the same length with only letters or numbers. if there are leftover chars then i fill them with a space (later to be stripped with trim). Without char[] strippedInput = null; i get variable may not have been initialized. With it I get null pointer exception. I drew a simple diagram of what would happen to the stripped array when I input "if, then." and everything seemed to match up. There seemed to be a value for each array index of strippedInput yet netbeans is telling me that something is null.
static boolean palindromeCheckC(String inputString)
{
boolean isPalin2 = false;
char[] inChars = inputString.toCharArray();
char[] strippedInput = null;
int offsetIndex = 0;
for (int i = 0; i < inputString.length(); i++)
{
if ((Character.isLetter(inChars[i]) || Character.isDigit(inChars[i]
)) == true)
{
strippedInput[i-offsetIndex] = inChars[i];
}
else offsetIndex++;
}
for (int i = inputString.length()- offsetIndex; i < inputString.length(); i++)
{
strippedInput[i] = ' ';
}
System.out.println(strippedInput);
//to string
//reverse
//compare to if 0 => isPalin2 = true
return isPalin2;
}
The problem is that instead of initializing your array, you set it to null. Try changing:
char[] strippedInput = null;
to
char[] strippedInput = new char[inputString.length()];
I understand that the strippedInput will likely contain fewer characters than are in the inputString. However, as far as I know, it is possible that you will need the same amount of characters in the stripped array. If you do not need all of them, just write a null character at the end the data and it will work/print correctly. Regardless, this will solve your NullPointerException.

String not populating properly

I am writing a program that is going to read a string from a file, and then remove anything that isn't 1-9 or A-Z or a-z. The A-Z values need to become lowercase. Everything seems to run fine, I have no errors, however my output is messed up. It seems to skip certain characters for no reason whatsoever. I've looked at it and tweaked it but nothing works. Can't figure out why it is randomly skipping certain characters because I believe my if statements are correct. Here is the code:
String dataIn;
int temp;
String newstring= "";
BufferedReader file = new BufferedReader(new FileReader("palDataIn.txt"));
while((dataIn=file.readLine())!=null)
{
newstring="";
for(int i=0;i<dataIn.length();i++)
{
temp=(int)dataIn.charAt(i);
if(temp>46&&temp<58)
{
newstring=newstring+dataIn.charAt(i);
}
if(temp>96&&temp<123)
{
newstring=newstring+dataIn.charAt(i);
}
if(temp>64&&temp<91)
{
newstring=newstring+Character.toLowerCase(dataIn.charAt(i));
}
i++;
}
System.out.println(newstring);
}
So to give you an example, the first string I read in is :
A sample line this is.
The output after my program runs through it is this:
asmlietis
So it is reading the A making it lowercase, skips the space like it is suppose to, reads the s in, but then for some reason skips the "a" and the "m" and goes to the "p".
You're incrementing i in the each of the blocks as well as in the main loop "header". Indeed, because you've got one i++; in an else statement for the last if statement, you're sometimes incrementing i twice during the loop.
Just get rid of all the i++; statements other than the one in the for statement declaration. For example:
newstring="";
for(int i=0;i<dataIn.length();i++)
{
temp=(int)dataIn.charAt(i);
if(temp>46&&temp<58)
{
newstring=newstring+dataIn.charAt(i);
}
if(temp>96&&temp<123)
{
newstring=newstring+dataIn.charAt(i);
}
if(temp>64&&temp<91)
{
newstring=newstring+Character.toLowerCase(dataIn.charAt(i));
}
}
I wouldn't stop editing there though. I'd also:
Use a char instead of an int as the local variable for the current character you're looking at
Use character literals for comparisons, to make it much clearer what's going on
Use a StringBuilder to build up the string
Declare the variable for the output string for the current line within the loop
Use if / else if to make it clear you're only expecting to go into one branch
Combine the two paths that both append the character as-is
Fix the condition for numbers (it's incorrect at the moment)
Use more whitespace for clarity
Specify a locale in toLower to avoid "the Turkey problem" with I
So:
String line;
while((line = file.readLine()) != null)
{
StringBuilder builder = new StringBuilder(line.length());
for (int i = 0; i < line.length(); i++) {
char current = line.charAt(i);
// Are you sure you want to trim 0?
if ((current >= '1' && current <= '9') ||
(current >= 'a' && current <= 'z')) {
builder.append(current);
} else if (current >= 'A' && current <= 'Z') {
builder.append(Character.toLowerCase(current, Locale.US));
}
}
System.out.println(builder);
}

Why is new line getting appended to my array element when I am trying to print this?

private int Index(String[] match,String keyword){
int m=0;
keyword=keyword+"1";
match[m]=match[m]+"1";
System.out.println("match:"+match[m]);
System.out.println("keyword:"+keyword);
System.out.println(match[m].equals(keyword));
while(!(match[m].equals("")) && !(match[m].equals(null))){
System.out.println("yes");
if(match[m].equals(keyword)){
break;
}
else
m++;
}
return m;
}
And I am getting following output (value of keyword is sparktg):
match:sparktg
1
keyword:sparktg1
false
Why in the case of match[m], there is a new line between "sparktg" & "1"?
If you have no control over the input, you can do a trim() before you use the inputs. This eliminates any \n and spaces.
if(match[m] != null) {
System.out.println("match:"+match[m].trim());
}
if(keyword != null) {
System.out.println("keyword:"+keyword.trim());
}
You can make it cleaner by writing a utility method to do this.
public String sanitize(String input) {
return input != null ? input.trim() : null;
}
and use it as so:
match[m] = sanitize(match[m]);
keyword = sanitize(keyword);
The only reason I can see is that match[0] already ends in a newline. You should check by outputting match[0] before adding the "1". A good practice is to output in this form:
System.out.println("|"+match[0]+"|");
...thus using the | to clearly mark where your string starts and ends.
You can use trim() to cut off any whitespace, including newlines:
match[m] = match[m].trim() + "1";
However, this will also remove spaces and tabs, which may or may not be a problem for you. When I compare strings, I often trim both strings first, just to be safe, but only if you are disregarding whitespace.
Try this. Replace all the new line before parsing.
private static int Index(String[] match,String keyword){
int m=0;
for(int k=0;k<match.length;k++){
if(match[k]!=null)
match[k]= match[k].replace("\n", "");
}
if(keyword!=null)
keyword= keyword.replace("\n", "");
keyword=keyword+"1";
match[m]=match[m]+"1";
System.out.println("match:"+match[m]);
System.out.println("keyword:"+keyword);
System.out.println(match[m].equals(keyword));
while(!(match[m].equals("")) && !(match[m].equals(null))){
System.out.println("yes");
if(match[m].equals(keyword)){
break;
}
else
m++;
}
return m;
}
That is not the answer, but notation about the code
match[m].equals(null) will throw an NullPointerException. The right way to check if match[m] not equals null is: mathc[m] != null before calling any method of your object. So use this:
match[m] != null && !match[m].equals("")
instead of this:
!match[m].equals("") && !match[m].equals(null)

Categories

Resources