This question already has answers here:
"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" with ArrayList?
(4 answers)
Closed 6 years ago.
Can anyone tell me why this code isn't working? It throws an IndexOutOfBoundsException.
package blok6afvink6;
/**
*
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Blok6afvink6 {
public static void main(String[] args) throws FileNotFoundException {
//1st, use Scanner to readin all sequence names and sequences;
//create two arrayList to store sequence names and sequences;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> sequence = new ArrayList<String>();
Scanner ScanLine = new Scanner(new FileReader("OverlapGraph.txt"));
String seq = "";
while (ScanLine.hasNextLine()) {
String temp = ScanLine.nextLine();
if (temp.charAt(0) == '>') {
sequence.add(seq);
name.add(temp.substring(1));
seq = "";
} else {
seq += temp;
}
}
ScanLine.close();
sequence.remove(0);
sequence.add(seq);
//naam en seq printen
int Len = name.size();
for (int i = 0; i < Len; i++) {
System.out.println(name.get(i) + ": " + sequence.get(i));
}
//3rd, connect all sequences with O3 overlap, put the linked-names into a new string ArrayList
ArrayList<String> overLaps = linkOverlaps(name, sequence);
System.out.println("\nPrintout results:");
for (int i = 0; i < overLaps.size(); i++) {
System.out.println(overLaps.get(i));
}
}
private static ArrayList<String> linkOverlaps(ArrayList<String> name, ArrayList<String> sequence) {
ArrayList<String> overLap = new ArrayList<String>();
//int size = name.size();
for (int i = 0; i < name.size(); i++) {
int Len1 = sequence.get(i).length();
for (int j = 0; j < name.size(); j++) {
if (i != j && sequence.get(i).substring(Len1 - 3).equals(sequence.get(j).substring(0, 3))) {
String linked = name.get(i) + " " + name.get(j);
overLap.add(linked);
}
}
}
return overLap;
}
}
The error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at blok6afvink6.Blok6afvink6.main(Blok6afvink6.java:36)
Line 36 referenced in the exception appears to be:
sequence.remove(0);
This can only fail with this exception if the list was empty.
So one has to assume that sequence.add(seq); is never called.
If that's OK and expected, you could check for empty first:
if (!sequence.isEmpty()) {
sequence.remove(0);
}
try
if(sequence.size() > 0) {
sequence.remove(0);
}
Look closely at the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
It would seem that one of your collections has size 0. If so, that would cause this exception because you don't always check to make sure that the collections actually have any items before you try to access them.
Check sequence in particular.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
While executing below code I'm getting:
(Exception in thread "main" java.lang.IndexOutOfBoundsException:
Index: 3, Size: 3)
Please, suggest what could be the changes that I have to do.
import java.util.ArrayList;
import java.util.List;
public class Testing {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
List < String > list1 = new ArrayList<String>();
list1.add("A");
list1.add("B");
list1.add("C");
List < String > list2 = new ArrayList<String>();
list2.add("A");
list2.add("D");
list2.add("E");
String str = null;
String Strcom1;
String Strcom2;
int maxLength = list1.size();
for (int i = 0; i <= list1.size(); i++) {
for (int j = 0; j < list2.size(); j++) {
Strcom1 = list1.get(i);
Strcom2 = list2.get(j);
//str=list1.get(1);
//System.out.println(str);
if (Strcom1.equals(Strcom2)) {
System.out.println("Matching found");
}
else {
System.out.println("No Matching found");
}
}
}
}
You have to say '<' not '<=' in the first for-loop.
The list 1 should be iterated from 0 to size-1, hence use this
for(int i=0;i<list1.size();i++)
instead of
for(int i=0;i<=list1.size();i++)
replace this:
for(int i=0;i<=list1.size();i++)
with:
for(int i=0;i<list1.size();i++)
reason: last position = list1.size()-1
You should be looping from 0 to list1.size()-1 since Lists are 0-indexed; your looping condition is therefore incorrect.
Change
for(int i=0;i<=list1.size();i++)
To
for(int i=0;i<list1.size();i++)
You can also use a for each loop, as you only require the elements themselves, not the indexes.
for(String Strcom1 : list1){
for(String Strcom2 : list2){
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(input.readLine());
for (int i = 0; i < t; i++) {
String[] arrayData = input.readLine().split(" ");
int[] cardsi = new int[arrayData.length];
int e = 0;
for(int a = 0; a < arrayData.length; a++){
cardsi[e] = Integer.parseInt(arrayData[a]);
e++;
}
int X = cardsi[0];
int N = cardsi[1];
long count = 0;
for (int j = 2; j < cardsi.length; j++) {
for (int l = 3; l <= (cardsi.length - 1); l++) {
if ((cardsi[j] + cardsi[l]) == X &&(j != l)) {
count++;
}
}
}
System.out.println((i + 1) + ". " + count);
}
}
}
Time limit exceeded error is appearing upon submitting this LCPC12F problem on spoj.. what might be a solution? Is scanner a major trouble for such error to appear?
Have you ever run those codes on IDE?
When I give the number to t element then arrayData (in this case, we should enter int type not String, because of the java.lang.NumberFormatException), it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 and int N = cardsi[1]; is the main problem on your code I think. This is because String[] arrayData = input.readLine().split(" "); size is 1 so you do not have cardsi[1] element on your int array
import java.io.*;
import java.util.*;
public class chopMiddle {
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
}
}
I try to break the string into tokens and uses Integer.parseInt method to convert the tokens into int value.
I want to return an array of size 3 which contains the int values of the 2nd to the 4th integers from the string to the caller. Am i doing something wrong, because it shows below message when i compiled
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at chopMiddle.main(chopMiddle.java:18)
The problem will be when it gets to the 5th token, it will read it, then create a new array and try to read 3 more.
After you have read the 2nd, 3rd and 4th, you should break both loops.
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) //check hasMoreTokens
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
you need to check every time when you call: tokenizer.nextToken()
If you check if tokenizer has more elements in the for loop itself then you won't require while loop at all.
try below example :
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
int[] array = new int[3];
for (int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
This question already has answers here:
ArrayList initial capacity and IndexOutOfBoundsException [duplicate]
(3 answers)
Closed 7 years ago.
I'm attempting to create a program that will take a given word and find the list of words that could be made out of the letters inside the given word. Here's my code:
package wordfinder;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class WordFinder {
public static void main(String[] args) throws IOException {
List<String> wordList1 = Files.readAllLines(Paths.get("res", "WordList1.txt"));
List<String> wordList2 = Files.readAllLines(Paths.get("res", "WordList2.txt"));
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string you would like this program to find words in.");
String wordToFind = scan.nextLine();
ArrayList<String> words = new ArrayList<>();
ArrayList<Character> charArray = new ArrayList<>();
char[] charList = wordToFind.trim().toCharArray();
for (int i = 0; i < charList.length; i++) {
charArray.add(charList[i]);
}
for (int i = 0; i < wordList1.size(); i++) {
char[] charsInWordToCheckAgainst = wordList1.get(i).toCharArray();
ArrayList<Boolean> containsLetter = new ArrayList<>(charsInWordToCheckAgainst.length);
for (int j = 0; j < charsInWordToCheckAgainst.length; j++) {
if (charArray.contains(charsInWordToCheckAgainst[j])) {
containsLetter.set(j, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList1.get(i));
}
}
for (int i = 0; i < wordList2.size(); i++) {
for (int j = 0; j < wordList2.get(i).length(); j++) {
char[] charsInWordToCheckAgainst = wordList2.get(i).toCharArray();
ArrayList<Boolean> containsLetter = new ArrayList(charsInWordToCheckAgainst.length);
for (int k = 0; k < charsInWordToCheckAgainst.length; k++) {
if (charArray.contains(charsInWordToCheckAgainst[k])) {
containsLetter.set(k, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList2.get(i));
}
}
}
System.out.println("Words found: " + words.size());
for(int i = 0; i < words.size(); i++) {
System.out.println("Word " + i + ": " + words.get(i));
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
public static boolean areAllTrue(ArrayList<Boolean> bools) {
for (int i = 0; i < bools.size(); i++) {
if (!bools.get(i)) {
return false;
}
}
return true;
}
}
And here's the error I'm getting:
Please enter the string you would like this program to find words in.
abcdefghijklmnopqrstuvwxyz
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.set(ArrayList.java:444)
at wordfinder.WordFinder.main(WordFinder.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
For clarification, WordFinder.java:36 is containsLetter.set(j, true); in the wordList1 for loop. So I really just don't understand why the size of the array is 0. containLetter should not be 0.
UPDATE 1
Updated wordList1 for loop to this:
for (int i = 0; i < wordList2.size(); i++) {
for (int j = 0; j < wordList2.get(i).length(); j++) {
char[] charsInWordToCheckAgainst = wordList2.get(i).toCharArray()
ArrayList<Boolean> containsLetter = new ArrayList<>();
Collections.fill((List) containsLetter, charsInWordToCheckAgainst.length);
for (int k = 0; k < charsInWordToCheckAgainst.length; k++) {
if (charArray.contains(charsInWordToCheckAgainst[k])) {
containsLetter.set(k, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList2.get(i));
}
}
}
But that still gives me the same error.
According to javadoc for ArrayList constructor new ArrayList<>(charsInWordToCheckAgainst.length) accept single parameter - which is initial capacity of list. Capacity - not size.
The difference is as follow.
Size - is number of elements stored in the list.
Capacity - is initial array size created for this structure.
E.g. whenever you adding element to list it will check - do I have capacity for it and if not - re-allocate new array. Purpose of providing this parameter into constructor is to reduce amount of re-allocations. In order to pre-fill list - you need to put elements inside manually or use utility functions provided by 3-rd party libraries.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am attempting to sort a list of names in alphabetical order and I keep getting the error Exception in thread "main" java.lang.NullPointerException and I don't know why.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class alphabeticalOrder {
static String names[];
static int count = 0;
static String sorting;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String[] names = new String[500];
File namesFile = new File("names.txt");
Scanner inputFile = new Scanner(namesFile);
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
String[] namesDetails = line.split(" ");
names[count] = namesDetails[0];
count++;
}
sort();
System.out.println(Arrays.toString(names));
}
public static void sort() {
int namesLength = names.length;
for (int i = 0; i < namesLength - 1; i++) {
for (int j = 0; j < namesLength - 1; j++) {
if (names[j].compareTo(names[j - 1]) > 0) {
sorting = names[j - 1];
names[j - 1] = names[j];
names[j] = sorting;
}
}
}
}
}
Customers txt has these names
Smith, Alexandra
Downes, Trish
Akbal, Maria
and the array must equal 500
Change
if (names[j].compareTo(names[j - 1]) > 0) {
to
if (names[j] != null && names[j].compareTo(names[j - 1]) > 0) {
And the annoying null pointer exception will go away.
If you ever get over your 500 String array obsession I suggest you try TreeSet since it will do all the sorting work for you.
public static void main(String[] args)
{
Set<String> alphabetical = new TreeSet<String>();
alphabetical.add("A");
alphabetical.add("Z");
alphabetical.add("M");
System.out.println(alphabetical);
}
outputs: [A, M, Z]
Your names array has 500 elements, most of which are null. That's why you are getting NullPointerException, when you call names[j].compareTo() for a null reference.
You should only attempt to sort as many names as you get as input.
Instead of
int namesLength = names.length;
Try
int namesLength = count;
Since count holds the number of inputs you actually have.
BTW, your sort() method has other problems :
The loops should go from 0 to namesLength - 1, so the condition should be j < namesLength
names [j-1] would give you ArrayIndexOutOfBoundsException when j==0
You have the array in size 500 and number your names are 6.
when you assign six names to first six indexes of the array, the rest indexes are still having null value. Therefor, comparing with the null value will throw NullPointerException.
why?
Because Objects in Java initialized by null value when they are defined for the first time.
Suggestion :
Try to use ArrayList which shrinks and expands by itself