I have created an array of arraylists which has a size of 45. I am getting an ArrayOutOfBoundException for some reason.
Here's where I'm getting the error:
String temp;
Scanner sc = new Scanner(str1);
while(sc.hasNext())
{
temp = sc.next();
int len = temp.length();
if(len > 0)
wordsByLen[len - 1].add(temp); //throwing the error here with exception of 59
}
Thank you in advance for your help!
Have you initialised the array wordsByLen correctly ? I suspect not.
I think what you need to do is initialise the array with the correct length, and then with a collection for every possible word length. e.g. (in pseudocode)
for (int i = 0; i < MAXWORDLENGTH; i++) {
wordsByLen[i] = new ArrayList<String>();
}
I would perhaps use a Map<Integer,List<String>> instead. You'll have to initialise it in a similar way, but it would be a more reliable mechanism. You wouldn't have an arbitrary limit on the maximum number of characters you can record words for.
Related
Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.
int[] a = new int[101];
int n = in.nextInt();
for(int i = 0; i < n; i++){
a[in.nextInt()]++;
}
a is an array that is initialized; the next line get's you the amount of numbers that will follow after that.
Assuming that in is an initialized Scanner, nextInt() will read the next int from the console. Usually on websites like codingames.com or apparently hackerrank use this construct to put in data for your code to test it.
In the loop the code will read an index to be used in the pre-initialized array to increase the value by one at that given index.
That is basically it. To make it clearer, you could write:
int[] a = new int[101];
int numberOfIntsToFollow = in.nextInt();
for(int i = 0; i < numberOfIntsToFollow; i++){
int x = in.nextInt();
a[x]++;
}
I am creating a program that imports a large list of words. This list has been separated by word but I now need to determine the ASCII value of each word in this list, and eventually which one has the highest total ASCII value. I am receiving a few errors and need to know how to get this corrected so that I can get each value.
public static void main(String[] args) throws IOException {
//import list of words
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> words = new ArrayList<String>();
//Find number of lines in txt file
String line;
String delimiter = "\t";
while ((line = File.readLine()) != null)
//read the file
{
String[] wordsInLine = line.split(delimiter);
//separate the words
for(int i=0, isize = wordsInLine.length; i < isize; i++){
words.add(wordsInLine[i]);//put them in a list
//assess each character in the word to determine the ascii value
int total = 0;
for (int i=0; i < wordsInLine.length(); i++)
Receiving an error on the above line that states - Cannot invoke length() on the array type
String[]
- Duplicate local variable i
{
char c = word.charAt(i);
Receiving an error on the above line that states word cannot be resolved
int j = (int) c;
total += c;
}
I have done some research trying to determine the best way to calculate the ASCII value of each word and I haven't been able to find much information on how to do this. If someone could please take a look at my code I would appreciate it!! Also, before anyone says it let me just say this is NOT a school project. I am on summer break and beginning programming II in the fall and just trying to keep up on coding so that I am not rusty in the fall. THANK YOU!!! :))
Receiving an error on the above line that states - Cannot invoke length() on the array type String[] - Duplicate local variable i
wordsInLine is an array, and length is property of array. So, you have to use:
wordsInLine.length
If wordsInLine was a String, then wordsInLine.length() would have made sense.
Receiving an error on the above line that states word cannot be resolved
Before the line char c = word.charAt(i);, add below:
String word = wordsInLine[i];
For the wordsInLine.length() issue, length() is not a valid method for arrays. You actually have to access the length field thusly: wordsInLine.length without ().
As for word.charAt(i), you haven't declared a variable called word anywhere which is what's causing the problem. What you really want to do is sum up the values for every word in the array, and for that you need a nested loop.
You also said that you wanted to figure out which one had the highest value. To do that, just keep track of the largest one and update it after each iteration like this:
int indexOfMax = 0;
int[] sums = new int[wordsInLine.length];
//Iterate over every word
for(int i = 0; i < wordsInLine.length; i++)
{
//Reset the total for each word
total = 0;
//Iterate over every character in the word
for(int j = 0; j < wordsInLine[i].length(); j++)
{
char c = wordsInLine[i].charAt(j);
total += c;
}
//Remember the sum for this word
sums[i] = total;
//If the word's sum is greater than our previous max,
//make it the new max
if(sums[i] > sums[indexOfMax])
{
indexOfMax = i;
}
}
And now you can get the word with the greatest ASCII value by calling wordsInLine[indexOfMax]. It will have an ASCII sum of sums[indexOfMax].
wordsInLine is an array and therefore it does not have a method to get its length. Instead, to get an array's length, use array.length as opposed to what you were doing: array.length() (which causes an error).
word is not a defined variable, this is why java is saying that it cannot be resolved (it can't find any declaration). Instead you want to use 2 for loops in order to loop over every character in the word in the array wordsInLine. You also have two instances of the variable i, this is not allowed. To fix these errors write the following code after `int total = 0;':
int total = 0; // Don't rewrite this line
int[] totals = new int[wordsInLine.length]; // If you want to add all your totals to an array
for (int j=0; j < wordsInLine.length; j++) {
total = 0;
for (int k=0; k < wordsInLine[j].length(); k++) { // Here wordsInLine[j] is a string so you use .length() instead of .length
char c = wordsInLine[j].charAt(k);
int w = (int) c; // Get ascii of c
total += w; // Add it to total
}
// Do something with the total of this word before it gets reset to 0
// Maybe add it to an array of totals:
totals[j] = total;
}
I hope this helps!
Well your organization of your code needs a little bit of work.
First I would take this whole block of code outside file read in while loop.
for (int i=0; i < wordsInLine.length(); i++)
{
char c = word.charAt(i);
int j = (int) c;
total += c;
}
Why? Lets split what you are doing into two steps. Read in all the words into the word list. After doing this you will find where your core root of the problem is. You aren't reading the words from your word list at all.
Further code cleanup
for(int i=0, isize = wordsInLine.length; i < isize; i++){
This line is a little bit bloated. You don't need isize at all you are essentially doing denoting it for no reason. (Well actually caching the length does improve efficiency, another talk for another day). Cleaning up.
for(int i=0, ; i < wordsInLine.length; i++){
Then fixing the entire project
//import list of words
BufferedReader File = new BufferedReader(new FileReader(LOC));
//Create a temporary ArrayList to store data
ArrayList<String> words = new ArrayList<String>();
//Find number of lines in txt file
String line;
String delimiter = "\t";
// adds all the words into the list.
while ((line = File.readLine()) != null)
{
String[] wordsInLine = line.split(delimiter);
for(int i=0, ; i < wordsInLine.length; i++){
// compute alg and store the value some how to the word.
words.add(wordsInLine[i])
}
}
// notice outside the while loop.
// .size() is used for lists and .length is used for arrays.
for(int i = 0; i < words.size(); i++){
// compare
}
I'm having trouble setting up and placing values into an array using a text file containing the floating point numbers 2.1 and 4.3 each number is separated by a space - below is the error I'm getting:
Exception in thread "main" java.util.NoSuchElementException
import java.util.*;
import java.io.*;
public class DoubleArray {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new FileReader("mytestnumbers.txt"));
double [] nums = new double[2];
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++;
nums[index] = in.nextDouble();
}
}
}
Thanks, I'm sure this isn't a hard question to answer... I appreciate your time.
You should always use hasNext*() method before calling next*() method
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[1] = in.nextDouble();
}
}
but I think you are not doing the right, I'd rather
for (int counter=0; counter < 2; counter++) {
if(in.hasNextDouble(){
nums[counter] = in.nextDouble();
}
}
NoSuchElementException is thrown by nextDouble method #see javadoc
I would suggest printing the value of index out immediately before you use it; you should spot the problem pretty quickly.
It would appear you're not getting good values from your file.
Oli is also correct that you have a problem with your index, but I would try this to verify you're getting doubles from your file:
String s = in.next();
System.out.println("Got token '" + s + "'"); // is this a double??
double d = Double.parseDouble(s);
EDIT: I take this partly back...
You simply don't have tokens to get. Here's what next double would have given you for exceptions:
InputMismatchException - if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
I did not understand what you are trying to do in your loop ?
for (int counter=0; counter < 2; counter++) {
int index = 0;
index++; <--------
nums[index] = in.nextDouble();
}
You are declaring index = 0 then incrementing it to 1 and then using it.
Why are you not writing int index = 1; directly ?
Because it is getting declared to be zero each time loop is run and then changes value to 1.
Either you should declare it out side the loop.
You should initialize index outside of your for loop.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
index++;
nums[index] = in.nextDouble();
}
Your index was getting set to zero at the beginning of each iteration of your for loop.
EDIT:
You also need to check to make sure you still have input.
int index = 0;
for (int counter=0; counter < 2; counter++)
{
if(!in.hasNextDouble())
break;
index++;
nums[index] = in.nextDouble();
}
Every time the cycle does an iteration, it's declaring the variable index and then you increase index with index++. Instead of using index, use counter, like this: num [counter] = in.nextDouble().
Check your mytestnumbers.txt file and ensure that the data that you are trying to scan is in the correct format. The exception that you are getting implies it is not.
Keep in mind that in.nextDouble() will be searching for double numbers separated by white space. In other words, "4.63.7" is not equal to "4.6 3.7" — the space is required. (I do not remember off the top of my head, but I believe that nextDouble() will only search for numbers containing a decimal point, so I do not believe that "4" is equal to "4.0". If you are seeking decimal numbers with this method, then you should have decimal numbers in your file.)
How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);