Can any one help me? I do not understand this exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.lang.String.charAt(Unknown Source)
at charPerLine.main(charPerLine.java:13)
Here's the code responsible:
import java.util.*;
public class charPerLine {
public static void main(String[] args)throws StringIndexOutOfBoundsException {
Scanner sc=new Scanner(System.in);
System.out.print("Type any name:");
String s=sc.next();
int j= s.length()+1;
for(int i=0;i<=j;i++){
System.out.println(s.charAt(i));
}
}
}
You're trying to directly access the 10th character of a string which has less than 10 characters. Something like:
"12345".charAt(9)
Remember that String indices are 0-based, hence .charAt(9) => 10th character. So "123".charAt(3) would throw, too.
You are referencing a character at position 9, which is outside the range of the actual string. Remember to check that it's within the range [0, length[.
Ah. Thanks to Greg for spotting the link to the other half of this question. He is right, it isn't fair.
Your for loop goes from 0 to whatever the length of s is plus one.
So if s was an array:
['a','b','c']
Then it would go from 0 to 4. The indexes of that array are 0, 1 and 2. So you are trying to access two point beyond the end.
You want to remove this line:
int j= s.length()+1;
And change the for loop to:
for(int i = 0; i < s.length(); i++){
j is s.length()+1 and then i is <=j. So: s.charAt(i) will eventually access index length()+1, which is 2 more than it is allowed to.
The loop should be:
for(int i=0; i < s.length(); i++){
System.out.println(s.charAt(i));
}
The last character in the string has index:
s.length() - 1
so you need to use the guard:
i < s.length()
This way your loop terminates before i becomes s.length().
The expression
s.charAt(i)
will throw an error, if i is larger or equal than s.length(). Try using
for (int i=0; i<s.length(); i++)
// ...
instead.
just replace the
int j= s.length()+1;
for(int i=0;i<=j;i++){
...
}
with
int j= s.length();
for(int i=0;i<j;i++){
...
}
:)
Related
I found problem which I don't know how to solve, so I need your help. Code example:
StringBuilder builder = new StringBuilder();
Integer x = -239;
char[] y = String.valueOf(x).toCharArray();
for(int i = 0; i < y.length; i++){
builder.append(y[i]);
System.out.println(builder);
}
And problem with outPut. I see something like that : - -2 -23 -239, but I need to have output without first symbol which is -
Simply start to iterate over the array beginning with the second index.
Your for loop starts with i at 0 and therefore starts on the first index of the char array.
Assign 1 to i in the for-loop and you will iterate over the whole array without the first character.
for(int i = 1; i < y.length; i++){
builder.append(y[i]);
System.out.println(builder);
}
(Please keep in mind I have only been studying java for under a month on my own)
I am trying to make a program that simply tells you the last char of the name you give the program. Here is my code:
import java.util.Scanner;
public class LastCharacter {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("hey");
String name = reader.nextLine();
lastChar(name);
}
public static char lastChar(String text) {
char lastChar = '\0';;
int i = 0;
for (i = 0; i <= text.length(); i++) {
lastChar = text.charAt(i);
}
System.out.println(lastChar);
return lastChar;
}
}
Error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:658)
at LastCharacter.lastChar(LastCharacter.java:19)
at LastCharacter.main(LastCharacter.java:11)
Java Result: 1
I also know this can be made by subtracting the length of the string by 1, however I would like to know why this method isn't working. I don't really know how to word this but do strings and chars not get along? (pls dont make fun of me)
Thanks!
Java strings start at a base index of 0. Therefore, this line: for (i = 0; i <= text.length(); i++) { is trying to access an index that doesn't exist. The string main only goes from 0 to 3. So, when you try to access index 4, you get the out of bounds error.
Replace this line:
for (i = 0; i <= text.length(); i++) {
With this:
for (i = 0; i < text.length(); i++) { to fix the problem.
The problem is because Java uses a 0 index array for the string. This means that your for loop i <= text.length() is going to the last character +1. In a name like "Joe"
J = 0,
o = 1,
e = 2
The length of "Joe" is 3 and therefor the loop goes to index(3) which is out of the bounds of the character array.
Two things to take note here:
1.) The length() method in Java String class returns the number of characters of a string
2.) Java arrays uses zero-base index
So, to accomplish your task of getting the last character of the name string :
public static char lastChar(String text) {
int textLength = text.length();
char lastChar = text.charAt(textLength - 1); //first char starts from index 0
return lastChar;
}
Hope it helps.
You are out of bounds! The condition should be:
i < text.length()
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
Strings are 0 based, meaning the first index is 0. So for the string "mom", the 0th index is "m", the 1st index is "o" and the 2nd index is "m". That means this string doesn't have a third index, even though its length is 3! Based on that, your loop should be:
for (i = 0; i < text.length(); i++) {
lastChar = text.charAt(i);
}
However, there is an even better way to do it with no loops at all. We can simply get the character at the last index of the string without looping over each character. It is less complicated and more efficent:
lastChar = text.charAt(text.length() - 1);
So basically, I've created a contains method and it prints out the correct output I need but after it does this it gives me an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MethodTesting.main(MethodTesting.java:90)
Not sure why when it displays the output no worries? If anyone can give me an idea of what i'm doing wrong?? My code is below, i've tried adjusting the length to just length and length-1 as seen below. I've written the code in strings as opposed to char arrays however it wouldn't give me the right result. Hoping someone can shed some light perhaps?
//contains method
char[] st = "Hello World".toCharArray();
char[] substr = "llo".toCharArray();
for(int contains=0; contains<st.length-1; contains++){
if(substr[contains] == st[contains]){
for(int j=contains; j<st.length-1; j++){
if(st[j] == substr[j]){
}
else{
contains = -1;
}
}
}
System.out.println("CONTAINS");
System.out.println(contains);
}
Thanks, in advance!
Assuming that you are trying to search a substring of a string, this can be done in String.contains() method. If you are trying to implement the method yourself, then you have to change your code like this:
public static void main (String[] args)
{
char[] st = "Hello World".toCharArray();
char[] substr = "llo".toCharArray();
for(int contains = 0; contains < st.length - substr.length; contains++) {
int j;
for(j = 0; j < substr.length; j++) {
if(st[contains + j] != substr[j]) { // mismatch
break;
}
}
if (j == substr.length) // Every character in substr has been matched
System.out.println("Contains");
}
}
Your arrays aren't of equal length, yet in your second loop, you make an assumption that they are. contains can be a value higher than substr.length, and consequently, j will be, too.
To ensure that you don't step off the array while iterating, fix your bounds in your second loop.
Change for(int j=contains; j<st.length-1; j++) to for(int j=contains; j<substr.length; j++). This will ensure that your second loop is never executed if contains > substr.length, whereas it was executing as long as j < st.length()-1.
st array length and substr lengths are different.So the line
j<st.length-1; should be j<substr.length-1;
I have been trying to execute this program which many will find a bit useless. Nevertheless I have been getting this error:Exception in thread "main" java.lang.StringIndexOutOfBoundsException while executing.this program is to find the number of vowels,consonants,special characters etc. and I recently got this error.Please help me. What is this error and how do I remove it from my code .Thanks in advance.
import java.io.*;
public class numberof {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter string");
String str=br.readLine();
int vowel=0,consonant=0,upcase=0,locase=0,special=0,dig=0;
int l=str.length();
for(int in=1;in<=l;in++){ //This also is being displayed as an error
char c=str.charAt(in); //This is the error Line.
if(c>=65||c<=90||c>=97||c<=123){
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='o'||c=='O'|c=='u'||c=='U'){
vowel++;
if(c>=65 && c<=90){
upcase++;
}
else{
locase++;
}
}
else{
consonant++;
if(c>=65 && c<=90){
upcase++;
}
else{
locase++;
}
}
}
else if(c>=48 && c<=57){
dig++;
}
else{
special++;
}
}
System.out.println(upcase+" "+locase+" "+vowel+" "+consonant+" "+dig+" "+special);
}
}
for(int in=1;in<=l;in++)
should be
for(int in=0;in<l;in++)
Array index starts from ZERO (in =0 assuming you want from first element)
EDIT:
l is length of String[], let us say 5 split into a[0], a[1], a[2], a[3], a[4].
If you observe, now you can start from 0 (or) 1 (or) 2, but max you can go upto a[4] only, when you use in <=, loop will check until a[5] which throws indexoutofBounds exception.
In your for loop, you're starting at index 1 and looping while smaller or equal to.
for (int in = 1; in <= l; in++) {}
This means you'll loop 2 more than you're supposed to. So it should be:
for (int in = 0; in < l; in++) {}
Array indexes are zero based, so it loops from 0 to length and not from 1 to length.
Another way of writing this is like this:
for(int i = 0; i < str.length(); i++) {}
Most java developers will find this easier to read.
Do you want to search for vowels in all string, starting from first character? use for(int in=0; in<l; in++)
Im having a bit of a problem with this code each time i execute it it gives me an error
String index out of range: 'n'
n - is the no. of characters that is entered in the textbox pertaining to this code...
(that is textbox - t2.)it is stuck at that first textbox checking it does not go over to the next as mentioned in the array.
Object c1[] = { t2.getText(), t3.getText(), t4.getText() };
String b;
String f;
int counter = 0;
int d;
for(int i =0;i<=2;i++)
{
b = c1[i].toString();
for(int j=0;j<=b.length();j++)
{
d = (int)b.charAt(j);
if((d<65 || d>90)||(d<97 || d>122))
{
counter++;
}
}
}
it is basically a validation code that i am trying to do without exceptions and stuff(still in the process of learning :) )
any help would be appreciated
thx very much.
Use <, not <= when iterating over the string. With <=, you get an out of bounds error, when j equals the length of the string. Remember that characters in the string are indexed starting from zero.
for(int j = 0; j < b.length(); j++)
In java string.charAt(string.length()) will be out of bounds since the string is 0 indexed and so the last character is at string.length() - 1.
Strings are indexed starting at 0. Your second for loop is set to end at b.length, which will always be 1 greater than the highest index for that string., Change it to j < b.length instead.