Can not figure out how to increment a two dimensional array - java

So, basically what I want to do with my code is make it so that a user can enter in a value, and then the program will add whatever value that would be to ALL the values in the array
//my code
{
//creates array called table
int[][] table = new int [10][10];
//load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;
//Print the table
for (int row=0; row < table.length; row++)
{
for (int col=0; col < table[row].length; col++)
System.out.print (table[row][col] + "\t");
System.out.println();
int incr;
Scanner scan = new Scanner(System.in);
System.out.println("");
System.out.println("What do you want to increment by?");
incr = scan.nextInt();
for (int row=0; row < table.length; row++)
{
for (int col=0; col < table[row].length; col++)
System.out.print (table[row][col] + "\t");
System.out.println();
}
}
That is my code so far, and I'm not sure where to go from here. If someone could help me figure this out, that would be great.

inside the loop add this line of code:
table[row][col] += incr;

Related

Having trouble taking user inputs and forming arrays

I need to take user inputs and and post them to a two dimensional array. This is what I have so far:
System.out.print("How many students? ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int col = input;
int row = 5;
String[][] y = new String[col][row];
for (col = 0; col < y.length; col++) {
for(row = 0; row < y[col].length; row++){
int n = col + 1;
System.out.println("Enter the name and grades of student " + n);
y[col][row] = scan.next();
}System.out.println();
}
for(row = 0; row< y.length; row++){
for(col = 0 ;col< y[row].length; col++){
System.out.println(y[row][col]);
}
System.out.println();
}
The only problem is that it asks the same question 5 times over before moving on to the next student. Do I stay on this same path? Or would it be easier to scrap it and go at it with a different approach?
this loop of yours goes trough each student,
for (col = 0; col < y.length; col++)
and this loop of yours goes trough each note and asks to input them,
for(row = 0; row < y[col].length; row++)
so, it's logical that you want to ask the user only one time to input the note, saying that you only need to ask it each time you iterate a student in the array, simply change this:
for (col = 0; col < y.length; col++) {
for(row = 0; row < y[col].length; row++){
int n = col + 1;
System.out.println("Enter the name and grades of student " + n); //you are asking each time you iterate a note
y[col][row] = scan.next();
}System.out.println();
to this:
for (col = 0; col < y.length; col++) {
System.out.println("Enter the name and grades of student " + col); //you are asking each time you iterate a student
for(row = 0; row < y[col].length; row++){
int n = col + 1;
y[col][row] = scan.next();
}System.out.println();
}
What you could do is that you can ask all the details for a particular student and then proceed for the next student rather than asking the same question for each student.
Try this:
System.out.print("How many students? ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
int col = input;
int row = 5;
String[][] y = new String[col][row];
for (col = 0; col < y.length; col++) {
System.out.println("Enter the name and grades of student " + col);
for(row = 0; row < y[col].length; row++){
int n = col + 1;
y[col][row] = scan.next();
}System.out.println();
}
for(row = 0; row< y.length; row++){
for(col = 0 ;col< y[row].length; col++){
System.out.println(y[row][col]);
}
System.out.println();
}
This will ask to enter the details once per student.
if you like to accept name and 4 grades input then this is your
code,else elaborate your problem
for (col = 0; col < y.length; col++) {
>
> int n = col + 1;
>
> System.out.println("Enter the name and grades of student " + n);
>
> for(row = 0; row < y[col].length; row++){
>
> y[col][row] = scan.next();
> }System.out.println();
> }

Trying to input values into a 2d array and print it, code not running

Code not running??
import java.util.Scanner;
public class Array2dNightPractice
{
int[][] studentmarks;
studentmarks = new int[3][3];
Scanner kb = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<3;row++){
for(int col=0;col<3;col++){
studentmarks[row][col] = kb.nextInt();
}
}
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 4; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
}
you're getting IndexOutOfBoundsException because of this --> col < 4.
for(int col = 0; col < 4; col++)
change to this:
for(int col = 0; col < studentmarks[row].length; col++)
side note - make use of the length property to prevent errors such as the one you've just encountered.
full solution:
for(int row = 0; row < studentmarks.length; row++) {
for(int col = 0; col < studentmarks[row].length; col++) {
System.out.print(studentmarks[row][col] + " ");
}
System.out.println();
}
the error comes from exceeding the bound of the array studentMarks in the second for loops at the number 4 it should be 3
A good habit to develop is to create constant variables as required with the size of each of the rows and columns, so you will not fall in such mistake.
Something like this:
import java.util.Scanner;
public class Array2dNightPractice{
public static void main(String[] agrs){
final int ROW =3, COL=3; // constant variable to determine the size of the 2d array
int[][] studentMarks = new int[ROW][COL];
Scanner in = new Scanner(System.in);
System.out.println("Enter 9 integers");
for(int row = 0;row<ROW;row++){ //note how I don't need to memorize and rewrite the numbers every time
for(int col=0;col<COL;col++){
studentMarks[row][col] = in.nextInt();
}
}
// print the marks as matrix
for(int row =0; row <ROW; row++) {
for(int col =0; col <COL; col++) {
System.out.print(studentMarks[row][col] + " ");
}
System.out.println();
}
}
}

Finding the sum of columns in a Two Dimensional Array with rows of different lengths

So i'm having a bit of trouble with my code in returning the sum of the columns in a two dimensional array with rows of different lengths. For example a 2X2 array works perfectly to calculate the sum of the columns. But if I were to have for example a 2X3 array it gives me an out of bounds error. I want it to work for any numbers given by the user for rows and columns not just a fixed number that I said as an example. Can somebody help me resolve this issue? much thanks!
here is my code:
public static void columnSum(int[][]anArray) {
int totalcol = 0;
for(int col =0; col < anArray.length; col++){
totalcol = 0;
for(int row = 0; row < anArray[col].length; row++) {
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
}
Your indices are flipped. Your for loops are written for column-major ordering, but your totalizer is written for row-major order. You need to reverse one or the other.
You have a problem in the for loop
for(int row = 0; row < anArray[col].length; row++) {
totalcol += anArray[row][col];
}
If the array is 2X3 then in this for loop when you are using the col = 0 Then anArray[col].length returns value 3. So your row variable can have values 0 - 2 in the for loop. So when the value of row is 2 and the value of column is 0 (as stated earlier), anArray[row][col] will throw an ArrayOutOfBoundException as anArray[2][0] does not exists.
So try out this instead:
for(int row = 0; row < anArray.length; row++) {
totalcol += anArray[row][col];
}
I think this will work.
The question does not specify the order of the array elements. There are two possiblities:
anArray[i][j] represents the element at row i and column j (row-major)
anArray[i][j] represents the element at column i and row j (column-major)
The easier task to solve is finding column sums in a column-major array, or---completely equivalently---row sums in a row-major array. The proposed solution in the question only needs to replace totalcol += anArray[row][col] with totalcol += anArray[col][row] and would already work for this case.
It is a bit more difficult to compute column sums in a row-major array, or---again equivalently---row sums in a column-major array. The rest of this answer shows how to compute column sums for a row-major array. In this case, anArray.length is the number of rows, and anArray[i].length is the number of columns in row i.
In the more usual case where all your rows have the same number of columns, you could do this:
int numrows = anArray.length;
int numcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int col = 0; col < numcols; col++) {
int totalcol = 0;
for(int row = 0; row < numrows; row++) {
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
If your rows may each have a different number of columns (as suggested by the question title), you need to:
Determine when there are no more columns to sum over.
When computing the sum of column col, make sure to skip rows that are too short
One way would be:
int numrows = anArray.length;
for(int col = 0; /* not known a priori*/; col++) {
int totalcol = 0;
boolean emptySum = true; // At first, assume no rows are long enough
for(int row = 0; row < numrows; row++) {
if(anArray[row].length <= col ) continue; // Skip short row
emptySum = false; // Mark assumption as wrong
totalcol += anArray[row][col];
}
// Exit the loop if we did not sum anything, i.e. no row had a column with index col
if(emptySum) break;
System.out.println("Sum of column " + col + " = " + totalcol);
}
Instead of using the awkward emptySum flag to quit the loop, you could determine the maximal column length in a preliminary pass:
int numrows = anArray.length;
int maxnumcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int row = 1; row < numrows; row++) {
maxnumcols = Math.max(maxnumcols, anArray[row].length);
}
for(int col = 0; col < maxnumcols; col++) {
int totalcol = 0;
for(int row = 0; row < numrows; row++) {
if(anArray[row].length <= col) continue; // Skip short row
totalcol += anArray[row][col];
}
System.out.println("Sum of column " + col + " = " + totalcol);
}
Finally, if you are allowed to store the sums (instead of immediately outputting them), this would be an even cleaner solution (note the row-major order of iteration, which fits nicely to the row-major order of the array itself):
int numrows = anArray.length;
int maxnumcols = (numrows > 0) ? anArray[0].length : 0; // Guard against 0x0 array
for(int row = 1; row < numrows; row++) {
maxnumcols = Math.max(maxnumcols, anArray[row].length);
}
int[] colsums = new int[maxnumcols]; // In Java, all elements are initialized to zero
for(int row = 0; row < numrows; row++) {
for(int col = 0; col < anArray[row].length; col++) {
colsums[col] += anArray[row][col];
}
}
for(int col = 0; col < colsums.length; col++) {
System.out.println("Sum of column " + col + " = " + colsums[col]);
}

Display lottery winners

I created a lottery program to randomly generate 3 numbers between 0-9 and then randomly generate the 3 winning numbers. I need help on how to make the program display the winners (if there are some) and display the number of how many won the lottery.
So something like:
Winners:
Person1
person5
Number of winners: 2
Here is my program
import java.util.Random;
public class TwoDArray
{
public static void main(String[] args)
{
int[][] table = new int[50][3];
int[][] win = new int[1][3];
Random rand = new Random();
int i = 1;
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = rand.nextInt(7-0 +1)+0 + col;
// Load the winning Values
for (int row=0; row < win.length; row++)
for(int col=0; col < win[row].length; col++)
win[row][col] = rand.nextInt(7-0 +1)+0 + col;
// Print the table of People
for (int row=0; row < table.length; row++)
{
System.out.print("Person" + i++ +":\t");
for (int col=0; col < table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
//Print the Winning Numbers
for (int row=0; row < win.length; row++)
{
System.out.print("\nThe winning numbers are:\t");
for(int col=0; col < win[row].length; col++)
System.out.print(win[row][col] + "\t");
System.out.println();
}
}
}
You want another for loop. Something like:
int counter = 0;
for (int i =0; i < table.length; i++){
if (table[i][0] == win[0][0] && table[i][1] == win[0][1] && table[i][2] == win[0][2])
{
counter++;
System.out.println("Person " + i);
}
}
System.out.println("There were " + counter + " winners.");

How do you print rows and columns in a 2-d array?

I'm trying to get this array to display 4 values arranged in a 2x2 array. With what I'm doing so far, I'm getting an array out of bounds error. How can I do this display properly?
import java.util.Scanner;
import java.util.Random;
public class GridPractice
{
public static void main(String[] args)
{
//declarations
Scanner in = new Scanner(System.in);
Random generator = new Random();
int [][] grid; //un-instantiated grid
int size = 0; //number of rows and columns
//get size of grid - no validation & instantiate
System.out.print("Enter size of grid: ");
size = in.nextInt();
grid = new int[size][size];
//fill grid with random number from 1..99
System.out.println();
for (int row=0; row<size; row++)
{
for (int col=0; col<size; col++)
{
grid[row][col] = generator.nextInt(100); //random numbers 0.99 - not 100
}
}
System.out.printf("%2d\n", grid[size][size]);
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.printf("%2d ", grid[row][col]);
}
System.out.println();
}
Try this:
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println("");
}
plus remove this line, this is the culprit of the exception:
System.out.printf("%2d\n", grid[size][size]);

Categories

Resources