Exception in thread main error in array program - java

// getting exception in thread main error in result[row][col]= arrayfirst [row][col] + arraysecound [row[col];
public class apples
public static void main(String args[])
{
int arrayfirst[] [] ={{1,2,3},{2,3,4}};
int arraysecound[] [] ={{3,4,5},{6,7,8}};
int result[][]= new int [2][2];
for(int row =0; row<arrayfirst.length; row++)
{
for(int col =0; col<arrayfirst[row].length; col++)
{
result[row][col]= arrayfirst [row][col] + arraysecound [row][col];
}
}
for(int row =0; row<arrayfirst.length; row++) {
for(int col =0; col<arrayfirst[row].length; col++) {
System.out.print(" "+result[row][col]);
}
System.out.println();
}
}
}
// BUT THESE SIMILAR PROGRAMS RUNS CORRECTLY WHY
public static void main(String args[])
{
int arrayA[][] = {{1,4,3,5},{3,8,1,2},{4,3,0,2},{0,1,2,7}};
int arrayB[][] = {{6,1,0,8},{3,2,1,9},{5,4,2,9},{6,5,2,0}};
int arrayC[][] = new int[4][4];
for(int i = 0; i < arrayA.length; i++) {
for(int j = 0; j< arrayA[0].length; j++) {
arrayC[i][j] = arrayA[i][j] + arrayB[i][j];
// System.out.print(arrayC[i][j] + " ");
} // end j for loop
} // end i for loop
for (int i = 0; i < arrayC.length; i++) {
for (int x = 0; x < arrayC[i].length; x++) {
System.out.print(arrayC[i][x] + " | ");
}
System.out.println();
}
} // end main
} // end class

int arrayfirst[] [] ={{1,2,3},{2,3,4}};
int arraysecound[] [] ={{3,4,5},{6,7,8}};
here, arrayfirst and arraysecound contain two rows and three columns each (The number of inner curly braces separated by Comma signify number of rows, and the numbers written within these inner curly braces signify number of columns), so when you add their elements and try to store the result, you again need an array that has two rows and three columns.
so, just replace
int result[][]= new int [2][2];
with
int result[][]= new int [2][3];

Your result array in the first program is too small.

Change following
int result[][]= new int [2][2];
to
int result[][]= new int [2][3];
Also, to learn more about arrays in java, have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Related

How to display methods in the console that read from a file?

