Switching rows on 2d-array generated at random - java

This is a 2d array which is generated at random, and stores 20 integers from 100-1000. I got that part right, I'm trying to switch the rows of this 2d array and not having much luck, i tried the temp but for some reason it comes out as column array...
public static void main (String args[]){
int [][] randArray = new int[2][10];
Random rnd = new Random();
for(int i=0; i<randArray.length; i++)
for(int j=0; j<randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i=0; i < randArray.length; i++){
System.out.println("Row " + i);
for (int j=0; j < randArray[i].length; j++)
System.out.print(randArray[i][j]+ " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j=0; j < randArray[0].length; j++){
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " ");
}
}
}
Switch the rows as in row1 [1,2,3,4,5] row2 [6,7,8,9,10] to row1[6,7,8,9,10] row2[1,2,3,4,5]

You can use Arrays.deepToString(Object[]) to print the array. Display the array after you perform your swap. Something like,
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++) {
for (int j = 0; j < randArray[i].length; j++) {
randArray[i][j] = 100 + rnd.nextInt(900);
}
}
System.out.println(Arrays.deepToString(randArray));
System.out.println("Switch row ");
for (int j = 0; j < randArray[0].length; j++) {
int temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
}
System.out.println(Arrays.deepToString(randArray));

Your code is working actually I fixed only the compile error;
public static void main(String args[]) {
int[][] randArray = new int[2][10];
Random rnd = new Random();
for (int i = 0; i < randArray.length; i++)
for (int j = 0; j < randArray[i].length; j++)
randArray[i][j] = 100 + rnd.nextInt(900);
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
System.out.println("Switch row ");
int temp = 0;
for (int j = 0; j < randArray[0].length; j++) {
temp = randArray[0][j];
randArray[0][j] = randArray[1][j];
randArray[1][j] = temp;
//System.out.println(randArray[i][j]+ " "); no i variable
}
//I added only below lines to print your result
for (int i = 0; i < randArray.length; i++) {
System.out.println("Row " + i);
for (int j = 0; j < randArray[i].length; j++)
System.out.print(randArray[i][j] + " ");
System.out.println();
}
}

Related

How to get the sum for each row?

I want to find and display the row number that has the maximum sum and display the row values and this is sample input/output:
The problem is every time the maximum sum is the third row how to solve these issues.
int [][] scores = new int[4][3];
for (int i=0; i<scores.length; i++)
{
System.out.print("Enter values for row "+i+": ");
for (int j=0; j<scores[i].length;j++)
scores[i][j] = kbd.nextInt();
}
int sum, sumMax, ii=0;
for (int i=0; i<scores.length; i++)
{
sum =0; sumMax = 0; ii=0;
for (int j=0; j<scores[i].length;j++)
{
sum += scores[i][j];
if (sum>sumMax)
{
sumMax = sum;
ii = i;
}
}
}
System.out.println("Row "+ii+" has the maximum sum");
System.out.print("Row "+ii+" has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
To print a specific row, you need one loop only
System.out.print("Row " + ii + " has the following values: ");
for (int j = 0; j < 3; j++)
System.out.print(scores[ii][j] + " ");
Or with Arrays.toString
System.out.println("Row " + ii + " has the following values: " + Arrays.toString(scores[ii]));
Also your finding max code is wrong, as you reset ii and sumMax to 0 for each row, the max can only be the last line, you need to keep track of these 2 along the rows. Also use the if only after computing the row's sum, no need to test at every bow of every row
int sum, sumMax = Integer.MIN_VALUE, ii = 0;
for (int i = 0; i < scores.length; i++) {
sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
if (sum > sumMax) {
sumMax = sum;
ii = i;
}
}
You can add the rows while getting the input from scanner and store them in an array. Then you can search for the max value in the sums array:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int[][] scores = new int[4][3];
int[] rowSums = new int[4];
for (int i = 0; i < scores.length; i++) {
System.out.print("Enter values for row " + i + ": ");
for (int j = 0; j < scores[i].length; j++){
scores[i][j] = kbd.nextInt();
rowSums[i] += scores[i][j];
}
}
int index = 0;
int maxSum = rowSums[index];
for(int i = 1; i < rowSums.length; i++){
if(rowSums[i] > maxSum){
maxSum = rowSums[i];
index = i;
}
}
System.out.println("Row "+index+" has the maximum sum");
System.out.print("Row "+index+" has the following values: ");
for(int i = 0; i < scores[index].length; i++){
System.out.print(scores[index][i] + " ");
}
}
}

How to print column total directly below each column in 2D array

