stringoutofboundexception in java (due to long string) [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting a StringIndexOutOfBoundsException for a long string. Basically the program is reading string from text file and for some reason i am getting error when I use long strings. For e.g. if use a=b+c or a=b or a=b+c-d*a this all works but when i put long strings such as "programming" or "javatutorial" this gives me a StringIndexOutOfBoundsException. At first I thought this was due to the fact that I am not checking whether or not x is empty but that is not the case this is occurring due to the length of the string itself. I would appreciate if someone could help.
while (scan.hasNext()) {
String x = scan.nextLine();
try
{
if(!x.isEmpty())
{
char ch=x.charAt(0);
s=String.valueOf(ch);
}
}
catch(StringIndexOutOfBoundsException siobe)
{
System.out.println("invalid input");
}
}

With the partial code you provided, all we can tell you is that the exception is being thrown because you are using the method:
String.charAt(int index)
on a String that does not have a character at the 'index'-th position.
For example, if String word = "cat", then word.charAt(8) would throw an exception because 'cat' only has three characters.
Search through your code for all the places that you used the charAt(int index) method and test that 'index' is indeed less than String.length(). Your error shows an argument of '11', so you can narrow your search to the location where you called the charAt() method with an index of 11. (This may be inside a loop).

Related

why does the loop on this program time out? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
it works fine for some strings, but for some reason it does not work for the last three. I see no difference to the type of strings being entered and I expect indx to evaluate to -1, but for some reason it does not on the last three strings. I don't understand why.
edit: problem solved. As you guys said, I was taking the substring of str instead of news within the loop. Sorry for such a simple mistake guys, I'm just starting to code and these are the details I need to pay attention to more. Also as I am working within the codingbat website there is no debugger, but I also want to highly recommend that website for other beginners. It will give you many example problems to begin coding on. Thanks again.
enter image description here
code:
public String stringYak(String str) {
int indx = str.indexOf("yak");
String news =str;
for(;indx!=-1;)
{
news = (str.substring(0,indx) + str.substring(indx+3,str.length()));
indx = news.indexOf("yak");
}
return news;
}
Because loop never breaks.
You are taking substring from str index from news inside the loop.
May be you want to take both substring and index from news.

Search a string array for a specific string. [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was hoping someone could help. Well I know how to use linear search to find a numerical value inside of an array. But now I want to learn how to search a string array for a string.
For example if I have a string array of students names how could I search the array to find a specific name inside that array?
If someone could write me a simple example since I'm new to Java still. Thank you, also is there a better way to search these kinds of things or linear search fine? :)
Use Arrays.asList() to wrap the array in a List. Then search in the List using contains() method:
String[] a= {"is", "are", "then"};
Arrays.asList(a).contains("are");
You can do using arrays also, but have to write some more lines of code. contains() method also does the linear search only.
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
The code for Strings can be the same as for numerical values, except you should use the String class's equals(...) method instead of ==.
You should use equals(...) because it's possible for two different String objects to have the same characters. But == would be incorrect because they are different objects.
Examples comparison expressions:
myArray[i].equals(myString)
or
myString.equals(myArray[i])
Note: Be sure the part on the left side isn't null. Otherwise you will get a NullPointerException.

Checking data string fits a 6 digit number format from input file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I got some data.txt file with N-string. Each string consists of 6 digits separating by space. I need to read this but before I need to check data format (I mean that each line must consist only 6 and only digits).
Do I need to use regexp?
Yes, you can do it with a regex.
One way to do this is to check if for each row you read, you have digits only, and add a constraint for the number of digits. The digits part can be done pretty easily, using a "/d" while the number of characters to be used is constrained by "{desiredNumber}".
To better understand regex in Java, use this link :D
If you still cannot solve it, this is the magic line:
if (!newLine.matches("\\d{6}")) {
return false;
}

Handling Invalid Character Constant [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have been working on a data compression and decompression program in java. At some point in my code, I want to visit only the nodes with keys. The part of the code looks like this:
//visit only nodes with keys
if(n.alpha != '\0') {
System.out.println("{" + n.alpha + ":" + s + "}");
charToCode.put(n.alpha, s);
codeToChar.put(s, n.alpha);
}
'\0' gives me an invalid character constant. I need to know what is going on, and how I can remedy the situation. Thanks!
You're trying to represent and treat a String as a char
n.alpha != '\0' // single quotes denote a character
You need to use a String instead
n.alpha != "\0"
Then, because the equality operator generally shouldn't be used with Strings, and because you're incorrectly testing the equality between a String and a char, you need to rewrite it as
if(!Character.toString(n.alpha).equals("\0"))
Note the use of Character.toString(n.alpha) to convert the char n.alpha to a String.

String comparison is wrong [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have a little/huge problem with String comparison in Java, I want to compare two Strings and .equals([...]) does not give me the correct result.
I also tried the following: ==, .compareTo([...]), .trim(), .equalsIgnoreCase([...]), creating a Collator with default Locale and using [collator].compare.
(All fail to work)
The first String comes from an already created object (the content of the string is from a database), the second String comes from a newly created object (but has been passed to a method), the content of this String is from the same database.
I am pretty clueless what to do now, the last thing I'd try is to convert it to some number (i.e. hex).
I already tried to write both Strings to console and manually look for differences, but there is none...
Code is this:
public static Lagerplatz hinzufuegen(Lagerplatz lagerplatz) {
boolean neu = true;
if (lagerplaetze.isEmpty()) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " erstmalig hinzugefügt!");
}
for (int i = 0; i < lagerplaetze.size(); i++) {
System.out.println("'" + lagerplatz.getBezeichnung() + "'" + " - " + "'"
+ lagerplaetze.get(i).getBezeichnung() + "'");
if (lagerplatz.getBezeichnung().equalsIgnoreCase(lagerplaetze.get(i).getBezeichnung())) {
neu = false;
}
}
if (neu) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " hinzugefügt!");
}
return lagerplatz;
}
The if-part with (lagerplaetze.isEmpty()) does work, after the first one is added it should check if the Lagerplatz (at least the name of it) is already in the lagerplaetze-ArrayList, if so then don't add, if not add.
Stepping through it revealed that the objects are correctly referenced...
Thanks very much in advance, and sorry if this question has been answered already but I can't find a helping answer under all these questions...
EDIT1: Normalizing does not help in this case, "umlaute" (german ä, ö or ü) are not causing the problem...
Converting the String to a byte[] and converting this byte-array to String like:
(Arrays.toString(lagerplatz.getBezeichnung().getBytes()).equalsIgnoreCase(
Arrays.toString(lagerplaetze.get(i).getBezeichnung().getBytes())))
and then comparing it does also not solve the problem, the bytes of the two strings are exactly the same: '[72, 55, 48]' - '[72, 55, 48]'
EDIT2: The problem is not with the String comparison, it is because the variables of the class "Lagerplatz" are static, they were replaced each time the loop is entered...
Maybe delete this question?
The only time two strings that look exactly the same but equals() does not result in true is when the unicode composition is different.
For example one can compose the A umlaut (Ä) with a single character: \u00C4
Or with a combination of the A character and the dots (the dieresis character ¨): \u0041\u0308
In essence, you are using two unicode characters for one letter. Because equals() compares characters, the form with dieresis is not equals to the form without.
To overcome this problem, one must decompose each string to a canonical form before comparison.
In Java one can create such a canonical form like this:
java.text.Normalizer.normalize("Your String", java.text.Normalizer.Form.NFD);
Once normalized, equals() will work as expected.
Obviously, since you didn't provide any data, this answer may or may not match your problem.
In any case, you might want to normalize all Strings in some form and then use a Set as data structure, not a list.

Categories