fixing Exception in main thread - java

Everything with my code seems to work correctly, whenever the boolean method returns true. However, when trying to test false, after the user enters 10 numbers I receive the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at FunArrays.main(FunArrays.java:15
What am I missing or overlooking with my code?
Here is my code:
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Please enter ten numbers....");
int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
boolean lucky = isLucky(userArray);
if (lucky){
sum(userArray);
} else
sumOfEvens(userArray);
}
public static boolean isLucky(int [] numbers){
for (int i = 0; i <= numbers.length; i++){
if (numbers[i]== 7 || numbers[i] == 13 || numbers[i] == 18){
return true;
}
}
return false;
}
public static void sum(int [] numbers){
int sum = 0;
for (int x = 0; x <= numbers.length -1; x++){
sum += numbers[x];
}
System.out.println(sum);
}
public static void sumOfEvens(int [] numbers){
int evens = 0;
for (int y = 0; y <= numbers.length -1; y++){
if (numbers[y] % 2 == 0){
evens += numbers[y];
}
}
System.out.println(evens);
}
}

You are entering 10 numbers but your array has only 9 spots. Change it to
int [] userArray = new int [10];

int [] userArray = new int [9];
for(int b = 0; b < 10 ; b++){
userArray [b] = input.nextInt();
}
Your array size is 9 (from index 0 to index 8) and your loop increment b from 0 to 9 (10 cases)
In this case b should be less than 9 in your loop.
So you could replace by this code:
int maxInput = 9;
int [] userArray = new int [maxInput];
for(int b = 0; b < maxInput ; b++){
userArray [b] = input.nextInt();
}

You should declare a size 10 array, since you are accepting 10 values from the user.
int [] userArray = new int [9];
Here is a good read on Arrays: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html

You're trying to store 10 numbers in an array of length 9.
Use int[] userArray = new int[10];

Related

Need to print rows of multidimensional array as columns

This is my program output:
Enter the size of 2D array:
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
and I need this instead:
1 12 5 16
2 11 6 15
3 10 7 14
4 9 8 13
I want the 2d array to be of size NxN where n is the integer inputted by the user. I want the first consecutive values to be stored in the even indexed columns from top to bottom and the next consecutive values to be stored in the odd indexed columns from bottom to top.
import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=inc;
inc++;
}
}
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println("\n");
}
}
public static int[][] transpose (int[][] array) {
if (array == null || array.length == 0)//empty or unset array, nothing do to here
return array;
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
return array_new;
}
}
As Sean pointed out in the comments, your transpose() function returns a new array but you are not capturing that and using it. The original array remains unchanged, which is what you are displaying at the end.
Change:
transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : arr) {
To:
int[][] newArr = transpose(arr);
// now let's print a two dimensional array in Java
for (int[] a : newArr) {
Try this out. It should do what you have described in the question.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of 2D array: ");
System.out.println();
int n = input.nextInt();
int arr[][] = new int[n][n];
int inc=1;
for(int j = 0; j < n; j += 2) {
for(int i = 0; i < n; i++) {
arr[i][j]=inc++;
}
}
for(int j = 1; j < n; j += 2) {
for(int i = n - 1; i >= 0; i--) {
arr[i][j]=inc++;
}
}
// now let's print a two dimensional array in Java
for (int[] a : arr) {
for (int i : a) {
System.out.print(i + "\t");
}
System.out.println();
}
}

Array Parameter proplem

I'm stuck..... i have been trying to use Arrays in methods to count the number of numbers divisible by 10 from the range 1-100.
here's my code:
import java.util.Scanner;
import java.util.Random;
public class Journal5a {
// METHOD
public int[] creatArray (int size)
{
int[] array = new int[size];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt(100);
return array;
}
public int[] DivByTen()
{
int x = 0;
int y[] = this.creatArray(1);
for (int i = 0; i < y.length; i++)
if (y[i] % 10 == 0)
{
x++;
}
return x;
}
public int[] printArray ()
{
int[] myArray = this.creatArray(1);
for (int i = 0; i<myArray.length; i++)
System.out.println(myArray[i]);
return myArray;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Journal5a j5a = new Journal5a();
j5a.DivByTen();
}
So my output would be :
there is 10 numbers divisible by 10
Another problem is the x used in the method DivByTen isn't being returned.
Your createArray() method fills the array with random numbers from 0-99, so it is not clear how much numbers are dividable by 10.
for(int i = 0; i < size; i++) {
array[i] = i;
}
will create an array with values from 0 to size - 1.
The second problem is that your return type is int[] instead of int
First, create and fill the array. For the range 1 to 100 you would need to pass in 100 and either start with i at 1 (or add 1 to i when you initialize the array);
private static int[] creatArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
Next, count the multiples of some multiple. Something like,
private static int countMultiples(int[] arr, int multiple) {
int count = 0;
for (int val : arr) {
if (val != 0 && val % multiple == 0) {
count++;
}
}
return count;
}
Finally, call the above methods and output the result
public static void main(String[] args) {
final int multiple = 10;
int count = countMultiples(creatArray(100), multiple);
System.out.printf("There are %d numbers divisible by %d.", count, multiple);
}
Output is
There are 10 numbers divisible by 10.

Although not exceed index, I get error by the index

My question is
( - Write the following method that merges two sorted lists
into a new sorted list. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. - )
When I run this code, Eclipse give error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at single_dimension_all_arrays.Merge_two_sorted_lists.getNumber(Merge_two_sorted_lists.java:60)
at single_dimension_all_arrays.Merge_two_sorted_lists.main(Merge_two_sorted_lists.java:77)
I can't understand why give the error. I can't exceed index.
private static void sort(int [] list3)
{
int temp=0;
for (int i = 0; i < list3.length; i++)
{
for (int j = 0; j < list3.length; j++)
{
if(list3[i]<list3[j])
{
temp=list3[i];
list3[i]=list3[j];
list3[j]=temp;
}
}
}
for (int i = 0; i < list3.length; i++)
{
System.out.println(list3[i]);
}
}
private static void getNumber(int [] list1,int [] list2)
{
Scanner scan = new Scanner(System.in);
int [] list3 = new int[list1.length+list2.length];
for (int i = 1; i < list1.length; i++)
{
System.out.println("Please, enter the number");
list1[i] = scan.nextInt();
}
for (int i = 1; i < list2.length; i++)
{
System.out.println("Please,enter the number");
list2[i]= scan.nextInt();
}
for (int i = 0; i <= list3.length; i++)
{
if(i<list1.length)
{
list3[i]=list1[i];
}
else if(i>list1.length)
{
list3[i] = list2[i];
}
}
sort(list3);
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please,enter the length of list1");
int l1 = scan.nextInt();
System.out.println("Please, enter the length of list2");
int l2 = scan.nextInt();
int [] list1 = new int[l1];
int [] list2 = new int[l2];
list1[0]=l1;
list2[0]=l2;
getNumber(list1,list2);
}
}
Thanks..:)
Although not exceed index...
Yes you do:
for (int i = 0; i <= list3.length; i++)
// ----------------^
The valid range of indexes is 0 to length - 1, so that should be < as it is in several other parts of your code.
Side note: You're also skipping the first element in arrays in a few places:
for (int i = 1; i < list1.length; i++)
// ----------^

