User Input java 2d Array - java

I need to create code that takes user input to create the size of the 2d array (rows and columns must be less than 6), then fill it up with values that the user gives (between -10 and 10). My loop for taking the values isn't working at all and I'm not sure why. Here's the code
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
// create loop for accepting values within the matrix
// first loop for row values
for (int i = 0; i < userArray.length; i++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix rows");
int rowValues = input.nextInt();
while (rowValues > 10 || column < -10) {
System.out.println(
"Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
rowValues = input.nextInt();
}
// second embedded loop for column values
for (int j = 0; j < userArray[i].length; j++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix columns");
int columnValues = input.nextInt();
while (columnValues > 10 || column < -10) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter a number between 10 and -10.");
columnValues = input.nextInt();
}
}
}
printMatrix(userArray);
}

Couple of things here. First, your for-loop has two separate loops for the rows and columns. I assume what you're going for is prompting the user for each individual cell of the 2D array, which would require two nested loops. Second, at no point does your code example assign the user input to a variable, so I presume your output is just a bunch of 0 values?
You're probably looking for something more like this:
for (int i = 0; i < userArray.length; i++)
for(int j = 0; j < userArray[i].length; j++)
{
System.out.println("Please enter numbers between -10 and 10 for your matrix");
int valueIn = input.nextInt();
while (valueIn > 10 || valueIn < -10)
{
System.out.println("Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
valueIn = input.nextInt();
}
userArray[i][j]=valueIn;
}

You need a nested loop, to read values at row and then column level.
Something like below:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
for(int i=0;i< row ; i++){
for(int j=0; j< column; j++) {
System.out.print("Please enter the value for array["+i+"]["+j+"] (between -10 and 10):");
int val = input.nextInt();
if(val>10 || val< -10) {
System.out.println("Invalid value.");
continue;
}
userArray[i][j] = val;
}
}
printMatrix(userArray, row, column);
}
public static void printMatrix(int[][] array, int row, int column) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}

public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows.");
int rows = getValueFromConsole(scan, 1, 5);
System.out.println("Enter number of columns.");
int cols = getValueFromConsole(scan, 1, 5);
System.out.println("Enter matrix data.");
int[][] matrix = createMatrix(scan, rows, cols, -99, 99);
printMatrix(matrix);
}
private static int[][] createMatrix(Scanner scan, int rows, int cols, int min, int max) {
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = getValueFromConsole(scan, min, max);
return matrix;
}
private static int getValueFromConsole(Scanner scan, int min, int max) {
while (true) {
System.out.format("Number [%d:%d]: ", min, max);
int val = scan.nextInt();
if (val >= min && val <= max)
return val;
System.out.println("Sorry. Your number is not correct. Try again.");
}
}
private static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.format("%4d", matrix[row][col]);
System.out.println();
}
}
}
Output:
Enter number of rows.
Number [1:5]: 3
Enter number of columns.
Number [1:5]: 3
Enter matrix data.
Number [-99:99]: 10
Number [-99:99]: -11
Number [-99:99]: 12
Number [-99:99]: -13
Number [-99:99]: 14
Number [-99:99]: -15
Number [-99:99]: 16
Number [-99:99]: -17
Number [-99:99]: 18
10 -11 12
-13 14 -15
16 -17 18

Related

Matrix Multiplication, Index Out of Bounds Exception

