Java String Concatenation Error "String index out of range: -1" - java

First off I know there are a lot of questions about "String index out of range", I have looked through them but can't find anyone having the same problem as me.
I have to write a simple program:
Given a string, return a "rotated left n" version where the first n chars are moved to the end.
leftN("Hello",2) → "lloHe"
leftN("java",0) → "java"
leftN("Hi,1") → "iH"
So I wrote the following:
package string;
public class LeftN {
public static String leftN(String str, int n) {
if (str.length() > 1 && n > 0) {
String a = str.substring(n);
String b = str.substring(0, n);
return a + b;
} else {
return str;
}
}
}
Question:
When I return just a or just b I get a valid output (if I add the output of a and b on paper I am getting the rotated left n version of the string). However, when I return the concatenation of a + b I get the String index out of range: -1 error, what can it be that is causing this?
Now I know that this error has to do with referencing a value that is out of bounds for the string and understand how this works when creating a substring. What is really confusing me is how adding two seemingly valid strings can give me this error?
Note: I have a test class provided that I am testing it against to see if it's giving the right output but I am not sure if I am allowed to post it online so that is why I am not providing it.

I can reproduce your exception by passing an n greater than the length of str:
leftN("abc", 4);
results in:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.base/java.lang.String.substring(String.java:1850)
at Ideone.leftN(Main.java:12)
at Ideone.main(Main.java:22)
You need to handle the case of n being too large (or, indeed, negative). For example:
Throw an IllegalArgumentException
Use n % str.length() instead.

Related

Removing a substring from a string, repeatedly

Problem:
Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.
Explanation/Working:
For Example: t = ab, s = aabb. In the first step, we check if t is
contained within s. Here, t is contained in the middle i.e. a(ab)b.
So, we will remove it and the resultant will be ab and increment the
count value by 1. We again check if t is contained within s. Now, t is
equal to s i.e. (ab). So, we remove that from s and increment the
count. So, since t is no more contained in s, we stop and print the
count value, which is 2 in this case.
So, here's what I have tried:
Code 1:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.
Code 2:
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.
Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?
Thank you in advance :)
Try saving the new (returned) string instead of ignoring it.
s = s.replace(t,"");
replace returns a new string; you seemed to think that it alters the given string in-place.
Try adding some simple parameter checks of the strings. The strings shouldn't be equal to null and they should have a length greater than 0 to allow for counts greater than 0.
static int maxMoves(String s, String t) {
int count = 0,i;
if(s == null || s.length() == 0 || t == null || t.length() == 0)
return 0;
while(true)
{
if(s.contains(t) && !s.equals(""))
s = s.replace(t,""); //Marked Statement
else break;
++count;
}
return count;
}
You might be missing on the edge cases in the code 1.
In code 2, you are not storing the new string formed after the replace function.
The replace function replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
Try this out:
public static int findCount(String s, String t){
if( null == s || "" == s || null == t || "" == t)
return 0;
int count =0;
while(true){
if(s.contains(t)){
count++;
int i = s.indexOf(t);
s = s.substring(0, i)+s.substring(i+t.length(), s.length());
// s = s.replace(t,"");
}
else
break;
}
return count;
}
String r1="ramraviraravivimravi";
String r2="ravi";
int count=0,i;
while(r1.contains(r2))
{
count++;
i=r1.indexOf(r2);
StringBuilder s1=new StringBuilder(r1);
s1.delete(i,i+r2.length());
System.out.println(s1.toString());
r1=s1.toString();
}
System.out.println(count);
First of all no logical difference in both the codes.
All the mentioned answers are to rectify the error of code 2 but none told how to pass all (14/14) cases.
Here I am mentioning a test case where your code will fail.
s = "abcabcabab";
t = "abcab"
Your answer 1
Expected answer 2
According to your code:
In 1st step, removig t from index 0 of s,
s will reduce to "cabab", so the count will be 1 only.
But actual answer should be 2
I first step, remove t from index 3 of s,
s will reduced to "abcab", count = 1.
In 2nd step removing t from index 0,
s will reduced to "", count = 2.
So answer would be 2.
If anyone know how to handle such cases, please let me know.

