0
    }

I have an input.txt file, i want call that from console. This file includes whitespaces and quotes. I write this code but it give me the error. Where is my fault in this code, guys?

Also, if (chars[i]=='"'){ j = i ; i++ ; while (chars[i] != '"'){ i++; } System.out.println(str.substring(j,i)); } because of the error, the print does not work.

1
  • You are making a basic mistake here. Arrays in java start at index 0, so even thought you have a length of N, the maximum array index is N-1. Commented Mar 27, 2014 at 10:50

3 Answers 3

1
while(i < chars.length)

and

i++ ;

will get you into trouble at

if (chars[i]=='"'){
Sign up to request clarification or add additional context in comments.

Comments

0

What happens if the last character of the string is ' '?

Look at the case of the string " " (single space)

while(i < chars.length) // i == 0
  chars[0] == ' ' // true;
  i++; // i = 1 (past array end)
  if (chars[1] == '"') // you've accessed past the end of the array and you get the exception

5 Comments

The exception part solved with this way. But my code doesn't work with quotes. It does not seperate quotes, only whitespace. How can I solve this?
What are you trying to achieve here? If you can, use a builtin like String replaced = str.replaceAll("[ \"\']", "") to remove all spaces, single and double quotes from the string.
I want to split all words. In input.txt, i have to seperate these words with spaces and quotes. For example; a b c "d e"
use String[] res = str.split("[ \'\"]"); which splits a string into an array of strings.
I know that split function. This parsing only whitespace again
0

I think you should check "i" variable always after "i++" operation - checking it in most outside while isn't enough, you can go out the array size

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.