My code requests the user to input array size, as well as values. I want to sum each column and display the total below each column, as in a table.
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.println("Total column: " + columnSum);
}
You can try this
String message="Total Column:";
Scanner input=new Scanner(System.in);
int row=2,column=3;
StringBuilder array_output=new StringBuilder();
int a[][] = new int[row][column];
for (int i = 0; i < row; i++){
array_output.append(String.format("%"+message.length()+"s",""));
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
System.out.print(message+" \t");
for (int j = 0; j < column; j++){
int columnSum = 0;
for (int i = 0; i < row; i++){
columnSum += a[i][j];
}
System.out.print(columnSum+"\t");
}
Notice only the additional changes that added on top of your code snippet.
int a[][] = new int[row + 1][column]; // +1 for total/sum
for (int j = 0; j < column; j++){
//... rest of the logic correct
a[row][j] = columnSum;
}
//Print the result
for (int i=0; i < row+1; i++) {
for (int j=0; j < column; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
Your problem is that you are using the same variable columnSum in each interation. If you want a sum for each column then columnSum needs to be an array with an entry for each column. Then you can print that array as last output row.
I recommend to give the variables i and j a more meaningful name. Call row rows and i row and you can read you code more easily.
Just create an array of result. Now while entering data in input array, prepare your result array by adding column data in result array. In last print it. It will same time and 1 extra for loop.
int a[][] = new int[row][column];
int result[] = new int[column];
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
System.out.println("Number" + (j + 1 )+ ": ");
a[i][j] = input.nextInt();
array_output.append("\t").append(a[i][j]);
result[j] = result[j]+a[i][j];//creating array of column sum
}
array_output.append("\n");
System.out.println("\n");
}
System.out.println("Array: ");
System.out.println(array_output);
for (int j = 0; j < result.length; j++){
System.out.print(result[j] + "\\t");
}

Elevens Activity 4 APCS debugging

I am a beginner programmer in APCS, and I am getting this error message on my code (below). How do I fix this? I am not sure what is wrong with it because I believe all of the called variables are within the scope of the code and I declared them as public... Let me know what I should be looking for, and what is wrong please! Thank you very much.
Error:
java.lang.ArrayIndexOutOfBoundsException: 4
at Shuffler.perfectShuffle(Shuffler.java:49)
at Shuffler.main(Shuffler.java:16)
Code:
import java.util.ArrayList;
public class Shuffler
{
private static final int SHUFFLE_COUNT = 1;
private static final int VALUE_COUNT = 4;
public static void main (String[] args)
{
System.out.println ("Results of " + SHUFFLE_COUNT + " consecutive perfect shuffles:");
int[] values1 = new int[VALUE_COUNT];
for (int i = 0; i < values1.length; i++)
{
values1 [i] = i;
}
for (int j = 1; j <= SHUFFLE_COUNT; j++)
{
perfectShuffle (values1);
System.out.print(" " + j + ":");
for (int k = 0; k < values1.length; k++)
{
System.out.println (" " + values1 [k]);
}
System.out.println();
}
System.out.println();
System.out.println("Results of " + SHUFFLE_COUNT + " consecutive efficient selection shuffles:");
int[] values2 = new int[VALUE_COUNT];
for (int i = 0; i < values2.length; i++)
{
values2[i] = i;
}
for (int j = 1; j <= SHUFFLE_COUNT; j++)
{
selectionShuffle(values2);
System.out.print(" " + j + ":");
for (int k = 0; k < values2.length; k++)
{
System.out.print(" " + values2[k]);
}
System.out.println();
}
System.out.println();
}
public static void perfectShuffle (int[] values)
{
int[] temp = new int [52];
int k = 0;
for (int j = 0; j < 25; j++)
{
temp [k] = values [j];
k+=2;
}
k=1;
for (int j=26; j<values.length; j++)
{
temp [k] = values [j];
k+=2;
}
for (int j=0; j<values.length; j++)
{
values [j] = temp [j];
}
}
public static void selectionShuffle (int[] values)
{
ArrayList<Integer> temp=new ArrayList<Integer>(52);
int rando=(int) Math.random()*52;
for (int counter=0; counter<temp.size(); counter++)
{
temp.set (counter,rando);
}
}
}

Cannot get the addition to output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Array Index out of Bound Exception while running the program to find largest of an array

Here is the code:Getting Array index out of Bound exception
class Max {
public static void main(String args[]) {
int a[][];
Scanner src = new Scanner(System. in );
System.out.println("Enter the no of rows");
int rows = src.nextInt();
a = new int[rows][5];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = src.nextInt();
}
}
System.out.println("Array is");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(" " + a[i][j]);
}
System.out.println();
}
int l = a[0][0];
int i;
for (i = 0; i < rows; i++)
l = a[i][0];
for (int j = 0; j < 5; j++)
if (l < a[i][j])
l = a[i][j];
System.out.println("Max" + l);
}
}
on run time it gives the following:
Exception in thread "main" java.lang.Array index out of Bound Exception:3
at Max.main Max.java:33
Can Anyone suggest what is wrong in the code????
You miss a { after the for (i = 0; i < rows; i++) so that the for (int j = 0; j < 5; j++) loop is inside the first one.
Without that, this gives:
for (i = 0; i < rows; i++)
l = a[i][0];
// End of the for i loop, now i = rows.
for (int j = 0; j < 5; j++)
if (l < a[i][j]) // i = rows: bang.
l = a[i][j];
Try this:
public static void main(String args[]) {
int a[][];
Scanner src = new Scanner(System. in );
System.out.println("Enter the no of rows");
int rows = src.nextInt();
a = new int[rows][5];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = src.nextInt();
}
}
System.out.println("Array is");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(" " + a[i][j]);
}
System.out.println();
}
int l = a[0][0];
int i;
for (i = 0; i < rows; i++) {
l = a[i][0];
for (int j = 0; j < 5; j++)
if (l < a[i][j])
l = a[i][j];
}
System.out.println("Max" + l);
}

Categories

Resources