Add Two Binary Numbers Recursively, w/o Bitwise Operations; Java Homework

I think I've gotten mostly to a solution for a homework problem.
This is for a 201 CS class. Right now I just want to get the logic right. At present, it doesn't operate as intended, but it's close.
We don't want to use .toBinary, bitwise, or anything else. We also haven't been taught stringBuilder, so I'd like to avoid using it.
There's a System.out.println(); within the method which provides the correct answer if you read the console from bottom to top.
public static void main(String[] args) {
System.out.println(addBin(1100111011,1101110011));
}
public static String addBin(int num1,int num2){
String result = "";
if(num1 > 0 || num2 > 0){
int part1 = num1%10, part2 = num2%10;
int rem1 = num1/10, rem2 = num2/10;
result += Integer.toString((part1 + part2)%2);
//System.out.println(result);
int carry = (part1 + part2) /2;
addBin(rem1 + carry, rem2);
return result;
}
return result;
}
So, this example adds 1100111011 and 1101110011 with the output
0
1
1
1
0
1
0
1
0
1
1
0
when the correct answer is 11010101110.
I'm having trouble understanding how to properly "pop" the "result" part properly. Could you please help me understand this process, possibly within the context of this problem?
Thanks!
As you can see from your output, you are getting the correct result in the reverse order but you are not appending any of your older result to the ones that are being currently computed.
Inside your if condition, you are calling the addBin() function but you are not using the result that it gives anywhere. Just change that line to the following:
result = addBin(rem1 + carry, rem2)+result;
That should effective append all your results in front of the current answer so that you do not get the result in backwards direction. Hope this helps.

compare two strings in java

