Index out of range - java

I want my program to mingle to strings in an array. The strings are coming from a .dat file. I keep getting an index out of range error.
the input file :
3
xyz abc
abc rstuvwxy
rstuv ab
wanted output:
axbycz
rasbtcuavbwcxayb
rasbtaubva
error i'm getting:
arbsctException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at test.main(test.java:39)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("strings.dat");
Scanner infile = new Scanner(file);
String string1;
String[] mingle = new String[2];
int length;
infile.nextLine();
while (infile.hasNextLine()) {
string1 = infile.nextLine();
for (int i = 0; i < mingle.length; i++) {
mingle = string1.toLowerCase().split("[\\s.]");
}
System.out.println(mingle[1] + mingle[0]);
if (mingle[0].length() > mingle[1].length()) {
length = mingle[0].length();
}
else if (mingle[1] == mingle[0]) {
length = mingle[1].length();
}
else {
length = mingle[1].length();
}
for (int i = 0; i < length; i++) {
System.out.print(mingle[0].charAt(i % length));
System.out.print(mingle[1].charAt(i % length));
}
}
infile.close();
}
}
Subsequent Error
arbsctException in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range:
3 at java.lang.String.charAt(Unknown Source) at
test.main(test.java:39)

The second for loop would not always work. Since the value of length would either be the length of mingle[0] or mingle[1], you cannot have both the array elements within the same loop.
For Example. Assume length of mingle[0] is 10 whereas length of mingle[1] is 11. Since length of mingle[1] is greater, the value of length would be '11'.
In this case, at the 11th iteration of the for loop (i.e. when i=10) then
//At 11th iteration, i=10, length=11
for (int i = 0; i < length; i++) {
System.out.print(mingle[0].charAt(i % length)); //equivalent of mingle[0].charAt(10)
System.out.print(mingle[1].charAt(i % length));//equivalent of mingle[1].charAt(10)
}
Since characters in mingle[0] can be accessed from 0-9, when accessing the 10th element you get the java.lang.StringIndexOutOfBoundsException

I guess that's what you want to do. Note that the loop uses the minimum of the lengths. You can print the excess of either string using substr.
private void merge( s1 String, s2 String ){
int len = Math.min( s1.length(), s2.length() );
for( int i = 0; i < len; ++i ){
System.out.print( s1.charAt(i) + s2.charAt(i) );
}
System.out.println( s1.substr(len) + s2.substr(len) );
}

#Python program
IndexError: list index out of range
example:
Team =["priya" ,"amanda" ,"sruthy"]
print(Team[3])
if you are trying to print the value at the position of 3,then you get index error
this happens because that's just way beyond your list size and list index starts at zero.

Related

Count Words Using indexOf

I can't use arrays, only simple Java (if, for, while, substring, length, indexOf)
public int howManyWords(String s){
myString = "I have a dream";
int count = 1;
int length = 0;
while(count>=0){
count = myString.substring(String.valueOf(length),myString.indexOf(" "));
count++;
length = myString.indexOf(" ");
}
return count;
}
Should return 4
First of all, you made infinite loop, because count is 1, and you just increase it.
Second, you haven't even try to write this code in some IDE, because it would throw you a syntax error, because you are assigning string to int, when you do count = myString.substring()
So, instead of using count in loop, you can use myString.indexOf
something like this could work if you don't care what is going to happen with myString
int count = 0;
while(myString.indexOf(" ") >= 0) {
count++;
myString = myString.substring(myString.indexOf(" ") + 1)
}
return count;
Let's assume that the string you are testing does not contain leading or trailing spaces, because that affects the solution. The example string in your question does not contain leading or trailing spaces.
Simply call method indexOf(String, int) in a loop and in each iteration you set the int parameter to one more than what you got in the previous iteration. Once the value returned by method indexOf() is -1 (minus one), you are done. But don't forget to add the last word after you exit the loop.
String myString = "I have a dream";
int count = 0;
int index = 0;
while (index >= 0 && index < myString.length()) {
index = myString.indexOf(" ", index);
System.out.println("index = " + index);
if (index >= 0) {
index++;
count++;
}
}
if (index < 0) {
count++;
}
System.out.println("count = " + count);
Edited : Added missing else case.
Try the following code :
Remove the counted words from your string using the substring and indexOf, and increment the count in each iteration.
public int countWords(String s){
String myString = "I have a dream";
int count = 0;
int length = myString.length();
while(length>0){
if((myString.indexOf(" ")!=-1) && (myString.indexOf(" ")+1)<length){
myString = myString.subString(myString.indexOf(" ")+1);
count++;
length = myString.length();
}
else {
length = 0;
break;
}
}
return count;
}
PS: Conventionally, your method names should denote actions, hence I suggested it to be countWords instead of howManyWords.