I have try to create a code that can solve a matrix.
import java.util.Scanner;
public class Pratical_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking A Matrix
System.out.println("Enter number of Rows and Column for first Matrix");
System.out.print("Enter Rows ");
int aRLen=sc.nextInt();
System.out.print("Enter Columns ");
int aCLen=sc.nextInt();
int [][] a = new int [aRLen][aCLen];
System.out.println("Enter Matrix");
for(int i=0;i<aRLen;i++)
{
for(int j=0;j<aCLen;j++)
{
a[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Taking B Matrix
System.out.println("Enter number of Rows and Column for second Matrix");
System.out.print("Enter Rows ");
int bRLen=sc.nextInt();
System.out.print("Enter Columns ");
int bCLen=sc.nextInt();
int [][] b = new int [bRLen][bCLen];
System.out.println("Enter Matrix");
for(int i=0;i<bRLen;i++)
{
for(int j=0;j<bCLen;j++)
{
b[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Creating resulting Matrix
int [][] r = new int [aRLen][bCLen];
// Check for Valid input
if(aCLen!=bRLen)
{
System.out.println("Error invalid input");
System.out.println("Multiplication of this matrix is not possible");
}
else
{
for(int i=0;i<aCLen;i++)
{
for(int j=0;j<bRLen;j++)
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
}//End of if-else
}//End of main
}//End of class
it have an error after sucessfully give an output
Output:-
Enter number of Rows and Column for first Matrik
Enter Rows 1
Enter Columns 3
Enter Matrix
1
2
3
Enter number of Rows and Column for second Matrix
Enter Rows 3
Enter Columns 1
Enter Matrix
1
2
3
14
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Pratical_8.main(Pratical_8.java:57)
Process finished with exit code 1
This Error only ocure in non Sysmetrix Matrix
What is the PROBLEM?
Since the final matrix is of order aRLen x bCLen the last for loops needs to be modified.
for(int i=0;i<aRLen;i++) // Instead of aClen
{
for(int j=0;j<bCLen;j++) //Instead of bRlen
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
This will work properly.

How to accept values within a certain range 2d array

I was wondering how to i set a range between certain number when entering numbers in?
Thanks
I tried using a do loop but it just kept looping even when i entered numbers within the range
public static void main(String args[])
{
int row, col, i, j;
int a[][]=new int[10][10];
do{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the order of a square matrix :");
row=sc.nextInt();
col=sc.nextInt();
/* checking order of matrix and then if true then enter the values
* into the matrix a[][]
*/
if(row == col)
{
System.out.println("Enter elements in the matrix:"+row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
a[i][j]=sc.nextInt();
}
}
} while(row != col);
// Display the entered value
System.out.println ("You have entered the following matrix");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
System.out.print (a[i][j] + " ");
System.out.println ();
}
First of all you should learn to extract tasks in methods and add Javadoc to make your code easier to read.
Hope this helps you:
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int dimension;
System.out.println("Enter the dimension of a squared matrix :");
dimension = sc.nextInt();
final int col = dimension;
final int row = dimension;
int[][] matrix = fillMatrix(row, col);
displayMatrix(matrix);
}
/**
* Prints the given matrix to console
*
* #param matrix to be printed
*/
private static void displayMatrix(int[][] matrix) {
System.out.println("You have entered the following matrix");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
/**
* Uses users input to fill create a matrix with the given dimensions
*
* #param row matrix row dimension
* #param col matrix column dimension
*
* #return a filled matrix
*/
private static int[][] fillMatrix(final int row, final int col) {
System.out.println("Enter elements in the matrix:" + row * col);
int[][] matrix = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmpNumber = 0;
while(tmpNumber<15 || tmpNumber >60){
System.out.println(String.format("Enter value for row %s, column %s between 15 and 60", i, j));
tmpNumber = sc.nextInt();
}
matrix[i][j] = tmpNumber;
}
}
return matrix;
}
Output:
Enter the dimension of a squared matrix :
2
Enter elements in the matrix:4
Enter value for row 0, column 0 between 15 and 60
2
Enter value for row 0, column 0 between 15 and 60
17
Enter value for row 0, column 1 between 15 and 60
18
Enter value for row 1, column 0 between 15 and 60
19
Enter value for row 1, column 1 between 15 and 60
20
You have entered the following matrix
17 18
19 20
First add the bounds as constant
final int LOWER_BOUND = 0;
final int UPPER_BOUND = 100;
Then check in the loop each entered value against the bounds before adding the value to the array
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
The problem remaining is that you can't use you for loops as they are now since the user might need several iterations to enter the right value. One simple solution is to surround the above code in a infinite while loop that is not exited until a correct value is given.
while (true) {
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
break;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
}
A better solution might be to replace the innermostfor loop with a while loop where you increase j manually when a correct value has been entered
This is simple example for your cause.
public static void main(String[] args) {
int number;
String getInputLine;
Scanner sc = new Scanner(System.in);
int a[][] = new int[10][10];
// for number of rows in your array
for (int i = 0; i < a.length; i++) {
// for number of columns in your array
for (int j = 0; j < a[0].length; j++) {
// print this message on screen
System.out.print("Enter your number: ");
// get input from next line
getInputLine = sc.nextLine();
//if you haven't match one or more integers
while (!getInputLine.matches("\\d{1,}")) {
System.out.print("Error! You inputted an invalid passcode, try again: ");
getInputLine = sc.nextLine(); // Prints error, gets user to input again
}
number = Integer.parseInt(getInputLine); // parse input into an integer
a[i][j] = number; // store it to array at position i j
System.out.println("You've set number " + number + " for array[" + i + " " + j + "]"); // Prints the passcode
}
}
//print your array
System.out.println(Arrays.deepToString(a));
}
}

Adding columns and rows in a 2D array of String type?

I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.

2D Array printing in one column error

Please keep in mind my switch statement is not complete yet. I'm trying to figure out why that when I try and print intArray everything comes out in a single column. If anyone needs details don't hesitate to ask.
import java.util.*;
public class twoDimensionalArray
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int choice, row, col, upper, lower;
System.out.println("Choose the number of rows for the array");
row = console.nextInt();
System.out.println("Choose the number of columns for the array");
col = console.nextInt();
int[][] intArray = new int[row][col];
choice = Menu();
switch(choice)
{
case 1:
do
{
System.out.println("Choose a lower bound for the random numbers");
lower = console.nextInt();
System.out.println("Choose an upper bound for the random numbers");
upper = console.nextInt();
if (lower > upper)
{
System.out.println("The lower bound must be less than the upper bound");
}
}
while (lower > upper);
fillArray(intArray, upper, lower);
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: System.exit(0);
}
}
public static int Menu()
{
Scanner console = new Scanner(System.in);
int choice;
do
{
System.out.println("Enter the number corresponding to your choice:\n"
+ "1) Fill the array with new values \n"
+ "2) Find largest element \n"
+ "3) Find smallest element \n"
+ "4) Find Sum of elements \n"
+ "5) Find average of elements \n"
+ "6) Count the number of even elements \n"
+ "7) Total the odd values \n"
+ "8) FindIt \n"
+ "9) Print Array \n"
+ "10) Exit");
choice = console.nextInt();
}
while (choice < 1 || choice > 10);
return choice;
}
public static int[][] fillArray(int[][] intArray, int upper, int lower)
{
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
intArray[row][col] = lower + (int)(Math.random() * ((upper - lower) + 1));
}
}
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}
return intArray;
}//end fillArray
}//end program
There's a difference between System.out.println() and System.out.print().
Your code:
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.println(intArray[row][col]);
}
}
My code:
for (int row = 0; row < intArray.length; row++)
{
for (int col = 0; col < intArray[row].length; col++)
{
System.out.print(intArray[row][col]);
}
System.out.println("");
}
print() prints the String argument, whereas println() prints the argument followed by a new line. I also added an additional call to println() between the rows so that they'll print out on their own lines.
System.out.println(intArray[row][col]) - println will end every print with a new line. To avoid this, use system.out.print()

