Hi guys I've been learning java over the summer and this is the last assignment, and I'm stuck. The program is supposed to take 13 numbers that I enter, sort them and then find the index number of the greatest number that I input in the original array. I'm trying to see if my selection method works but every time I try to enter in the numbers I get an out of bounds error. This is kind of frustrating and I've been trying to find and answer for a couple of hours now. Any help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int indmax;
int[] fmax = new int[13];
fillmax(fmax);
//System.out.println(fmax);
indmax = maxfmax(fmax);
//indmin = minfmax();
System.out.println(indmax);
}
public static void fillmax(int[] farray)
{
Scanner sc = new Scanner(System.in);
int i = 0;
for(i = 0; i < farray.length; i++)
{
farray[i] = sc.nextInt();
}
}
public static int maxfmax(int[] farray)
{
int[] copy = farray;
int j, x=0, i;
boolean flag = true;
int temp;
while(flag)
{
flag = false;
for( j = 0; j < copy.length -1; j++)
{
if(copy[j] < copy[j+1])
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
flag = true;
}
}
for(i=0; i <= farray.length; i++)
{
if(farray[i] == copy[1])
x = i;
}
}
return x;
}
}
This line will throw the out of bounds exception.
for(i=0; i <= farray.length; i++)
Your termination condition is incorrect. Try this:
for(i=0; i < farray.length; i++)
so that you stop the loop before you go past the last index (farray.length - 1).
You defined the Lenght of the Array as 13 than you run this line:
for(i=0; i <= farray.length; i++)
This means you will go for the items fmax[13] which doesnt exist, because java starts counting at 0. So the hightest index is fmax[12]. You need to change your condition to something like that:
for(i=0; i < farray.length; i++)
or
for(i=0; i <= farray.length -1; i++)
In this case length for array is returning size of your array - but it starts with 1 not with zero.
i <= farray.length - causes out of bounds exception
u have to use - as was mentioned i < farray.length in your for loop
Array always has index beginning with zero and ending with length-1
for(i=0; i <= farray.length; i++)
Your terminating condition is wrong. It is trying to access element located at index length, which does not exist and hence you get the exception. It should be modified to something like below to make it work:
for(i=0; i < farray.length; i++)
Related
This question is from G4G array rotation. I am getting an error in the second loop telling me the array is getting out of scope. But I don't understand why.
import java.util.Scanner;
public class timba {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, d;
n = sc.nextInt();
d = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
while (d > 0) {
int t;
t = arr[0];
for(int j = 0; j < arr.length; j++) {
arr[j] = arr[j+1];
}
arr[n-1] = t;
d--;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Inside the second loop, j + 1 index will be out of bounds once j hits arr.length - 1 since indices start from 0, therefore it should be j < arr.length - 1
This should be your exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at timba.main(timba.java:30)
This is caused because your code is letting me input 7 elements when I only specified I want to input 6. Have a look at this line.
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
Say I specified that n is 5 so the length of the array is 5, but, this is letting me input 6. This can simply be fixed by adding a -1 to the code.
for(int i=0;i<arr.length - 1;i++){
arr[i]=sc.nextInt();
}
Next bit of code we have to look at is
for(int j=0;j<arr.length;j++){
arr[j]=arr[j+1];
}
This is a common mistake that beginner Java programmers make. This will always go out of bounds because when j = 4, then "arr[4] = array[5]" but your array only goes up to arr[4] because I only wanted to input 5 elements. That's why the compiler gave you that exception. You can fix this by adding a "-1" just like the previous mistake you made and this should fix this exception.
for(int j=0;j<arr.length - 1;j++){
arr[j]=arr[j+1];
}
Your new code should be
import java.util.Scanner;
public class timba {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n,d;
n=sc.nextInt();
d=sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<arr.length - 1;i++){
arr[i]=sc.nextInt();
}
while(d>0){
int t;
t=arr[0];
for(int j=0;j<arr.length - 1;j++){
arr[j]=arr[j+1];
}
arr[n-1]=t;
d--;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
This should be it for the exceptions, but you also need to fix the code's functionality as it is not giving you the answer that it is supposed to. I think that it can be fixed with just a little bit more of revising and changing the while loop (int t might be causing the problem.)
I hope you enjoy your journey with Java. Have a great day and remember to stay safe!
I am searching for matching elements in two arrays. If the matching element was found I set k and j greater than the for loop conditions to quit the cycle, but I get an exception at inner loop condition. Granted, I can fix it by using break outerloop;, but isn't setting index greater than the for loop condition supposed to exit the loop?
//outerloop:
for (int j = 0; j < listOfSubcategories.size(); j++) {
if (listOfSubcategories.get(j).subcatName.equals(rawOptions.get(i).subcatName)) { //if the subcatName exists
for (int k = 0; k < listOfSubcategories.get(j).listOfID.size(); k++) {
if (0 == rawOptions.get(i).codeID.compareTo(listOfSubcategories.get(j).listOfID.get(k).codeID)) {//if this id (as in 0090-01 exists
listOfSubcategories.get(j).listOfID.get(k).usageCount += rawOptions.get(i).usageCount;
isProcessed = true;
k=listOfSubcategories.get(j).listOfID.size(); //this fails
j = listOfSubcategories.size();
//break outerloop; //this works
}
}
}
}
First of all, can you please post your stack trace?
Second, your exception is most likely caused by j = listOfSubcategories.size(); This makes comparison k < listOfSubcategories.get(j).listOfID.size() impossible.
The code below works.
public class ForArray {
public static void main(String[] args) {
int[] myIntArray = {1, 2, 3}; //This is my Array
int searchingForThisNumberInArray = 2; //Search for this number in an array
int index=-1; //Index of the first matching element. -1 if element not found.
for (int i = 0; i < myIntArray.length; i++) { //Check each element
if (myIntArray[i] == searchingForThisNumberInArray) { //if this element contains correct number
index = i; //Save it in index
i = myIntArray.length; //Quit for cycle by increasing i.
}
}
System.out.println(index);
}
}
So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?
I tried writing a Sieve of Eratosthenes algorithm, I am getting an ArrayIndexOutOfBoundsException but I don't seem to understand why, if I change the limits, upon printing it only displays composite numbers, the code's below help if you can.
public static Boolean[] solution(int N) {
Boolean[] isPrime = new Boolean[N];
isPrime[0] = false;
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for(int i = 2; i <= N; i++) {
if(isPrime[i]== true) {
System.out.println(i);
for(int j = 2; (j * i) < N; j++) {
int k = j * i;
isPrime[k] = false;
}
}
}
return isPrime;
i <= N; cause the error
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for example
if N=4 then you get error when i=4. isPrime[4] cause OutOfBounds exception because length is 4.arrays are zero index based. so maximum index you can access is 3.isPrime[3]
you can avoid this error by changing loop to for(int i = 1; i < N; i++) {
however i'm not sure what is Eratosthenes algorithem is .i hope you can change your code keep in mind arrays are zero index based
Boolean[N] creates an array of N elements, so, since the indexes start from 0, the last index is N-1.
The error is caused by i<=N in the for loop
I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.