PigLatin translator giving out of bounds message when taking items from a vector

package piglatinTranslation;
import java.util.Scanner;
import java.util.Vector;
public class PigLatin {
public static void main (String[]args)
{
Scanner Input = new Scanner(System.in);
int words = 1;
Vector<Object> spacesList = new Vector<Object>();
Vector<Object> translatedWordList = new Vector<Object>();
String Phrase = Input.nextLine();
Input.close();
//Compares each character in the string 'Phrase'
//If a character is found as an empty space, it adds to the word count and saves the index of the space in a vector
for(int v = 0; v < Phrase.length(); v++)
{
char temp = Phrase.charAt(v);
String tempString = Character.toString(temp);
if(tempString.equals(" "))
{
words++;
spacesList.add(v);
}
}
//Takes each item in the vector (an integer for the index of each space within the sting)
// and creates a substring for each word, putting it though the translation method
// The translated word is added to a vector of strings
for(int v = 0; v < words; v++)
{
if(v == 0)
{
int subStrEnd = (int) spacesList.get(v);
Phrase.substring(1, subStrEnd);
translatedWordList.add(Translate.translateWord(Phrase));
}
else
{
int subStrStart = (int) spacesList.get(v - 1);
int subStrEnd = (int) spacesList.get(v);
Phrase.substring(subStrStart, subStrEnd);
translatedWordList.add(Translate.translateWord(Phrase));
}
}
//Takes each string in the vector and combines them into one string to be returned to the user
for(int v = 0; v < words; v++)
{
Phrase.concat((String) translatedWordList.get(v));
}
System.out.println(Phrase);
}
}
A user should be able to input a string, and have it replied back to them translated through pig Latin.
For example:
Input: Hello
Output: Ellohay
Input: Hello, how are you
Output: ellohay, owhay areyay ouyay
I keep getting an out of bounds error at line 43.
That line should, in theory use the temporary variable 'v', and use that as a pointer to take the stored integer, the index of a space, to be used to separate the string into word substrings.
Your vector is being populated correctly, it's just that when there are n words there are only n - 1 spaces. So you would only want to loop up to words - 1. Generally in these types of situations though, you would just use spacesList.size() and you don't need to use the words variable at all.

Getting "Exception in thread "main" java.lang.StringIndexOutOfBoundsException" in Java

