stripping input causing null pointer - java

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.

Related

Why is this code not executing properly? Longest substring problem

So I'm trying to solve the Longest Substring Without Repeating Character problem in a webpage and when I'm trying to upload it it will show me this bug:
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hash = new HashSet<>();
int count = 0, finalCount = 1;
char prevChar = s.charAt(0);
hash.add(prevChar);
for (int i = 1; i < s.length(); i++)
{
char character = s.charAt(i);
if (!hash.contains(character)){
hash.add(character);
count++;
if (count > finalCount) finalCount = count;
}
else{
hash.clear();
hash.add(character);
count = 1;
}
prevChar = character;
}
return finalCount;
} }
Is there anything wrong with it?
If not, do you think my algorithm was efficient? I can't compare its performance since the webpage won't let me upload it.
You call s.charAt(0) in line 5. I imagine they pass in the empty string as a test case and you are getting an out of bounds exception. Prior to line 5 add a check to see if the string length is 0 and if it is return 0.
According to the error description it's doing a dummy-spit at line 5 of the Solution class.
Based on the picture that's:
char prevChar = s.charAt(0);
The error is ArrayIndexOutOfBounds which generally indicates you tried to get more out of something than was actually there (e.g. running over the end of an array).
Here I'd suggest maybe putting in some System.out.println lines at line 3 to sanity check the method parameter, e.g.:
(a) if the input String s is null
or
(b) if the input String s is empty (e.g. "")
charAt(0) will get the first character, but if there are zero characters then trying to get the 1th character is an error, no?
NB: something like this:
System.out.println("Input was :" + s + ":");
Will show both of those conditions, as either:
Input was ::
for an empty String
Input was :null:
for a null String

Java method not doing what expected. Trying to understand why

Trying to write a java method that will take a string, loop through it and where it finds a vowel (A,E,I,O,U,Y) replace it with the vowel plus "OB".
I've written the below but it isn't working as I'd expect and doesn't seem to be matching the current character in my string with the vowels from my list. (The program compiles and runs so it isn't an issue with not importing necessary bits at the beginning. The input string will always be uppercase and only contain alphas.) I'm struggling to figure out where I'm going wrong.
Can anyone help?
public static String obifyText(String text) {
String[] myList = new String[] {"A","E","I","O","U","Y"};
StringBuilder tempText = new StringBuilder(text);
String obify = "OB";
for (int i = 0; i < text.length() -1 ; i ++ ) {
if ( Arrays.asList(myList).contains(tempText.charAt(i)) ) {
System.out.println(tempText.charAt(i)+" found.");
tempText = tempText.insert((i+1),obify);
}
}
text = tempText.toString();
return text;
}
Don't play with indexes.
Managing with indexes could be difficult when you are dealing with changing the string.
Loop on the chars itself as follows:
public static void main(String[] args){
String[] myList = new String[] {"A","E","I","O","U","Y"};
String text = "AEE";
StringBuilder tempText = new StringBuilder("");
String obify = "OB";
for (char c : text.toCharArray()){
tempText = tempText.append(c);
if ( Arrays.asList(myList).contains(c+"") ) {
System.out.println(c+" found.");
tempText = tempText.append(obify);
}
}
text = tempText.toString();
System.out.println(text);
}
OUTPUT:
A found.
E found.
E found.
AOBEOBEOB
charAt returns a char, but myList stores String elements. An array of Strings can never contain values of char. Your if statement never runs.
You can convert the char value to a string:
Arrays.asList(myList).contains(Character.toString(tempText.charAt(i)))
There's just one more problem with your code.
When the code inserts OB after a vowel, there is a side effect: a new vowel O is created. Your code then tries to insert OB after the new O. This is undesired, right?
To make it not do this, you can loop from the end of the string to the start:
for (int i = text.length() - 1; i >= 0 ; i--) {
If this is not a homework question to practice using StringBuilder or for loops, here's a one liner solution using regex:
return text.replaceAll("([AEIOUY])", "$1OB");
You compare two different types in Arrays.asList(myList).contains(tempText.charAt(i)), Arrays.asList(myList) is a List<String> and tempText.charAt is a char. So the contains check will never result in true.
One possible fix, change myList to Character[]
Character[] myList = new Character[] {'A','E','I','O','U','Y'};
There is another problem with the actual insertion, see Pankaj Singhal answer for a solution to that.

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

Java null char in string

I'm trying to build a string in Java which will be at maximum 3 long and at minimum 1 long.
I'm building the string depending on the contents of a integer array and want to output a null character in the string if the contents of the array is -1. Otherwise the string will contain a character version of the integer.
for (int i=0; i < mTypeSelection.length; i++){
mMenuName[i] = (mTypeSelection[i] > -1 ? Character.forDigit(mTypeSelection[i], 10) : '\u0000');
}
This what I have so far but when I output the string for array {0,-1,-1} rather than just getting the string "0" I'm getting string "0��".
does anyone know how I can get the result I want.
Thanks, m
I'm going to assume you want to terminate the string at the first null character, as would happen in C. However, you can have null characters inside strings in Java, so they won't terminate the string. I think the following code will produce the behaviour you're after:
StringBuilder sb = new StringBuilder();
for (int i=0; i < mTypeSelection.length; i++){
if(mTypeSelection[i] > -1) {
sb.append(Character.forDigit(mTypeSelection[i], 10));
} else {
break;
}
}
String result = sb.toString();

Categories

Resources