I cannot figure this out. This is for homework. I need to create a method that reverses an integer that is passed to it. I've now been able to fix the outofBounds error in the for loop thanks to everyone's input. The integer that is passed into the method can be of any length. And I have to return an integer instead of an array or string. But now I get an 'Unresolved compilation problem: Syntax error on token "[", Expression expected after this token' on the int u = backInt[]; line. But I have no idea what to put in the []'s. I haven't been able to find a way to convert an Integer array to an integer so I can pass the integer back, so I'm lost. Here is the code that I have so far:
public static int reverseIt(int x){
int y = String.valueOf(x).length();
int[] backInt = new int [y];
for(int z = 0; z < y; z++){
x %=10;
backInt[z] = x;
x /= 10;
}
int u = backInt[];
return u;
return -1;
}
You start with z=0 and end with z=y. That's y+1 times through the loop, but your array is correctly only y elements long, so the exception occurs on the last iteration of the loop when you try to write to the nonexistent element. By that time, though, x should already be zero because you've processed all y digits, so your stopping condition should be z<y instead of z<=y.
You're going too far in your loop. It should be:
for(int z = 0; z < y; z++) {
...instead.
Take the input 12 as an example. It's two characters long, so backInt has a length of 2. When you go through the loop, you're iterating through values of z of 0, 1, and 2. What's the value of backInt[2] when backInt only has two elements in it?
Edit: Your code will also break for, say, 2147483646, because your resulting integer will be too large for the Integer type. But that's beside the point here.
Java arrays are 0-indexed. What that means is that if you do int[] arr = new int[10], you create an integer array that can hold ten ints, and the first int is stored in arr[0], the second in arr[1], and the last in arr[10-1], which is arr[9].
To fix your code, change z <= y to z < y. In the future, just remember that if you create an array for n objects, then you can access them by arr[0], arr[1]... arr[n-1], but accessing arr[n] will throw an OutOfBounds exception.
Related
I'm trying to get a program to work where I generate 1,000,000 random numbers between 0 and 1 and then find and print the largest number.
I've got the generator to work and managed to insert each double generated into an ArrayList but I cannot seem to figure out how to find the largest number in the list. At the moment the current code throws the error "java.lang.IndexOutOfBoundsException".
This is all probably due to me being new to the ArrayList and not being fluent with its commands and how it works but I would really appreciate some help on what I'm doing wrong here as I've been stuck for a while.
import java.util.ArrayList;
import java.util.Random;
public class milran {
public static void main(String[] args) {
Random r = new Random();
ArrayList<Double> myList = new ArrayList<Double>();
for (int i = 1; i<=1000000; i++){
double randomValue = 0.0+(1.0-0.0)*r.nextDouble();
myList.add(randomValue);
}
double max = myList.get(1);
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
if (test>max){
max = test;
}
}
System.out.println(max);
}
}
First of all take a look at the docs for java.util.Collections and java.util.ArrayList.
Secondly, the ArrayIndexOutOfBoundsException is being triggered by this...
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
...
}
This is because array indexing starts at 0, therefore the last element is myList.size() - 1. In other words, when z = myList.size(), it is out of bounds.
Also, in your first for loop, you are using i = 1; 1 <= 1000000. It makes much more sense to use i = 0; i < 1000000 as you can use i to touch each element in an array (or list).
for( i = 0; i < 1000000; i++ )
{
// do something with myArray[i]
}
Here's what I would do after the values have been inserted...
Sort the array: Collections.sort(myList);
Retrieve the last element: System.out.println( myList.get( myList.size() - 1 ) );
...and that's it.
If you need to implement the actual sort yourself then i'd consider using a primitive double array (double[]) rather than a Collection.
Otherwise, if you are using a collection, you can use a foreach loop.
for( Double d : myList ) // for each Double 'd' in myList
{
// do something with d
}
N.B. Another potential issue with this line in the second loop
double test = myList.get(z);
This automatic conversion from Double (object) to double (primitive) is called unboxing. There will be a performance cost, especially when repeated a million times. In the first loop you are converting the other way (autoboxing) – also a million times.
ArrayList start count its elements from 0. You need to replace myList.get(1) to myList.get(0), int z=2 to int z=1 and z<=myList.size() to z<myList.size().
This line: for (int z=2; z<=myList.size(); z++) { is wrong. It should be for (int z=1; z<myList.size(); z++) {.
This is because arrays and lists are 0 based, so a list of size 2 has 2 elements - index 0 and index 1. Currently you try to index into the element number equal to the size, which does not exist.
Along the same line, myList.get(1); should be myList.get(0);.
This is unrelated to your problem, but this line 0.0+(1.0-0.0)*r.nextDouble(); can be much more easily written as r.nextDouble();. I'm not sure what you were trying to do by doing 0 + 1 - 0.
As others have already pointed out, you have an error in your for-loop condition that causes the index to go out-of-bounds.
One way that you can avoid this in the future is by using Java's for-each loop syntax instead of trying to manage the index yourself.
for (Double test : myList) {
if (test>max){
max = test;
}
}
This syntax makes your intent much clearer than the traditional indexed for syntax and removes a point of potential error (managing the index and the bounds of the list) from your hands.
I'm trying to teach myself coding, and I stumbled on an example I don't understand. Could someone give me an overview of what this code is supposed to do? I'm a bit confused about int a[] and what is later int a[i]. I know what an array is, but could someone please explain how this is being used in this context? Thank you in advance.
public class all {
public int select(int a[],int n,int x)
{
int i=0;
while(i<n && a[i]<x)
{
if(a[i]<0)
a[i]=-a[i];
i++;
}
return(a[i-1]);
}
}
This
if(a[i]<0)
a[i]=-a[i];
i++;
is he same like this
if(a[i]<0) {
a[i]=-a[i];
}
i++;
a[i] -> value at the position i, into the Array
if(a[i]<0) { -> if the value at position i is smaller than 0, also negative number
a[i]=-a[i]; -> replace the value with a reverse sign.
i++ -> increment loop Counter
Also what is done here: negative numbers convert to positive numbers.
while(i<n && a[i]<x) -> i = loop counter; if i smaller n and the value at position i in the array is smaller than x, then go into the loop.
return(a[i-1]); -> return the last value, that has been checked into the while loop
the method gets an array and two int args n and x (as a side note, I must say the names leave a lot to be desired...)
anyway, lets see what are the args for. they both are used in the while loop. the condition i<n tells us that n serves as upper limit to the iteration, while the condition a[i]<x tells us that x is used as upper limit to the values in the array.
so far, we can say:
select method receives an array, int arg specifying iteration-upper-limit and int arg specifying cell-value-upper-limit.
iterate over the array until you reach position specified by iteration-upper-limit or you reach a cell value that exceeds cell-value-upper-limit (which ever comes first)
can you continue to say what's being done inside the loop? it's fairly straightforward.
1.) a[] is the declaration of array.size is not defined.
2.)In a[i], i is the index number of the array...that means indicating the position of the element in array.
a[] is an array and we do not know its length. n must be lower than the length of a[] or it will throw an exception. It it traverses from the first element toward the last untill it one element is larger than x. it returns these element's absolute value which were traversed
Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {
So I got this assignment while my teacher is away, and basically I have to make a student project. The student has a name, marks, and average. To calculate the average I decided to store the marks inside a int[] array.
public void addQuiz(int m)
{
int l = (marks.length);
marks[l] = m;
}
int[] marks = new int[8];
But when I run the function:
student.addQuiz(90);
I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Any help?
I'm not sure what the int[8] part does but it was in the tutorial I followed and it would give me a null pointer without it. There are eight marks in total so I just made it 8.
You can't dynamically add things to an array. You should use an array list instead.
Arraylist<Integer> marks = new ArrayList<Integer>();
then in your addQuiz method:
public void addQuiz(int m) {
marks.add(m)
}
You'll probably also need to change your method for calculating the average a bit, but that should be trivial and I'll leave it to you.
The error says: ArrayIndexOutOfBoundsException: 8
You have an array with 8 elements, indexed from 0 to 7 (inclusive). This array has a length of 8, and you are actually trying to access marks[8], when you only can go up to 7.
In Java, Array index starts from '0'. so, you cannot access the index of the array equal to the length of the array.if your arrays length is '8', then the last index of the array is '7' not '8'. if you are trying to access the illegal index of the array, then ArrayIndexOutOfBoundException is thrown. the code should be changed to
public void addQuiz(int m)
{
int l = (marks.length); //assuming marks is an array of length '8'
marks[l-1] = m; //index is 7 now
}
To calculate the average, you need to sum up the contents of the array (provided all the values are of int values) and then divided by the lenght of the array
int sum = 0;
int avg = 0;
for(int i=0; i<array.length;i++){
sum =sum+array[i];
}
avg = sum/array.length;
Hope this gives an idea
Use Arraylist<Integer> and then you can add to the list dynamically
There is not index in this array for this marks[l] = m;. use marks[l-1] = m;
You can call this for loop in main for getting marks 8 times.
for(int i=0;i<8;i++)
student.addQuiz(<marks you want to enter>, i);
You can define addQuiz function like below
public void addQuiz(int m, int arrayIndex)
{
marks[arrayIndex] = m;
}
int[] marks = new int[8]; //this will be as it is
These are minimal changes. You can make your code better by passing array marks to addQuiz as a parameter. But this will also work, its just that this is not the best way to write code.
I know that this is quite a long and probably confusing post... but I really have no idea what could be causing this... so i did the best I could at explaining. I am not sure how to describe the problem succinctly, which has made it rather difficult for me to look for other solutions.
Anyway, First a slight bit of background. This program is reading through a 2D array in all of a possible 8 directions looking for a word (The program is basically an automated word find).
I have the 2D array and I am searching through it, looking for a given string. To do this, I have 3 loops:
The first loop (looping x) chooses the starting x-coordinate
The second loop (looping y) chooses the starting y-coordinate
The last loop (looping L) checks for a word of length L starting at the positions given by (x,y) coordinates from the outer loops.
However, It seems the program does not enter the loop for L until the outer loops have increased to 1. Because of this, I cannot start a search for a word in column 1 (x=0), the first one that gets accessed is column 2 (x=1). It is almost as if there is an if statement preventing the for loop from running when the values from either of the other two loops are below 1. What is more, this ONLY HAPPENS When I am subtracting index locations of the array, not when I am adding them.
To clarify on that last point, I am searching for words by adding chars to a string one at a time. So when reading forward, a three letter word 'cat' would consist of a string 'c' at location x, then we add to the string the char 'a' at location x+1, then we add to that string the char 't' from location x+2. This basically gets writted as arr[x+L][y], to search forward for a word. HOWEVER, I also want to find words written backwards. so for that I have a loop the adds arr[x-L][y]. It seems that this error ONLY happens when I am subtracting L from the indicies in my array, and only happens to the value that it is subtracted from (so for [x-1][y], x=0 does not go into the for loop, but y=0 DOES.
Here is the (shortened) code:
public void searchPuzzle(String[][] Puzzle){
//For Each Coordinate X,Y
for(int x=0; x<Puzzle.length; x++){//For each x position
for(int y=0; y<Puzzle[x].length; y++){//For each y position
//RESET or INITAITE strings for searching in all 8 directions
String F="", B="", U="", D="", DiFU="", DiFD="", DiBU="", DiBD="";
//SEARCH FORWARD
for(int L = 0; L < Puzzle.length-x; L++){ //search for word of length L
F = F+Puzzle[x+L][y];
//System.out.println(F);
if(isWord(F)){
//System.out.println(F);
}
}
//SEARCH BACK
System.out.println("X:" + x + " Y: "+y);
for(int L = 0; L < x; L++){ //search for word of
System.out.println("X:" + x + " Y: "+y);
B = B+Puzzle[x-L][y];
System.out.println(B);
if(isWord(B)){
//System.out.println(B);
}
}
System.out.println("--");
//SEARCH DIAGONALLY - BACK & UP
for(int L = 0; L < smaller(x,y); L++){
DiBU = DiBU+Puzzle[x-L][y-L];
if(isWord(DiBU)){
//System.out.println(DiBU);
}
}
SEARCH FORWARD
works perfectly (Because F+Puzzle[x+L][y] involves only addition).
So for this one the program to start reading at arr[0][0], as it should.
SEARCH BACK
has the error I mentioned, but only the x value is wrong. This means that x=0 never gets passed into the loop SEARCH BACK, ans as a result the loop starts with x=1. Note that the code has B+Puzzle[x-L][y]
So for this one the program to start reading at arr[1][0].
SEARCH DIAGONALLY - BACK & UP
has this error for both x AND Y. Because of "DiBU+Puzzle[x-L][y-L]", BOTH x=0 and y=0 do not go into the loop. And so
So for this one the program to start reading at arr[1][1].
EDIT: I have tried simply subtracting 1 (as in B+Puzzle[x-L-1][y]), however this just causes it to start in the right place but end one column to short.
TL;DR
Innermost of three for loops cannot be read unless the value of the outer two loops is above 0. But this problem only occurs if I am subtracting values from the indices of an array inside the said innermost For Loop.
I think it is simpler to separate the forwards and backwards searches, at least until you get it all working. Do one thing at a time, and do it carefully.
The reason for not doing any iterations of the second loop if x is zero lies in the loop condition:
for(int L = 0; L < x; L++)
L is never less than 0, and so if x is 0 the condition L < x is never met, and the loop does zero iterations.
Suppose y is 0 and x is 2. The elements [2][0], [1][0], and [0][0] could be a three letter word. You will only do two iterations, for L=0 and L=1.
Both problems would be fixed by doing one more iteration by changing the condition to L <= x.
It is very, very important to think about your loop conditions. In many simple cases a "<" test is appropriate, but not always. In this case, L==x results in looking at element 0 of the array, which you want.
I think there is an logical issue with :
//SEARCH BACK
for(int L = 0; L < x; L++){ //search for word of
B = B+Puzzle[x-L][y];
//System.out.println(B);
if(isWord(B)){
//System.out.println(B);
}
}
If the word CAT is written TAC at the beginning of your matrix, you will not find it.
Maybe you want to do :
//SEARCH BACK
for(int L = Puzzle.length-x - 1; L >=0 ; L--){
B = B+Puzzle[L-x][y];
//System.out.println(B);
if(isWord(B)){
//System.out.println(B);
}
}
So, why do you you search backwards??? You can rather concatenates a word on the other side each time you search forward. Which means :
String forwardword;
String backwardword;
for(int L = 0; L < Puzzle.length-x; L++){ //search for word of length L
forwardword = forwardword +Puzzle[x+L][y];
backwardword = Puzzle[x+L][y] + backwardword; // <<HERE
if(isWord(forwardword)){
//System.out.println(forwardword);
}
if(isWord(backwardword)){
//System.out.println(backwardword);
}
}