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();
Related
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
This is just a little bit of my code, but I am trying to loop through two strings, get the value of the first number in one string, and then use that number as the position to find in the other string, then add that word into a new string. But it comes up with the error "String cannot be converted to int" can anyone help?
String result = "";
for (int i = 0; i < wordPositions.length; i++){
result += singleWords[wordPositions[i]];
}
if your wordPositions is a String array when you do this:
result += singleWords[wordPositions[i]];
it like if you does this
result += singleWords["value of the wordPositions array at index i"];
but is need to be an int in [] not a string that why you have the exception String can not be cast to Int
If wordPositions is an array of numbers inside a string for example
String[] wordPositions = new String[]{"1","2","3"};
Then you nees to use
Integer.parseInt(NUMBER_IN_STRING);
To change the string value to an int value.
You are getting this error because wordPositions[i] returns a string and you need to convert it to int before trying to acess singlewords[].
result += singleWords[Integer.parseInt(wordPositions[i])];
Use this to convert String into int
Integer.parseInt(integerString);
The completed line of code:
result += singleWords[Integer.parseInt(wordPositions[i])];
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;
}
I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.
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.