Can someone tell me why am I getting java.lang.ArrayIndexOutOfBoundsException error in my code? [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 2 years ago.
Improve this question
I am working on a Java program to iterate through two arrays and compare the first one to the second for any matches. It should return all the numbers/strings that DON'T MATCH as an array list. I am done, but I am not sure why I am getting an ArrayIndexOutOfBoundsException error. This is my code:
package test;
import java.awt.List;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayComparer {
public static ArrayList<String> ArrayComparer(String[] arrayOne, String[] arrayTwo){
// if one is bigger than start by comparing the smaller one to the bigger one
// as if it were the other way the bigger one would run out over numbers to compare
// declaring the array for holding all the non-matching telephone numbers to be returned
ArrayList<String> nonMatchingTelephoneNumbers = new ArrayList<String>();
for(int i = 0; i<arrayOne.length; i++){
int strikes = 0;
// for each value of the first one it should go through all the values of the second and compare each
for(int i2 = 0; i<arrayTwo.length; i2++){
if(arrayOne[i] != arrayTwo[i2]){
strikes++;
if(strikes == arrayTwo.length){
// meaning it has gone through ALL of arrayTwo and couldn't find a match
nonMatchingTelephoneNumbers.add(arrayOne[i]);
}
}
}
}
return nonMatchingTelephoneNumbers;
}
public static void main(String[] args) throws IOException {
// declaring the first list of telephone number
String[] ArrayListOne;
// declaring the second list of telephone numbers
String[] ArrayListTwo;
// splitting up the user input of telephone numbers by commas
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your first array of telephone numbers, split by commas");
ArrayListOne = myObj.nextLine().split(","); // Read user input
// once it has iterated through all of the telephone numbers in the first list, ask for the second list
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your second array of telephone numbers, split by commas");
ArrayListTwo = myObj2.nextLine().split(","); // Read the second user input
// once it has collected and sorted all the user input, the ArrayCOmparer method should be called
// to compare them and return the telephone numbers that DON'T MATCH
ArrayComparer(ArrayListOne, ArrayListTwo);
}
}
The error is on line 22, where it says if(arrayOne[i] != arrayTwo[i2]){.It also doesn't say there is an error on line 22 until I run it. Can someone please tell me why I am getting this:console error?

Hi i think this is causing the error
for(int i2 = 0; i<arrayTwo.length; i2++){
You should replace it with:
for(int i2 = 0; i2<arrayTwo.length; i2++){

Related

Do while loop condition not matching with variables inputted through scanners [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 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}

Java issues with Scanner and hasNextLine() while reading a file

I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
public class LabProgram {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int NUM_CHARACTERS = 26; // Maximum number of letters
int MAX_WORDS = 10; // Maximum number of synonyms per starting letter
String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
char userChar = scnr.next().charAt(0); //Get char user wants to search
String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS]; // Declare 2D array for all synonyms
String[] words = new String[MAX_WORDS]; // The words of each input line
File aFile = new File(userWord);
Scanner inFile = new Scanner(aFile);
while(inFile.hasNextLine()) {
for(int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
for(int wordCount = 0; wordCount < words.length; wordCount++) {
synonyms[i][wordCount] = words[wordCount];
}
}
}
}
}
The issue is with this for loop:
for (int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
....
}
You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.
I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.
Hope that answers your query.
Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.
I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.

String array out of bounds [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to make an array of type string of which the size and strings are inputted by the user and i keep getting error ArrayIndexOutOfBoundsException There is similar threads i found pertaining to this but none of which have solved this error. in my for statement if i take out the equal to and just do less than i receive no errors but i can only input one name less than the number i input. If i leave the code as is everything appears to work as it should minus the error. I understand i am getting this fault because my array is going out of bounds but i cant figure out why. please help! thank you!
package sales;
import compare.*;
import java.util.*;
public class Sales {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter number of employees to compare:");
int numEmp = scan.nextInt();
while(numEmp < 2){
System.out.println("Has to be at least 2 employees:");
numEmp = scan.nextInt();
}
String[] names = new String[numEmp];
System.out.println("Enter employees name:");
for(int i=0;i<=names.length;i++){
names[i]=scan.nextLine();
}
}
}
Change the condition of the for to i<names.length instead of i<=names.length.
scan.nextLine(); //add this
for(int i=0;i<names.length;i++){
names[i]=scan.nextLine();
}

Read first 100 string array, java i/o [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I was directed from to this website from a friend. The goal is to read the first 100 strings in the txt file and count how many times those words appear and print them off.
Thank you so much in advance. I've done very well with code but this has stumped me for some reason.
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) throws FileNotFoundException {
WordAnalysis a = new WordAnalysis();
a.ReadFile();
}}
class WordAnalysis{
String[] coun = new String[1000];
int[] ana = new int[100];
void ReadFile() throws FileNotFoundException {
Scanner read = new Scanner(new File("myths.txt"));
int[] ana = new int[100];
String coun = new String();
String word=null;
while(read.hasNext()) {
word = read.next();
String[] arrWord = word.split(" ");
}
}
}
Procedure:
1: Read lines [0,99] via nextLine() from Scanner
2: Split up line with another Scanner and use next() to get each word. Alternatively, you can use split.
3: Put each word in a HashMap(String, Integer) where String is the word, and Integer is the number of times it has appeared
4: Iterate through HashMap and prints out key, value pairs
Check this, here I've used a map to keep word count.
int count = 0;
HashMap<String, Integer> wordCntMap = new HashMap();
while (read.hasNext()) {
count++;
word = read.next();
String[] arrWord = word.split(" ");
if (count == 100) {
break;
}
for (String str : arrWord) {
Integer num = wordCntMap.get(str);
if (num == null) {
wordCntMap.put(str, new Integer(1));
} else {
wordCntMap.put(str, num + 1);
}
}
}
System.out.println("Word Count " + wordCntMap);
Welcome to Stack Overflow, where no answer is too stupid and no comment too thoughtless.
It seems fairly clear however that you haven't finished writing this code. :-)
Now that you have your words in arrWord, you need to start using some sort of structure that will allow you to keep track of each word and how many times its been seen.
There are plenty of containers that let you use a string as a key and an integer as a value. For your purposes it doesn't matter which one you use.
For each word in arrWord, see if you can find it in your structure (Dictionary, Hashmap, whatever). If you can't find 'word', insert a new entry of [word, 1]. If you can find 'word' then increment the counter that you find.
When you are done, all you need to do is print out the key-value pair for each entry in your structure.
HTH!

Read multiple lines from console and store it in array list in Java?

Can anyone please help me with the code as how to read multiple lines from console and store it in array list?
Example, my input from the console is:
12 abc place1
13 xyz place2
and I need this data in ArrayList.
So far I tried this code:
Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
scanner.useDelimiter("\t");
information = scanner.nextLine();
informationList.add(information);
count++;
}
Any help is greatly appreciated.
Input line from console is mix of string and integer
You've got a few problems.
First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Object inside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.
Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.
Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.
Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.
Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.
To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:
import java.util.ArrayList;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<>();
System.out.println("Enter block size");
int blockSize = scanner.nextInt();
System.out.println("Enter data rows:");
int count = 0;
while (count < blockSize) {
list.add(scanner.nextInt());
list.add(scanner.next());
list.add(scanner.next());
count++;
}
System.out.println("\nThe data you entered is:");
System.out.println(list);
}
}

Categories

Resources