Error:Exception in thread "main" java.lang.StringIndexOutOfBoundsException - java

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++)

Related

java.lang.ArrayIndexOutOfBoundsException error in java

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;

No Such Element Exception when reading from a file

I understand that this is a commonly asked question, however, I'm not sure why I'm getting the error even after doing research.
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("input.txt"));
}
catch(Exception e){
System.out.println("Oh noes, the file has not been founddd!");
}
}
public void readFile(){
int n = 0;
n = Integer.parseInt(x.next()); //n is the integer on the first line that creates boundaries n x n in an array.
System.out.println("Your array is size ["+ n + "] by [" + n +"]");
//Create n by n array.
int[][] array = new int[n][n];
//While there is an element, assign array[i][j] = the next element.
while(x.hasNext()){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
array[i][j] = Integer.parseInt(x.next());
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}
}
public void closeFile(){
x.close();
}
}
I'm reading a text file that contains an adjacency matrix, where the first line indicates how large the matrix will be. ie) line 1 reads 5. Therefore I create a 2d array that is 5x5. The problem I'm having is after I read the file and print it, I get a NoSuchElement Exception. Thanks ahead of time!
Note: I am curious, I've seen that I need to user x.hasNext() when in a loop, so I do not assume there is input when there isn't. However, I've done this. Not sure what the problem is.
Output:
Your array is size [7] by [7]
0110011
1000000
1001000
0010001
0000001
1000001
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at readfile.readFile(readfile.java:32)
at verticies.main(verticies.java:8)
It looks like your code is reading a whole line as an int, is each of those numbers:
0110011 1000000 1001000 0010001 0000001 1000001
meant to be the 7 digits forming each row?
If that is the case, you need to split each value into the its component parts for its corresponding sub array.
In which case, use this section of code instead:
while(x.hasNext()){
for(int i = 0; i < n; i++){
String line = x.next();
for(int j = 0; j < n; j++){
array[i][j] = line.charAt(j) - '0';
System.out.printf("%d", array[i][j]);
}
System.out.println();
}
}

Java Double Array

I'm having trouble setting up and placing values into an array using a text file containing the floating point numbers 2.1 and 4.3 each number is separated by a space - below is the error I'm getting:
Exception in thread "main" java.util.NoSuchElementException
import java.util.*;
import java.io.*;
public class DoubleArray {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("mytestnumbers.txt"));
double [] nums = new double[2];
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++;
nums[index] = in.nextDouble();
}
}
}
Thanks, I'm sure this isn't a hard question to answer... I appreciate your time.
You should always use hasNext*() method before calling next*() method
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[1] = in.nextDouble();
}
}
but I think you are not doing the right, I'd rather
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[counter] = in.nextDouble();
}
}
NoSuchElementException is thrown by nextDouble method #see javadoc
I would suggest printing the value of index out immediately before you use it; you should spot the problem pretty quickly.
It would appear you're not getting good values from your file.
Oli is also correct that you have a problem with your index, but I would try this to verify you're getting doubles from your file:
String s = in.next();
System.out.println("Got token '" + s + "'"); // is this a double??
double d = Double.parseDouble(s);
EDIT: I take this partly back...
You simply don't have tokens to get. Here's what next double would have given you for exceptions:
InputMismatchException - if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
I did not understand what you are trying to do in your loop ?
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++; <--------
nums[index] = in.nextDouble();
}
You are declaring index = 0 then incrementing it to 1 and then using it.
Why are you not writing int index = 1; directly ?
Because it is getting declared to be zero each time loop is run and then changes value to 1.
Either you should declare it out side the loop.
You should initialize index outside of your for loop.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
index++;
nums[index] = in.nextDouble();
}
Your index was getting set to zero at the beginning of each iteration of your for loop.
EDIT:
You also need to check to make sure you still have input.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
if(!in.hasNextDouble())
break;
index++;
nums[index] = in.nextDouble();
}
Every time the cycle does an iteration, it's declaring the variable index and then you increase index with index++. Instead of using index, use counter, like this: num [counter] = in.nextDouble().
Check your mytestnumbers.txt file and ensure that the data that you are trying to scan is in the correct format. The exception that you are getting implies it is not.
Keep in mind that in.nextDouble() will be searching for double numbers separated by white space. In other words, "4.63.7" is not equal to "4.6 3.7" — the space is required. (I do not remember off the top of my head, but I believe that nextDouble() will only search for numbers containing a decimal point, so I do not believe that "4" is equal to "4.0". If you are seeking decimal numbers with this method, then you should have decimal numbers in your file.)

Why am I getting java.lang.StringIndexOutOfBoundsException?