The values of the columns of my 2D array are averaging wrong with out of order inputs

I'm working on a code to produce a 2D array to hold user inputted values. I made a averaging function in the "print array for loop"but it messes up such as when column input (3 1 2) gives an average of output of (2 6 4). All the values of the array were set to 2 for testing. I can't figure out what is wrong with the loop. I'm new to java so I'm sorry if the answer is something obvious.
The table printed should look like this with row(3) and columns(3 1 2):
A:2.0 2.0 2.0 [3.0]
B:2.0 [2.0]
C:2.0 2.0 [2.0]
where the bracketed term holds the average and the 2.0 are the values held by the column.
The code:
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group+" : ");
for(int col=0; col<figures[row].length; ++col) {
sum += figures[row][col];
average = sum/figures[row].length;
System.out.print(" "+figures[row][col]);
System.out.print(" ");
}
System.out.printf("%1$5s","["+average+"]");
System.out.println();
}
}
PS: its a minor question, I'm using %1$5s to keep the bracket term 5 spaces from the printed columns, but I was wondering if there is a way to keep them all at the same length.
You need to add
sum = 0;
after
for(int row=0; row<figures.length; ++row) {
otherwise the totals are wrong when you calculate the average.
To pad out a string, there's a good answer on here already How can I pad a String in Java?. Look at the 2nd answer.
int minLen = 20;
String s = myformat(value, length);
int diff = minLen - s.length;
System.out.printf("%1$" + diff + "s", s);
Where String s is your formatted string using your above "[" + average + "]" stuff. The idea is that you have a minimum length string to work with so that your positioning is always the same.

Categories