Reputation: 21
I am working on a project for my Java class, and cannot seem to figure out how to fix this problem. Based on the exception, I understand that it lies within the string index length, however, I cannot seem to correct the problem. This is my first foray into learning Java, so please forgive me for the novice question.
Some background on the task at hand: I am attempting to import an ascii art file (.txt), convert it to csv format, and output to specified file. The method signature was provided by the instructor, and cannot be manipulated. This code compiles, but when run, an out of bounds exception citing my call to imageToNumRep
is thrown.
Here is my code for this particular section:
import java.io.*;
import java.util.*;
public class Convert{
public static void main(String[] args) throws FileNotFoundException {
File input=new File("Flag.txt");
File output=new File("result.txt");
imageToNumRep(input, output);
}
public static void imageToNumRep(File input, File output) throws FileNotFoundException {
Scanner in=new Scanner(input);
PrintStream out= new PrintStream(output);
int count=0;
while(in.hasNextLine()) {
count++;
String s=in.nextLine();
out.print("(");
for(int x=0; x < s.length()-1; x++) {
int num=1;
while(s.charAt(x)==s.charAt(x+1)) {
num++;
}
out.print(num+s.charAt(x-1));
num=1;
if(s.charAt(x) != s.charAt(x-1) && s.charAt(x) != s.charAt(x+1)) {
out.print("1,"+s.charAt(x));
} else {
num=1;
}
}
out.print(")");
out.println();
}
}
}
Upvotes: 0
Views: 604
Reputation: 34146
Your are looping from index 0
to s.length()-2
(s.length()-1
won't be included because of the <
operator), this will avoid getting an exception if you call s.charAt(x+1)
, but when you do
s.charAt(x-1)
and x = 0
, then you will get an exception because it will be like s.charAt(-1)
, which is not valid.
What can you do?
You can iterate starting from 1
:
for(int x = 1; x < s.length() - 1; x++)
Upvotes: 2
Reputation: 741
In addition to the previous answer, and at first glance,
while(s.charAt(x)==s.charAt(x+1)) {
num++;
}
should never terminate, since you are not changing the value of x. You might be lucky in the case that the first two consecutive chars are not equal however.
Upvotes: 1