How would I display the position of an element in an array? - java

My dilemma is after the user inputs a number, that number is then checked to see if it's in the array, if it is i'll let them know that is in the array along with the position of that said number. I have it to where it prompts user for the number, but after that i get the ArrayIndexOutOfBoundsException error.
Here's what I have so far:
int [] iGrades = new int [30];
System.out.print ("Enter the grades, when you're done input (-1) ");
for (int i=0; i<iGrades.length;i++)
{
iGrades [i]= kb.nextInt();
if (iGrades [i]< 0)
{
break;
}
}
System.out.print ("\nEnter a grade to check if it's in the array");
iVal = kb.nextInt();
for(int i=0; i<=iGrades.length; ++i)
{
if(iVal == (iGrades[i]))
{
found = true;
for(int j=0; j<=iGrades.length; ++j)
{
iGrades[j]=j+1;
}
break;
}
}
if (found == true)
{
System.out.println(iVal + " is in the array at position ");
}
else
{
System.out.println(iVal + " is NOT in the array.");
}
}
Any assistance would be great.

The problem is in your second for loop. This
for(int i=0; i<=iGrades.length; ++i)
Change the <= to <.

The exception says it already. You are checking an index that is not in the bounds of the array any more. Look at the second for loop:
for(int i=0; i<=iGrades.length; ++i)
It runs from 0 to 30. The array only goes from 0 to 29 though. You have to use < instead here:
for(int i=0; i < iGrades.length; i++)

Since arrays are zero-based, this
i<=iGrades.length
will allow i to equal Grades.length, which is one past the last index of the array. Use <.

Remember
Array Index start from 0 to length of array -1
Change the loop accordingly
Hint change <= to <

Related

Making An Array of Selected Values That Only Displays Specific Values

I'm trying to figure out how to print out a second array that is based off my first one but only displays values that are greater than the value to its left and less than the value to it's right and displaying these values by row in the row that they are in the original array. Here's my code so far.
public static void main(String[] args)
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
row = 3;
col = 6;
// enter array elements.
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.println("Enter a value: ");
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("Matrix Display :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);
System.out.println(arr[3]);
}
}
You won't know how many of the elements fit your criteria, so you need to use a mutable object. Since each row might have a different number of matching numbers, you won't be able to make a normal array without null values in it most of the time.
Use a 2D ArrayList, scan through your original 2D array, and add the value that match your criteria to the corresponding row of your ArrayList.
You could do something like this:
int width = arr[0].length-1;
ArrayList<ArrayList<Integer>> listoflists= new ArrayList<ArrayList<Integer>>();
// Scan array for matching values
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
listoflists.add(new ArrayList<Integer>());
if(j==0 && arr[i][0]<arr[i][1])
listoflist.get(i).add(arr[i][0]);
else if(j==width && arr[i][width]>arr[i][width-1]
listoflist.get(i).add(arr[i][width]);
else if( #this is the last condition to check from both sides)
listoflist.get(i).add(arr[i][j]);
}
}

Java - array comparing doesnt terminate when match found?

Although the recommendations on asking a question did not prohibit this, if I violate any rules by asking specific questions, please let me know.
I am trying to compare the user input to the previous user inputs (1-9) then checking for repeats. However, my program won't stop if it encounters a repeat. What am i doing wrong?
import java.util.Scanner;
public class No_Duplicates {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
boolean repeat = false;
do {
int[] array = new int[9];
for(int i = 1; i <= 9; i++)
{
System.out.println("Enter a number 1 - 9");
int num = scan.nextInt();
array[i] = num;
for(int j = 1; j <= i; j++)
{
if(num==array[j])
repeat = true;
}
}
}while(!(repeat == true));
System.out.println("No Duplicates Allowed!");
}
}
Your code doesn't stop when it encounters a repeated element.
I also noticed that you are accessing the array index from 1 not 0. In Java, array indices start from 0. So, you should start from 0 and stop before the length of the array. Otherwise, you'll run into ArrayIndexOutOfBoundsException.
Here is something you can try:
boolean repeat = false;
int[] array = new int[9];
for(int i=0 ; i<9 && repeat!=true ; i++)//checks for repeated input
{
System.out.println("Enter a number 1 - 9");
int num = scan.nextInt();
array[i] = num;
for(int j=0; j<i; j++)
{
if(num==array[j])
{
repeat = true;
break; //breaks out of the loop if encounters a repeated input
}
}
}
if(repeat)
System.out.println("No Duplicates Allowed!");

How to check if certain numbers appear in an array?

I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}
To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}

Calling a method to print an array in single line

I've been trying to work out what is wrong but I can't seem to figure it out. Essentially my code will get the user to input N size of array. The array will then be filled with random numbers generated from 1-100. I have a printArray method which prints the elements of an array in a single line that I've tested on a fixed array and it works, but when I call it from the generated array it gives me a lot of extra 0's.
Here is the code:
Scanner scan = new Scanner(System.in);
System.out.println("Size of array:"); //prompts the user enter size of array
int size = scan.nextInt();
int array[] = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) + 1;
printArray(array);
and here is the display method:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i == 0) {
System.out.print(array[i]);
}
else if (i == array.length) {
System.out.print(array[i]);
}
else
System.out.print("," + array[i]);
}
}
When I run the code it will generate an output like this:(3 as example)
Size of array to sort?
3
36,0,036,68,036,68,75, where it's supposed to just be 36,68,75.
You are printing the array multiple times in a single line.
In the first iteration you print 36,0,0, In the second iteration you print 36,68,0 and only in the final iteration you print the fully initialized array - 36,68,75.
Move printArray(array); to the end of the loop. You might want to add a println at the end of printArray.
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) + 1;
}
printArray(array);

How to stop a "ArrayIndexOutOfBounds" exception

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++)

Categories