I want to write a program that prints words incrementally until a complete sentence appears. For example : I need to write (input), and output:
I
I need
I need to
I need to write.
Here is my code:
public static void main(String[] args) {
String sentence = "I need to write.";
int len = sentence.length();
int numSpace=0;
System.out.println(sentence);
System.out.println(len);
for(int k=0; k<len; k++){
if(sentence.charAt(k)!='\t')
continue;
numSpace++;
}
System.out.println("Found "+numSpace +"\t in the string.");
int n=1;
for (int m = 1; m <=3; m++) {
n=sentence.indexOf('\t',n-1);
System.out.println("ligne"+m+sentence.substring(0, n));
}
}
and this is what I get:
I need to write.
16
Found 0 in the string.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at
java.lang.String.substring(String.java:1937) at
split1.Split1.main(Split1.java:36) Java Result: 1 BUILD SUCCESSFUL
(total time: 0 seconds)
I don't understand why numSpace doesn't count the occurrences of spaces, nor why I don't get the correct output (even if I replace numSpace by 3 for example).
You don't have a \t character, so indexOf(..) returns -1
You try a substring from 0 to -1 - fails
The solution is to check:
if (n > -1) {
System.out.prinltn(...);
}
Your loop looking for numSpace is incorrect. You are looking for a \t which is a tab character, of which there are none in the string.
Further, when you loop in the bottom, you get an exception because you are trying to parse by that same\t, which will again return no results. The value of n in n=sentence.indexOf('\t',n-1); is going to return -1 which means "there is not last index of what you are looking for". Then you try to get an actual substring with the value of -1 which is an invalid substring, so you get an exception.
You are mistaken by the concept of \t which is an escape sequence for a horizontal tab and not for a whitespace character (space). Searching for ' ' would do the trick and find the whitespaces in your sentence.
This looks like homework, so my answer is a hint.
Hint: read the javadoc for String.indexOf paying attention to what it says about the value returned when the string / character is not found.
(In fact - even if this is not formal homework, you are clearly a Java beginner. And beginners need to learn that the javadocs are the first place to look when using an unfamiliar method.)
The easiest way to solve this I guess would be to split the String first by using the function String.split. Something like this:
static void sentence(String snt) {
String[] split = snt.split(" ");
for (int i = 0; i < split.length; i++) {
for (int j = 0; j <= i; j++) {
if (i == 1 && j == 0) System.out.print(split[j]);
else System.out.printf(" %s", split[j]);
}
}
}
As other people pointed out. You are counting every characters except tabs(\t) as a space. You need to check for spaces by
if (sentence.charAt(k) == ' ')
\t represents a tab. To look for a space, just use ' '.
.indexOf() returns -1 if it can't find a character in the string. So we keep looping until .indexOf() returns -1.
Use of continue wasn't really needed here. We increment numSpaces when we encounter a space.
System.out.format is useful when we want to mix literal strings and variables. No ugly +s needed.
String sentence = "I need to write.";
int len = sentence.length();
int numSpace = 0;
for (int k = 0; k < len; k++) {
if (sentence.charAt(k) == ' ') {
numSpace++;
}
}
System.out.format("Found %s in the string.\n", numSpace);
int index = sentence.indexOf(' ');
while(index > -1) {
System.out.println(sentence.substring(0, index));
index = sentence.indexOf(' ', index + 1);
}
System.out.println(sentence);
}
Try this, it should pretty much do what you want. I figure you have already finished this so I just made the code real fast. Read the comments for the reasons behind the code.
public static void main(String[] args) {
String sentence = "I need to write.";
int len = sentence.length();
String[] broken = sentence.split(" "); //Doing this instead of the counting of characters is just easier...
/*
* The split method makes it where it populates the array based on either side of a " "
* (blank space) so at the array index of 0 would be 'I' at 1 would be "need", etc.
*/
boolean done = false;
int n = 0;
while (!done) { // While done is false do the below
for (int i = 0; i <= n; i++) { //This prints out the below however many times the count of 'n' is.
/*
* The reason behind this is so that it will print just 'I' the first time when
* 'n' is 0 (because it only prints once starting at 0, which is 'I') but when 'n' is
* 1 it goes through twice making it print 2 times ('I' then 'need") and so on and so
* forth.
*/
System.out.print(broken[i] + " ");
}
System.out.println(); // Since the above method is a print this puts an '\n' (enter) moving the next prints on the next line
n++; //Makes 'n' go up so that it is larger for the next go around
if (n == broken.length) { //the '.length' portion says how many indexes there are in the array broken
/* If you don't have this then the 'while' will go on forever. basically when 'n' hits
* the same number as the amount of words in the array it stops printing.
*/
done = true;
}
}
}

What is wrong in in this code? [duplicate]

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++){
...
}
:)

Categories

Resources