I need to be able to display the Average, ColumnTotal, Highest/Lowest in row, RowTotal. I'm not sure whether it depends on something I did in the methods themselves that has to be changed, or if I can simply that call them with the correct arguments to read from a file. The text file that it reads from basically just inputs two integers that are separated by a space on the same line, those are the arguments I would like to be able to input. I'm not entirely sure how to do this. This is just an assignment from a College text book basically amped up by my Instructor called "TwoDimArray" which I've been able to find many examples of online but none of them had the 'read from file' portion that I have to do here, they all just used a normal array input such as "int[][] array = {{22, 37, 48, 68}} for the main method. I'm going to include the entire program in order to show exactly what I need to be displayed via println. I've been thinking about how to do this for quite a few hours now and decided that I definitely need help. Any help would be greatly appreciated! Thanks ahead of time.
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwoDimArray {
private int arr[][];
public TwoDimArray() {
loadArray();
}
public void loadArray(){
/**
* loadArray() method loads user defined filename
* #return text file's contents
*/
String fileName = "";
try {
fileName = JOptionPane.showInputDialog("Enter file name: ");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
return;
}
try {
Scanner in = new Scanner(new File(fileName));
int rows, cols;
rows = in.nextInt();
cols = in.nextInt();
arr = new int[rows][cols];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
arr[i][j] = in.nextInt();
}
}
in.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
}
}
public int getArrayMaxValue(){
/**
* #return the max vale of the array
*/
int maxVal = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] > maxVal){
maxVal = arr[i][j];
}
}
}
return maxVal;
}
public int getArrayMinValue(){
/**
* #return the minimum value of the array
*/
int minVal = Integer.MAX_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] < minVal){
minVal = arr[i][j];
}
}
}
return minVal;
}
public static int getTotal(int[][] array) {
int total = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
}
return total;
}
public static int getAverage(int[][] array) {
return getTotal(array) / getElementCount(array);
}
public static int getRowTotal(int[][] array, int row) {
int total = 0;
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
return total;
}
public static int getColumnTotal(int[][] array, int col) {
int total = 0;
for (int row = 0; row < array.length; row++) {
total += array[row][col];
}
return total;
}
public static int getHighestInRow(int[][] array, int row) {
int highest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] > highest) {
highest = array[row][col];
}
}
return highest;
}
public static int getLowestInRow(int[][] array, int row) {
int lowest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] < lowest) {
lowest = array[row][col];
}
}
return lowest;
}
public static int getElementCount(int[][] array) {
int count = 0;
for (int row = 0; row < array.length; row++) {
count += array[row].length;
}
return count;
}
public static void main(String[] args){
/**
* what to put in int[][] array to allow println of average, getrowtotal,
* etc..
*/
int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(getAverage(array));
}
}
0) Create numbers.txt in the root of your project. This is the file you will load array from. Example content as follows (2 rows, 3 columns):
2 3
1 2 3
4 5 6
1) You don't need your explicitly created int[][] array = ??? because there is already existing private int arr[][] which will be automatically loaded from file after you type it's name as intended in TwoDimArray constructor.
2) Since main method located at the same class as private int arr[][], you can access this private array without public getter/setter, and get average value like this:
// you don't need following line at all
// int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue()); // Max value: 5
System.out.println("Min value: " + twoDimArray.getArrayMinValue()); // Min value: 1
// Average value
System.out.println(getAverage(twoDimArray.arr)); // 3, because 21 / 6 = 3
3) You probably got confused because getArrayMaxValue is signed as public int, and got invoked as twoDimArray.getArrayMaxValue(), whereas getAverage is public static int and must be called in different way.
I suggest marking getAverage as public int instead of public static int, and use private int arr[][] instead of int[][] array provided from arguments, so you will be able to call it the same way you do with other methods:
// Somewhere up
public int getAverage() {
return getTotal(arr) / getElementCount(arr);
}
// In your main method
System.out.println(twoDimArray.getAverage());
Basically, what you have there is a jagged array, it is not a bidimensional array. I will explain you the idea, you do the rest. That it is not a bidimensional array. This is an array of array, in each position you are pointing to a new array of int. If you never instantiated a new array on each position, then you have a position with a null value.
So going back with your question, you should read the entire line with the two integers that are on the same line. Be sure that the line in your file has in the first line 2 numbers separated by a space.
Then use the next() method to get the complete string
String line = in.next();
String[] parts = line.split(" ");
int val1 = Integer.parseInt(parts[0]);
int val2 = Integer.parseInt(parts[1]);
For this question:
what to put in int[][] array to allow println of average, getrowtotal,
int[][] array = new int[4];
array[0] = new int[] {10,20,30,40,50};
array[1] = new int[] {60,71,80,90,91};
array[2] = new int[] {1};
Hope this helps
Now, what do you think you have in array[3]? The answer is: NULL
you already read the array from file in your method loadArray...
Use it instead of trying to load the same thing again, remove static modifier from all method and use field arr instead of parameter array
private int getTotal() {
int total = 0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
total += arr[row][col];
}
}
return total;
}
private int getAverage() {
return getTotal() / getElementCount();
}
private int getElementCount() {
int count = 0;
for (int row = 0; row < arr.length; row++) {
count += arr[row].length;
}
return count;
}
public static void main(String[] args) {
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(twoDimArray.getAverage());
}

Error when trying to print a transposed 2d array

