Reputation: 411
I'm trying to create a code to remove spaces in a user input String, but I receive an error at line 16.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at practice5.main(practice5.java:16)
Note: We are not allowed to use the replace method of Java. I need to code it manually.
Here's my code:
import java.util.Scanner;
public class practice5{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String line;
System.out.print("Sentence: ");
line = scanner.nextLine();
char phrase[] = line.toCharArray();
int i = 0;
int n = 0;
while(phrase[i] != '\0') {
if(phrase[i] == ' ') {
for(n=i; n<phrase.length; n++) {
phrase[n] = phrase[n+1];
}
}
i++;
}
String output = new String(phrase);
System.out.print(output);
}
}
Thank you!
Upvotes: 1
Views: 3983
Reputation: 2203
Try using below code it may help
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.print("Sentence: ");
line = scanner.nextLine();
char phrase[] = line.toCharArray();
String result = "";
for (int i = 0; i < phrase.length; i++) {
if (phrase[i] != ' ') {
result += phrase[i];
}
}
System.out.println(result);
}
Upvotes: 1
Reputation: 196
Use CharMatcher
to determine
whether a character is whitespace according to the latest Unicode standard
CharMatcher.whitespace().trimAndCollapseFrom("user input","");
Upvotes: 0
Reputation: 2508
Reason for error:ArrayIndexOutOfBound
suppose yor sentence is: abc.Now when you will execute your code...this is happening...
1st iteration: i is on the index 0(i.e at a).2nd iteration,i is on index 1 (i.e at b) and on 3rd iteration,i is on index 3 (on c),and again i is incremented by 1,so now i=4.Now
while(phrase[i]!='\0')
will return such exception because you are comparing value at index 4 while is not available.Hence,such exception is occuring.
Upvotes: 1
Reputation: 156
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15 at practice5.main(practice5.java:16)
The ArrayIndexOutOfBoundsException is thrown when a call to an array element is made at an index that does not exist.
In your code, at line 16, you are calling phrase[n+1]
which works fine for all cases except when n==(phrase.length-1)
because then n+1 will be equal to phrase.length
.
Length is counted starting from 1 whereas indices are counted starting from 0. Therefore, during the last iteration, phrase[n+1]
is equivalent to phrase[phrase.length]
which is an out of bound index.
You can correct it by reducing the loop iterations by 1.
Upvotes: 1
Reputation: 312404
Why reinvent the wheel? Just use String's replace
method:
String output = line.replace(" ", "");
Upvotes: 0
Reputation: 1171
You can use a function of the String class. Just use line.replace(" ","")
Upvotes: 1