The output is supposed to be each word of the array printed backwards with their own lines
public class Main
{
public static void main(String[] args)
{
String [] list = {"every", "nearing", "checking", "food", "stand", "value"};
String reverse = "";
int length = list.length;
for(int j=0; j<list.length; j++)
{
String word = list[j];
for ( int i = length - 1 ; i >= 0 ; i-- )
{
reverse = reverse + word.charAt(i);
}
System.out.println(reverse);
}
}
}
but I keep getting this message
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 5
at java.lang.String.charAt(String.java:658)
enter code here`at Main.main(Main.java:13)
I cleaned up your code a tiny bit. Don't rely on temporary variables that do not improve the readability of your code. Do try and use for-each loops (they improve readability). Applying those two points, gives us
String[] list = { "every", "nearing", "checking", "food", "stand", "value" };
for (String word : list) {
for (int i = word.length() - 1; i >= 0; i--) {
System.out.print(word.charAt(i));
}
System.out.println();
}
which is based on your original code. Personally, I would prefer to use StringBuilder and its' reverse() method. Like,
for (String word : list) {
System.out.println(new StringBuilder(word).reverse());
}
or in Java 8+, with a map like
Arrays.stream(list).map(s -> new StringBuilder(s).reverse())
.forEachOrdered(System.out::println);
for ( int i = length - 1 ; i >= 0 ; i-- )
The length value you are using above is the length of the list array, not the word.
Remember to empty reverse word after each loop:
System.out.println(reverse);
reverse = "";
if you don't flush you'll get:
yrev
yrevgnirae
yrevgniraegnikceh
yrevgniraegnikcehdoo
yrevgniraegnikcehdoodnat
yrevgniraegnikcehdoodnateula
instead of:
yrev
gnirae
gnikceh
doo
dnat
eula
Verify that the provided arguments are valid in Main.java:13. Check that the provided offset points to a valid index and that the count argument does not point to indices greater than the size of the string itself.
An alternate:
public String[] reverseString(String[] words)
{
String[] reverse=new String[words.length];
for(int i=0;i<words.length;i++)
{
//added for setting element as emptyString instead of null
reverse[i] = "";
for(int j=words[i].length()-1;j>=0;j--)
{
reverse[i]+=words[i].substring(j,j+1);
}
}
System.out.println(Arrays.toString(reverse));
return reverse;
}
In line 11, change
int i = length-1;
to
int i = word.length()-1;
and the exception will go away.

Looping through two separate if statements

The code below is a simplified version of a method I am working on for a java project. The method will sort through a list of items(two different categories), in this case 0,s and 1's. The code reads through an array of numbers stops at either 0 or 1 and then prints out both the 0 or one and the string of numbers following the 0 or 1. If a preceding string is a 1 or a zero then it will stop and switch to another if statement. However it only executes each statement once. However there is more in the array that it needs to read through and organize. I would like to set up some sort of loop so that it loops through the set of if statements until it has read through the entire array.
public class tester
{
public static void main(String[] args )
{
String flags[] = {"0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i,j,k,h;
int count = 0;
for (i = 0; i<flags.length; i++)
{
if (flags[i].equals("0"))
{
for (j=0; !flags[j].equals("1") ; j++)
{
count = j+1;
array[j] = flags[j];
zeros[j] = flags[j];
}
} else
if (flags[count].equals("1"))
{
j = 0;
for(k=count; !flags[k].equals("0");k++)
{
array[k] = flags[k];
j++;
ones[j-1] = flags[k];
}
}
}
for(i=0; i<zeros.length; i++)
{System.out.println(zeros[i]);}
System.out.println();
for(i=0; i<ones.length; i++)
{System.out.println(ones[i]);}
}
}
What it prints out now:
0
23
25
34
null
null
null
null
null
null
null
null
1
9
12
13
null
null
null
null
null
null
null
null
String flags[] = {"9","0","23","25","34","1","9","12","13","0","67","2","43"};
String array[] = new String[flags.length];
String zeros [] = new String[array.length];
String ones[] = new String[array.length];
int i;
boolean addingZeroes = false;
boolean addingOnes = false;
int zeroCount = 0;
int onesCount = 0;
for (i = 0; i<flags.length; i++) {
if (flags[i].equals("0")) {
zeros[zeroCount] = flags[i];
zeroCount++;
addingZeroes = true;
addingOnes = false;
} else if (flags[i].equals("1")) {
ones[onesCount] = flags[i];
onesCount++;
addingZeroes = false;
addingOnes = true;
} else if (addingZeroes) {
zeros[zeroCount] = flags[i];
zeroCount++;
} else if (addingOnes) {
ones[onesCount] = flags[i];
onesCount++;
}
}
for(i=0; i<zeroCount; i++) {
System.out.println(zeros[i]);
}
System.out.println();
for(i=0; i<onesCount; i++) {
System.out.println(ones[i]);
}
Hey, couple things were wrong. Basically, you need a little state machine where you need to know whether you are in the midst of storing the sequence after a 1 or a 0. I used the boolean values (eg addingZeroes) for that.
Then, you need to separately keep track of your element count (eg zeroCount) for each of the storage arrays. You might have 20 digits after a 0 and just 2 after a 1.
Finally, at the end, your length of your storage arrays is not what you want - you want the amount of values you ended up storing. That's why you got all those "nulls".
One other thing I noticed is that your j value is initialized always to 0 in the 0 block, so you would always be using the lowest values of the start array.

Returning the element number of the longest string in an array

I'm trying to get the longest method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part.
public static void main(String [] args)
{
Scanner inp = new Scanner( System.in );
String [] responseArr= new String[4];
for (int i=0; i<4; i++)
{
System.out.println("Enter string "+(i+1));
responseArr[i] = inp.nextLine();
}
int highest=longestS(responseArr);
}
public static int longestS(String[] values)
{
int largest=0
for( int i = 1; i < values.length; i++ )
{
if ( ????? )
}
return largest;
}
for (int i = 0; i < values.length; i++)
{
if (values[i].length() > largest)
{
largest = values[i].length();
index = i;
}
}
return index;
Note: initialize the int i with 0 - array index is 0-based.
Back in your main, you could then do System.out.println("Longest: " + responseArr[highest]); etc.
Here's how I'd write it:
public static int findIndexOfLongestString(String[] values)
{
int index = -1;
if ((values != null) && (values.length > 0))
{
index = 0;
String longest = values[0];
for (int i = 1; i < values.length; ++i)
{
if (values[i].length() > longest.length())
{
longest = values[i];
index = i;
}
}
}
return index;
}
You will want to store two things in your longestS method: the largest length so far, and the array index of the largest length. Also keep in mind that array indices start at 0 in Java. A for loop initialised with int i = 1 is actually going to start at the second index.
My solution:
public class JavaApplication3
{
public static void main(String[] args)
{
String[] big={"one","two","three"};
String bigstring=null;
int maxlength=0;
for(String max:big)
{
if(maxlength<max.length())
{
maxlength=max.length();
bigstring=max;
}
}
System.out.println(bigstring);
}
}

Categories