While writing my code I'm getting stuck on I'm trying to return the new transposed array and actually transposing the array itself. I get the error cannot convert int to int[][]. i thought trans would be an array var. the problem code is at the way bottom. any help is greatly appreciated.
package workfiles;
import java.util.*;
import java.util.Scanner;
public class hw2 {
// Do not modify this method
public static void main(String[] args) {
try
{
int [][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);
int [][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
}
catch (InputMismatchException exception)
{
System.out.println("The array entry failed. The program will now halt.");
}
}
// A function that prints a 2D integer array to standard output
// It prints each row on one line with newlines between rows
public static void print2DIArray(int[][] output) {
for (int row = 0; row < output.length; row++) {
for (int column = 0; column < output[row].length; column++) {
System.out.print(output[row][column] + " ");
}
System.out.println();
}
}
// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException {
int row=0;
int col=0;
int arow=0;
int acol=0;
int holder;
Scanner numScan = new Scanner(System.in);
while (row<=0){
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}
while (col<=0){
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}
int[][] iArray = new int[row][col];
while (arow < row) {
while (acol < col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
iArray[arow][acol] = holder;
acol++;
}
if (acol >= col) {
acol = 0;
arow ++;
}
}
//arrayName[i][j]
numScan.close();
return iArray;
}
//!!! problem code here!!!
public static int[][] transposition(int [][] iArray) {
int m = iArray.length;
int n = iArray[0].length;
int trans[][];
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans = iArray[y][x] ;
}
}
return trans;
}
}
You missed two things
1.) initialization of trans
int trans[][]= new int [n][m];
2.) trans is a 2D array
trans[y][x] = iArray[y][x] ;
//trans = iArray[y][x] ; error
Update : To form this logic , we need index mapping like this
// trans iArray
// assign values column-wise row-wise
// trans[0][0] <= iArray[0][0]
// trans[1][0] <= iArray[0][1]
// trans[2][0] <= iArray[0][2]
mean traverse the iArrays row-wise and assign values to trans array columns-wise
int m = iArray.length;
int n = iArray[0].length;
// iArray[2][3]
int trans[][] = new int[n][m];
// 3 2
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans[x][y] = iArray[y][x] ;
}
}

Error in output on converting 2D String array to 1D String array

For a practice problem for my programming class we have:
"Define a method that returns the first row of a two-dimensional array of strings that has a string with the name “John”."
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
System.out.println(firstRow(b)); // line 8
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
After going through the debug process on Eclipse, my String array name is set to {"John", "Abby"}, however I am getting an ArrayIndexOutOfBoundsException error at lines 8 and 17 when attempting to run the program.
Confused on what to do to get this program to output the names "John" and "Abby."
Because of this line;
for (int row = 0; row < a.length; row++) {
The goal of firstRow(String[][] a) method is returning the first row of the array, thus, the line above should be as below;
for (int row = 0; row < 1; row++) {
Because that it traverse all of the elements of the array, it exceeds the size of the name array which has only a[0].length rooms, numerically, 2. ( String[] name = new String[a[0].length]; )
In order to make your code functional, there are two ways;
First Solution
Update the for loop conditional as written above, the test code is;
public class TwoDimensionalStringArrayI {
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
String[] name = new String[a[0].length];
int counter = 0;
// for (int row = 0; row < a.length; row++) {
for (int row = 0; row < 1; row++) {
for (int col = 0; col < a[row].length; col++) {
name[counter++] = a[row][col]; // line 17
}
}
return name;
}
}
The output is as below;
John Abby
You've noticed (you should), I've also updated the print line.
Second Solution
The second way to make your code functional is, returning only first row for a[][], which is actually is as easy as returning a[1]. The test code is;
public static void main(String[] args) {
String[][] b = {{"John", "Abby"},
{"Sally", "Tom"}};
// System.out.println(firstRow(b)); // line 8
String[] result = firstRow(b);
for(int i = 0; i < result.length; i++)
System.out.print(firstRow(b)[i] + " ");
}
public static String[] firstRow(String[][] a) {
return a[0];
}
And the output is;
John Abby
Hope that it helps.
I think you should switch the variables row and col in line 17.

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

Changing values in an array

Ok, so here are my codes (main method and method I'm trying to call)
I want my method "rotateRR" to basically take the value from board[0] and put it on [1] and keep doing that for that single row. For example:
old array -> [1][2][3][4][5] to become [5][1][2][3][4] <- what new array should look like.
but after I call my method, I put my regular input which should be "1 rr", but it returns the same array. I need to return the updated array from rotateRR method, but it doesn't let me add a return statement.
public class Numbrosia {
static int [][] board = new int[5][5];
public static void main(String [] args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();
}
}
Scanner input = new Scanner (System.in);
while (true){
showBoard();
System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();
if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}
}
}
public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");
}
}
//METHODS
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type
The main problem with the method is that it's not even doing what you described as the functionality:
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
Should be changed to:
public static void rotateRR (int [][] board){
// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];
// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}
// Set the first entry to temp
board[0] = temp;
}
So after that method your array you inserted as a parameter is changed the way you described above. Notice that you don't need a return type, since the change affects the original array (keyword call-by-reference).
You have made the function void therefore you cannot return anything from it. So what you need to do is change it from void to something like char * and then return the associated char * to solve your problem
Read this: http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html for any further doubts.
Change this:
public static void showBoard()
to this
public static return-type showBoard()

Categories