Getting "Exception in thread "main" java.lang.StringIndexOutOfBoundsException" in Java - 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.

Related

LeetCode 14. longest common prefix

Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}

Index out of range

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.

Used an arraylist in Java to find four consecutive letters in a dictionary, error while building the code

This is the initial challenge I'm trying to address
1) takes two arguments—a “source" English word in a string, and an English dictionary supplied in an array
2) returns a list of English words as an array
The words returned are those from the dictionary that have four consecutive letters (or more) in common with the “source” word. For example, the word MATTER has the four letters in a row “ATTE" in common ATTEND.
The code however gives me errors with the substring
Below is the code for your reference.
public class FourLetterInCommon {
static String wrd = "split";
static String[] d = new String[]{"SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS", "SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS"};
public static void main(String[] args){
System.out.println(fourletters (wrd, d));
}
public static List<String> fourletters (String word, String[] dict){
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for(int i = 0; i<=dictsize; i++) {
for (int j=0; j<=wordlength;) {
if(dict[i].contains(word.substring(i, 5)))
{
Commonletters.add(dict[i]);
}
break;
}
}
return Commonletters;
}
}
This is the error message I get:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at FourLetterInCommon.fourletters(FourLetterInCommon.java:22) at FourLetterInCommon.main(FourLetterInCommon.java:10)
What does the errors mean? Apologies, but a bit clueless at this stage.
Quite a few issues here.
1)
for(int i = 0; i<=dictsize; i++) {
should be
for(int i = 0; i<dictsize; i++) {
2)
for (int j=0; j<=wordlength;) {
should be
for (int j=0; j<=wordlength-4; j++) {
3)
if(dict[i].contains(word.substring(i, 5)))
should be
if(dict[i].contains(word.substring(j, j+4)))
4)
I don't believe you really want to break; there. I'm guessing you want to break when you find a match, so it should be inside the if statement.
Corrected code:
public class FourLetterInCommon
{
static String wrd = "SPLIT";
static String[] d = new String[] { "SPLITS", "SPLITTED", "SPLITTER", "SPLITTERS", "SPLITTING", "SPLITTINGS",
"SPLITTISM", "SPLITTISMS", "SPLITTIST", "SPLITTISTS" };
public static void main(String[] args)
{
System.out.println(fourletters(wrd, d));
}
public static List<String> fourletters(String word, String[] dict)
{
int dictsize = dict.length;
int wordlength = word.length();
List<String> Commonletters = new ArrayList<String>();
for (int i = 0; i < dictsize; i++)
{
for (int j = 0; j <= wordlength - 4; j++)
{
if (dict[i].contains(word.substring(j, j + 4)))
{
Commonletters.add(dict[i]);
break;
}
}
}
return Commonletters;
}
}
Output:
[SPLITS, SPLITTED, SPLITTER, SPLITTERS, SPLITTING, SPLITTINGS, SPLITTISM, SPLITTISMS, SPLITTIST, SPLITTISTS]
The following line would throw an Exception:
if(dict[i].contains(word.substring(i, 5)))
Here, i ranges from 0 to dict.length which is 10 in this case. word contains 5 characters only. So, accessing any character from index 5 onwards would throw an Exception.
If you want to check for certain number of characters then you should use this:
for (int j=0; j < wordlength;) {
if(dict[i].contains(word.substring(j, wordlength - j)))

trying to print transpose string[]

So i've been trying to take a txt file which has input like this for eg -
abcddhdj
efghdd
ijkl
to get this -
j
d
hd
dd
dhl
cgk
bfj
aei
i have tried to do this using 2d char array which gave nullexception and arrayoutofbound error and didnt work mostly,then tried string array , arraylist of arraylist of char , and lastly i have been trying using arraylsit of string
here is the closest i got to my solution after lot of searching by using string[] -
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")); // PUT YOUR FILE LOCATION HERE
int k=0,i,j=0,x;
String line[] = new String[10] ; //SET THE APPROXIMATE NUMBER OF ROWS
while((line[k] = br.readLine()) !=null)
{System.out.println(line[k]); //print to check input - verified
k++;
}
for(x=0;x<k;x++)
{if(j<line[x].length())
{j=line[x].length()-1;} //this part not working in above loop
}
System.out.println(j); // verified but not working inside previous loop for some reason
System.out.println(k);
for(x=j-1;x>=0;x++) //without this loop,its perfect, but with it gives indexoutofbound error , doesnt run at x=j
{ for(i=0;i<k;i++)
{ System.out.print(line[i].charAt(x));
}
System.out.println();
}
}
here is one output
run:
abcd
efgh
ijkl
4 //should have come as 3 since i did length-1
3
chl //notice the d missing , every char of first row shifted,just why
bgk //in outofbound error , it only prints d at the end, need explanation
afj
ei
BUILD SUCCESSFUL (total time: 0 seconds)
if i add a space after abcd it gives indexoutofbound and no output after k
at end i used another method which adds spaces to make all length equal
yet still the output was wrong, plus there is something wrong with this way of thinking , there should be better method
so i tried arraylist , this is giving me more problems again
trying to work this out by any method understandable.
This ought to do the trick:
The key here is that I pad all the line arrays with empty chars so that each character array is the same length as the longest line.
public static void main(String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")))
{
String line;
List<List<Character>> lines = new ArrayList<>();
int longestLine = 0;
while((line = br.readLine()) !=null)
{
line = line.trim();
if (line.length() > 0)
{
List<Character> currList = new ArrayList<>();
for (char c : line.toCharArray())
{
currList.add(c);
}
if (currList.size() > longestLine)
{
longestLine = currList.size();
}
lines.add(currList);
}
}
// pad all lists to be the same as the longest
for (List<Character> currList : lines)
{
while (currList.size() < longestLine)
{
currList.add(Character.MIN_VALUE);
}
}
// go through each list backwards
for (int i = longestLine - 1; i >= 0; i-- )
{
for (List<Character> currList : lines)
{
System.out.print(currList.get(i));
}
System.out.println();
}
}
catch (Throwable t)
{
t.printStackTrace();
}
}
Example Input:
abcd
efgh
ijkl
g
Example Output:
dhl
cgk
bfj
aeig
Assuming input is read into the arraylist
ArrayList<String> inputList = new ArrayList<String>();
inputList.add("abcddhdj");
inputList.add("efghdd");
inputList.add("ijkl");
int maxSize = 0;
for (String input : inputList) {
if (input.length() > maxSize) {
maxSize = input.length();
}
}
String outputList[] = new String[maxSize];
for (int i = 0; i < maxSize; i++) {
String output = "";
for (String input : inputList) {
if(i<input.length())
output=output+input.charAt(i);
}
outputList[maxSize-(i+1)]=output;
}
Store all to direct 2d array and transpose in printing loop
final char[][] matrix = Files.lines(Paths.get(fileName)).map(String::toCharArray).toArray(char[][]::new);
final int width = Arrays.stream(matrix).mapToInt(a -> a.length).max().getAsInt();
for (int i = 0; i < width; ++i ) {
final int idx = width-i-1;
String s = Arrays.stream(matrix).map(a -> a.length > idx ? String.valueOf(a[idx]) : " ").collect(Collectors.joining());
System.out.println(s);
}

NullPointerException error while trying to remove a string word from an Array in a remove() method

I'm making this method remove() which takes a String word as argument, to delete from a global Array "words", but I keep getting a NullPointerException for some reason I cannot find, been stuck for hours.
Basically I check for if the word is in the first position, else if is in the last position, or else if it is in neither so I check all the array, and add the first half before the position of the word, and then add the second half after the position of the word in the array, as to skip it and "delete it". But I'm getting a NullPointerException in the for loop looking for the position of the word in the array. Code for the method is here:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
Also, if theres any suggestions for good coding practice would be appreciated, thanks!
** I can only use Arrays as my data structure for this method.
Modify the condition like this
a.equals(words[0])
because you know the string value a. But dont know what value will come from array. So even null value comes from the array it does allow the null pointer exception.
I run your code and find a few errors, I correct somethings without changing the core idea:
} else { // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
If the original array could't have null elements I would do like this:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
I would do that like this:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
I have a question for you:
Why oh why are you using an array? You should always use a collection (eg a List) unless you absolutely have to use an array (which is rare indeed).
If it were a List, you wouldn't even need this method, because List has the remove() method that does all this for you!

Categories