I am trying to compare to strings by using an algorithm as you see below
My code does not work .. eclipse does not show any error before I run the code
public class MysteryClass {
public static void mystery(String n) {
String k= "alla";
if (k.charAt(k.length())==n.charAt(n.length())) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
}
}
public static void main(String[] args) {
MysteryClass.mystery("alla");
}
}
but we I run the code I get
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at shapes.MysteryClass.mystery(MysteryClass.java:6)
at shapes.MysteryClass.main(MysteryClass.java:15)
How to fix that??
thanks
Not sure what you want, but your StringIndexOutOfBoundsException is cause by access an array's index which is does not exist.
Take your String k = "alla" as example, k.length() will return 4 because "alla" have four characters, and you are accessing k.charAt(4), the "alla"break into as follows:
a l l a // string
0 1 2 3 // index
As you can see the last index of "alla" is 3, that's why you get StringIndexOutOfBoundsException. But you can solve it using .length() -1 as follow:
if (k.charAt(k.length()-1)==n.charAt(n.length()-1)) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
Alternative:
If you want to compare two string, you can use .equals method too, as follow:
if (k.equals(n)) {
System.out.println("palindrom");
} else {
System.out.println("not palindrom");
Two issues with your code:-
1)By your logic, tigert is also palindrome but it is actually not.Palindrome is when the word is completely reversed and it is still the same.Currently,you are checking only the first and last character
2)String is internally held as a char array and arrays have indexing from 0 to length -1
The error is caused by the statement if (k.charAt(k.length())==n.charAt(n.length()))
Above k.length() returns 4. the statement then resolves to:
(k.charAt(4)
This will through error because the function charAt counts from the index 0. So it counts the characters at index 0, 1, 2, 3 and you are asking it to fetch character at index 4 which does not exist.
A suggested alternative is :
(k.charAt(k.length() -1)==n.charAt(n.length()-1))

Java - Complex Recursive Backtracking

For Java practice I started working on a method countBinary that accepts an integer n as a parameter that prints all binary numbers that have n digits in ascending order, printing each value on a separate line. Assuming n is non-negative and greater than 0, some example outputs would look like this.
I am getting pretty much nowhere with this. I am able to write a program that finds all possible letter combinations of a String and similar things, but I have been unable to make almost any progress with this specific problem using binary and integers.
Apparently the best way to go about this issue is by defining a helper method that accepts different parameters than the original method and by building up a set of characters as a String for eventual printing.
Important Note: I am NOT supposed to use for loops at all for this exercise.
Edit - Important Note: I need to have trailing 0's so that all outputs are the same length.
So far this is what I have:
public void countBinary(int n)
{
String s = "01";
countBinary(s, "", n);
}
private static void countBinary(String s, String chosen, int length)
{
if (s.length() == 0)
{
System.out.println(chosen);
}
else
{
char c = s.charAt(0);
s = s.substring(1);
chosen += c;
countBinary(s, chosen, length);
if (chosen.length() == length)
{
chosen = chosen.substring(0, chosen.length() - 1);
}
countBinary(s, chosen, length);
s = c + s;
}
}
When I run my code my output looks like this.
Can anyone explain to me why my method is not running the way I expect it to, and if possible show me a solution to my issue so that I might get the correct output? Thank you!
There are more efficient ways to do it, but this will give you a start:
public class BinaryPrinter {
static void printAllBinary(String s, int n) {
if (n == 0) System.out.println(s);
else {
printAllBinary(s + '0', n - 1);
printAllBinary(s + '1', n - 1);
}
}
public static void main(String [] args) {
printAllBinary("", 4);
}
}
I'll let you work out the more efficient way.

Recursive method to determine if a string is a hex number - Java

This is a homework question that I am having a bit of trouble with.
Write a recursive method that determines if a String is a hex number.
Write javadocs for your method.
A String is a hex number if each and every character is either
0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9
or a or A or b or B or c or C or d or D or e or E or f or f.
At the moment all I can see to test this is if the character at 0 of the string is one of these values he gave me then that part of it is a hex.
Any hints or suggestions to help me out?
This is what I have so far: `
public boolean isHex(String string){
if (string.charAt(0)==//what goes here?){
//call isHex again on s.substring(1)
}else return false;
}
`
If you're looking for a good hex digit method:
boolean isHexDigit(char c) {
return Character.isDigit(c) || (Character.toUpperCase(c) >= 'A' && Character.toUpperCase(c) <= 'F');
}
Hints or suggestions, as requested:
All recursive methods call themselves with a different input (well, hopefully a different input!)
All recursive methods have a stop condition.
Your method signature should look something like this
boolean isHexString(String s) {
// base case here - an if condition
// logic and recursion - a return value
}
Also, don't forget that hex strings can start with "0x". This might be (more) difficult to do, so I would get the regular function working first. If you tackle it later, try to keep in mind that 0xABCD0x123 shouldn't pass. :-)
About substring: Straight from the String class source:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
offset is a member variable of type int
value is a member variable of type char[]
and the constructor it calls is
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
It's clearly an O(1) method, calling an O(1) constructor. It can do this because String is immutable. You can't change the value of a String, only create a new one. (Let's leave out things like reflection and sun.misc.unsafe since they are extraneous solutions!) Since it can't be changed, you also don't have to worry about some other Thread messing with it, so it's perfectly fine to pass around like the village bicycle.
Since this is homework, I only give some hints instead of code:
Write a method that always tests the first character of a String if it fulfills the requirements. If not, return false, if yes, call the method again with the same String, but the first character missing. If it is only 1 character left and it is also a hex character then return true.
Pseudocode:
public boolean isHex(String testString) {
If String has 0 characters -> return true;
Else
If first character is a hex character -> call isHex with the remaining characters
Else if the first character is not a hex character -> return false;
}
When solving problems recursively, you generally want to solve a small part (the 'base case'), and then recurse on the rest.
You've figured out the base case - checking if a single character is hex or not.
Now you need to 'recurse on the rest'.
Here's some pseudocode (Python-ish) for reversing a string - hopefully you will see how similar methods can be applied to your problem (indeed, all recursive problems)
def ReverseString(str):
# base case (simple)
if len(str) <= 1:
return str
# recurse on the rest...
return last_char(str) + ReverseString(all_but_last_char(str))
Sounds like you should recursively iterate the characters in string and return the boolean AND of whether or not the current character is in [0-9A-Fa-f] with the recursive call...
You have already received lots of useful answers. In case you want to train your recursive skills (and Java skills in general) a bit more I can recommend you to visit Coding Bat. You will find a lot of exercises together with automated tests.

Categories

Resources