How do I sort the numbers inputted from an array to tell how many times the number was entered

Ok so this is my code. I'm supposed to gather 10 numbers of input and then sort them in descending order by the number of which they appear.
Ex. {0,0,1,2,2,2]
My output would be "Mode=2 and then have 2 appears 3 times, 0 appears two times, 1 appears once."
My code can gather the 10 integers and find the mode but I'm having issues trying to sort the numbers in that way. This is what I have so far and I'm stuck.
import java.util.*;
class question2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arrTwo = new int[10];
int x=0;
for (int i = 0; i < 10; i++)
{
System.out.println("Enter number: " + (i + 1));
arrTwo[i] = scan.nextInt();
}
mode(arrTwo);
int temp;
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x )
{
if (bs[x]>bs[x+1])
{
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
for(int i = 0; i <= bs.length-1; i++)
{
for(int index=0; index <= 99 ; index++)
{
if (i == i)
{
bs[i] +=1;
}
}
System.out.println("The number " + i + " is generated " +arrTwo[i] + " times");
}
}
public static void mode(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println("The mode is: "+maxIndex);
}
My output isn't listing my numbers, just 0-9 and the generated times is just going from 1-9 with no basis or order.
this code:
int bs[] = new int[10];
for ( x=0 ; x<=8 ; ++x ){
if (bs[x]>bs[x+1]) {
temp=bs[x];
bs[x]=bs[x+1];
bs[x+1]=temp;
x=-1;
}
}
does nothing. On initialization bs is filled with zeroes bs[x-1] is never greater than bs[x] because all values are the same.
also
if (i == i){
is always true

processing an array via method

is it possible to use a reference and pass it to a method as a argument and do the
initialization in the method body in java?
what i mean is this:
i have a method that get's a array as parameters:
public static void arrayreader(int [] [] m){
int rows,cols;
rows=input.nextInt();cols=input.nextInt();
m = new int [rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
m[i][j] = input.nextInt();
}
}
}
i want to do the initialization of array in the method body not in the main method
but java dont allow that and says it's not initialized
If you made that array a return value instead of a parameter, your main method can look like this:
int[][] m = arrayreader();
You can't, because when you say:
m = new int [rows][cols];
You are effectively assigning a new array to "m" reference(pointer), thus you are losing the reference to the array passed as argument.
if you would like to initialise an array in the method, than there is no need to pass it as a parameter
you can do something like this instead
public static int[][] arrayreader()
{
int rows,cols;
int[][] result = new int[rows][cols];
rows=input.nextInt();
cols=input.nextInt();
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
result[i][j] = input.nextInt();
}
}
return result;
}
you can also create the array object in main like:
int rows,cols;
rows=input.nextInt();cols=input.nextInt();
m = new int [rows][cols];
and then can have the function like:
public static void arrayreader(int [] [] m, int rows, int cols){
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
m[i][j] = input.nextInt();
}
}
}
Taking into account that I spent one day due to errors like:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
I implemented all the ideas from above in the code bellow which works like a charm for matrix multiplication:
import java.util.*;
public class MatmultC
{
private static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
int m = sc.nextInt();
int n = sc.nextInt();
int a[][] = new int[m][n];
arrayreader(a,m,n);
printMatrix(a);
int[][] b = readMatrix();
printMatrix(b);
int[][] c=mult(a,b);
printMatrix(c);
}
public static void arrayreader(int [][] m, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = sc.nextInt();
}
}
}
public static int[][] readMatrix() {
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = sc.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%4d " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static int[][] mult(int a[][], int b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new int[0][0];
if(a[0].length != b.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = b[0].length;
int ans[][] = new int[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
}
}
where as input matrix we have inC.txt
4 3
1 2 3
-2 0 2
1 0 1
-1 2 -3
3 2
-1 3
-2 2
2 1
in unix like cmmd line execute the command:
$ java MatmultC < inC.txt > outC.txt
and you get the output
outC.txt
Matrix[4][3]
1 2 3
-2 0 2
1 0 1
-1 2 -3
Matrix[3][2]
-1 3
-2 2
2 1
Matrix[4][2]
1 10
6 -4
1 4
-9 -2

Categories

Resources