This question already has answers here:
Java charAt() String index out of range: 0
(5 answers)
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I keep getting this error whenever I try to input an empty String. Everything else so far works and if I put a space inside the String it works. I know this is really picky but I'm super curious what I should do in this situation to make sure it returns just an empty String.
**> HW2.nthWord(2,"")
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at HW2.nthWord(HW2.java:124)**
I did create a special instance for when this value is put in but it still does not work.
What do I need to to correct this?
/*nthWord takes an int and a String as input and returns a String:
The input int represents a number n that is assumed to be positive, and the output string
contains every nth word of the input string, starting with the first word, separated by a single space.
For this method, a word is defined to be a sequence of non-space characters.
There should be no space at the end of the output string.
*/
public static String nthWord( int number, String input ){
StringBuilder create = new StringBuilder();
int totalspaces = 0; //This is to hold a count of the number of spaces in a String
if( number == 0){
return input;
}
if(input == ""){
return input;
}
else{
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
for( int i = 0; i < input.length() - 1 ; i = i + 1){
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
if(totalspaces % number == 0 && totalspaces != 0){
create.append(' ');
for(int j = i+1; input.charAt(j) != ' ' && j < input.length(); j = j+1){
create.append(input.charAt(j));
i = j;
}
}
}
}
return create.toString();
}
}
I noticed a few things
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
This loops will keep adding characters of "input" until it reaches a space' ' character. If input does not have a space character then this loop will go beyond the length of input and cause the error. You may want something like:
for(int i = 0; i < input.length(); i = i + 1){
if(input.charAt(i) == ' ' ){
break;
} else {
create.append(input.charAt(i));
}
}
Also, when you get to the line:
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
you already know that i < input.length() - 1 because you are in a for loop. You may change that line to:
if(input.charAt(i) == ' ' && input.charAt(i+1) != ' '){
For the same reason, your next section:
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
can be changed to
if( i != input.length()-1 ){
totalspaces = totalspaces + 1;
}
Also, I noticed that you may be making the problem harder than it needs to be. The problem will be much easier if you solve it in a single for-loop.
for(int i = 0; i < input.length(); i = i + 1){
if( x ) //x is some code that determines if you are part of the nth word
create.append(input.charAt(i));
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
When I submit my code to Leetcode, it reported runtime error as:
Runtime Error Message: Line 8: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
I tested that case in my local, it works fine. I thought it maybe causeed by the platform and compiler are different. I then tried to test it on Leetcode Playground. It also worked very well.
The Leetcode problem is:https://leetcode.com/problems/string-to-integer-atoi/
I would be very appreciated if anyone could let me know what's wrong with my code.
class Solution{
public int myAtoi(String str) {
if (str == null || str.length() == 0) return 0;
char chs[] = str.toCharArray();
long base = 0;
int i = 0, sign = 1;
while (chs[i] == ' ' && i < str.length()){
i++;
}
if(i == str.length()){
return 0;
}
if (chs[i] == '-') {
i++;
sign = -1;
} else if (chs[i] == '+') {
i++;
}
while (i < str.length() && (chs[i] >= '0' && chs[i] <= '9')) {
base = base * 10 + (chs[i] - '0');
if (sign * base > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign * base < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int)(sign * base);
}
}
If pass empty string (one space or more) to myAtoi(" ") in while statement you will go beyond the boundaries of the array:
// chs = {' '}; chs.length = 1; i = 0;
while (chs[i] == ' ') {
i++;
}
You can add an additional condition i < chs.length to while loop:
while (i < chs.length && chs[i] == ' ')
screenshot with result
I'm trying to #2 of the Canadian Computing Contest, but my solution doesn't work. It only reads the first few characters(the first three I believe) and just ends the loop, then proceeding to provide the adequate output based only on the first three characters.
Here is the past paper:http://cemc.uwaterloo.ca/contests/computing/2015/stage%201/juniorEn.pdf
My code
Scanner input = new Scanner(System.in);
String lines = input.next();
char[] line = lines.toCharArray();
int happy = 0;
int sad = 0;
int i = 0;
while(i < line.length)
{
if(line[i] == ':' && line[i+1] == '-')
{
if(line[i+2] == ')')
happy++;
else if(line[i+2] == '(')
sad++;
i+=3;
}
else i++;
}
if(happy == 0 && sad == 0)
System.out.print("none");
else if(happy == sad)
System.out.print("unsure");
else if(happy>sad)
System.out.print("happy");
else if (sad>happy)
System.out.print("sad");
consider that with
while(i < line.length)
if i == line.length - 1
then if you do
line[i+1]
you will exceeed the length or your array and get an OutOfBoundsException
I'm trying to set up a compression algorithm that places a number before a char in a string when that char can be seen in succession. EX: for the string
"balloonnnnns" it would be compressed to "ba2l2o5n" but I am receiving an index out of bounds error:
for(int i = 0; i < (length-1); i++ ){
if (original.charAt(i) == original.charAt(i + 1)){
count = count + 1;
original = original.substring(i, i+1);
System.out.println(original);
System.out.println(count);
if(count > 0){
altered = count + original.substring(i);
System.out.println(altered);
}
}else{
count = 0;
As #Jon Skeet pointed out you shouldn't change your original while in the loop.
You could try this way (comments on code for understanding)
Test:
public class Test
{
public static void main ( String [ ] args )
{
String original = "balloonnnnns";
int length = original.length ( );
int count = 1;
String altered = "";
//Loop over all string
for(int i = 0; i < (length-1); i++ ){
//while they are the same
while (original.charAt(i) == original.charAt(i + 1)){
//count and keep going on the original string
count++;
i++;
//avoid border case when last character is repeated, i.e : baaaaaaaa
if ( i == length -1)
{
break;
}
}
//if they are repetead
if(count > 1)
{
//add altered + count + charRepeated, i.e. a3e5t
altered = altered +count + original.charAt(i);
}
else{
//just add the normal character without count
altered += original.charAt(i);
}
//add last character if not repeated
if ( (i == length - 2) && (count > 1))
{
altered += original.charAt ( i+1 );
}
//reset counting
count = 1;
}
System.out.println ( altered );
}
}
Output:
ba2l2o5ns
The first time your loop gets executed, you update string named 'original' with the first character of actual 'original' string.
For eg. if String original = "aaa" - after loop executes for 0, value for original becomes 'a'!
You can refer this for solutions:
Java compressing Strings
This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 7 years ago.
I am trying to count the amount of 'x' characters that are in a string, and print out the number. I end up just counting the number of characters in the string instead. Here is what I have tried:
int count = 0;
for (int j = 0; j < input1.length(); j++)
{
char character = input1.charAt(j);
count++;
}
if (indexX != -1)
{
System.out.println("x count: "+count);
} // indexX = input1.indexOf('x');
You are not checking if the chacter is x, and then increasing the counter.
if(character == 'x')
counter++;
You never check what the character is.
char character = input1.charAt(j);
if (character == 'x') {
count++;
}
You need to check if the character is 'x'.
This is how you do it :
for (int j = 0; j < input1.length(); j++)
{
char character = input1.charAt(j);
if (character == 'x' || character == 'X') {
count++;
{
}
How about comparing length of string pre and post replace, have a look at http://www.rosettacode.org/wiki/Count_occurrences_of_a_substring#Java
Common method that would work everywhere.
for (int i = 0; i < str.length(); i ++) // Checks every position of array
{
arr[i] = str.charAt(i); // Ignore this, not needed
if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') // Checks every position of array to see if any character equals a comma, decimal point, or a dollar sign
{
// Ignore below
/*
valueString = String.valueOf(value);
numOfAsterisks = arr.length - valueString.length();
for (int asterisk = 0; asterisk <= numOfAsterisks; asterisk ++)
{
System.out.print("*");
}
System.out.println((int)value);
*/
}
}
Here, what I want to do is to check an array of characters and see if the array contains a comma, a decimal point, or a dollar sign. If the array does not contain any of these characters, then the commented-out portion (where it says "Ignore below") will be executed. The only problem I have here is that because if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') is under the outside for loop, the commented-out part is executed multiple times. I need the code to execute only once, but still check each position of the array.
If I understand your question correctly, what you actually want is something like this:
boolean found = false;
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$') {
found = true;
break;
}
}
if(!found) {
/* Your commented-out code */
}
Note that this can also be formulated as such:
skip: {
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$')
break skip;
}
/* Your commented out code goes here. */
}
Choose for yourself which you like more. :)