I try to print the matrix AxA with all of the values are showed in there, but I failed.
Output should be something look like this:
1 2 3
4 5 6
Thank you
So this is my code:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j] = input.nextInt();
}
System.out.println(" " + array);
}
}
Updated:
I was able to print out the matrix, but now I run into the second question is calculating the average of each rows and columns of the matrix. I tried to use this code, but it didn't work, and I know that I have a major problem right here, but I couldn't find one.
I have been doing it since this morning until now. Not going to lie, this is my homework which to test my basic knowledge.
My new output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
ave=2.5, 3.5, 4.5
And this is my current code right now:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
public static doube averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
public static doube averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
You can use same logic for reading and writing array elements,Try this code
Reading an array...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
array[i][j] = input.nextInt();
}
}
Printing array elements...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
Use
Stream.of(array).map(Arrays::toString).forEach(System.out::println);
Which will print :
[1 ,2, 3]
[4, 5, 6]
or
System.out.println(Arrays.deepToString(array));
Reference
Keep in mind that you can't simply print the whole array. I.e.: System.out.println(" " + array);
You're on the right track but you need to print using a for loop (give printf a try, it's powerful):
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++){
System.out.printf("%d ", array[i][j]);
}
System.out.printf("\n");
}
There is another single loop way I can think of:
for (int[] a : array) {
String str = Arrays.toString(a);
System.out.println(str.substring(1, str.length()-1).replaceAll("[,]", ""));
}
The for loop basically iterates over each row, i.e. value of 'a' is an array (row) in the matrix.
Arrays.toString(a) returns the string equivalent of the array, e.g. for a = [1,2,3,4,5], it would return "[1, 2, 3, 4, 5]". Now simply remove the brackets (substring) and replace commas (",") with "", and you have the desired result.
Note that the first parameter of the replaceAll is a regex, not the string itself.
Related
My code is almost done but the problem is the returning size it supposed to return the size after the duplicated elements has been removed. it wont output the right size.
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
int size;
int i;
int j;
Scanner scn = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
size = scn.nextInt();
System.out.println("\n");
int myArray[] = new int [size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value for num["+i+"]: ");
myArray[i] = scn.nextInt();
}
System.out.print("\nThe inputted values are ");
for(i = 0; i < size; i++)
{
System.out.print(" " + myArray[i] + ",");
}
System.out.print("\nDuplicate values ");
for (i = 0; i < myArray.length-1; i++)
{
for (j = i+1; j < myArray.length; j++)
{
if ((myArray[i] == myArray[j]) && (i != j))
{
System.out.print(" " +myArray[j]+ ",");
}
}
}
int length = myArray.length;
length = remove_dupli(myArray,length);
System.out.print("\nThe new values of the array are ");
for(i = 0; i < length; i++)
{
System.out.print(" " +myArray[i]+", ");
}
System.out.println("\nThe new length of the array is: "+array_sort(myArray));
}
is there a problem on this part?
public static int remove_dupli(int myArray[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (myArray[i] != myArray[i+1]){
temp[j++] = myArray[i];
}
}
temp[j++] = myArray[n-1];
for (int i=0; i<j; i++){
myArray[i] = temp[i];
}
return j;
}
or this part?
public static int array_sort(int[] myArray) {
int index = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[index-1])
myArray[index++] = myArray[i];
}
return index;
}
}
The output should be:
Enter Number of Elements: 4
Enter value for num[0]: 2
Enter value for num[1]: 2
Enter value for num[2]: 3
Enter value for num[3]: 4
The inputted values are 2,2,3,4
Duplicated values 2,
The new values of the array are 2,3,4
The new length of the array is 3
The process you are using to find the duplicate elements is fine but you are not actually changing the elements in the array , you are just printing the non-duplicate ones, best approach is to change the value of the duplicate elements as a flag and then to find the length of the array after the duplicates have been removed,it will be easy :
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++)
{
if((array[i]==array[j]) && i!=j)
System.out.println("duplicate value:"array[j]);
array[j]=-1;
}
}
So, now for the array length after removing the duplicate elements is:
int count=0;
for(int i=0;i<array.length;i++){
if(array[i]!=-1)
count ++;
}
Trying to change this code so I can get user input instead of a predefined array. Can anyone help? This code needs to have the method sum with the double[][] parameter. The method should return the sum of the elements of the array passed to it and should be rectangular.
import java.util.Scanner;
class Array2_1
{
public static double sum (double[][] array)
{
double sum = 0;
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[0].length; j++)
{
sum += array[i][j];
}
}
return sum;
}
public static void main(String[] args)
{
System.out.println("")
double a [][] = {
{1.2, 2},
{6, 7.2},
{11, 12}
};
System.out.println(sum(a));
}
}
You can use Scanner to read values from the keyboard. First, read the values for the dimensions of the array and then input values for the individual indices using nested loops.
You can also define a method to display the array in the tabular form.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
double array[][] = new double[rows][cols];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("Enter value for array[%d][%d]: ", i, j);
array[i][j] = scanner.nextDouble();
}
}
System.out.println("The array:");
print(array);
System.out.println("Sum of elements: " + sum(array));
}
public static double sum(double[][] array) {
double sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
}
return sum;
}
public static void print(double[][] array) {
for (double[] row : array) {
for (double col : row) {
System.out.print(col + "\t\t");
}
System.out.println();
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 2
Enter value for array[0][0]: 1.2
Enter value for array[0][1]: 2
Enter value for array[1][0]: 6
Enter value for array[1][1]: 7.2
Enter value for array[2][0]: 11
Enter value for array[2][1]: 12
The array:
1.2 2.0
6.0 7.2
11.0 12.0
Sum of elements: 39.4
I have added comments to the code for your understanding. Hope it answers your query.
public static void main(String[] args) {
//You can use the Scanner class for taking input
Scanner scan = new Scanner(System.in);
//take input for the number of rows in array
System.out.println("Enter no. of rows in array");
int row = scan.nextInt();
//take input for the number of columns in array
System.out.println("Enter no. of columns in array");
int col = scan.nextInt();
//create an array with row and col as dimensions of the 2D array
double[][] arr = new double[row][col];
//this for loop is for inputting elements in your array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
arr[i][j] = scan.nextInt();
//this for loop is for printing out the elements
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
scan.close();
//now give a call to your sum() method and print the result
System.out.println(sum(arr));
}
I am able to print the 2 2D arrays with the numbers from user input and I am also able to print the odd numbers, but I am having trouble combining the two forms of code so that the odd numbers stay consistent with their cell and not just in one print line. How would I print the odd numbers leaving the non odds as blanks in 2 3x3 arrays?
Heres the code for printing the array:
public static void display ( int[][] FirstArray, int[][] SecondArray)
{
//Print first array
System.out.print("Array1: \n");
for (int row = 0; row < FirstArray.length; row++)
{
for(int column = 0; column < FirstArray[row].length; column++)
{
System.out.print(FirstArray[row][column] + " ");
}
System.out.println();
}
//Print second array
System.out.print("Array2: \n");
for (int row = 0; row < SecondArray.length; row++)
{
for(int column = 0; column < SecondArray[row].length; column++)
{
System.out.print(SecondArray[row][column] + " ");
}
System.out.println();
}
}
ex output:
array 1: array2
3 3 3 4 4 4
3 3 3 4 4 4
3 3 3 4 4 4
Here is the code for printing the odd numbers without in the 3x3 format like the code above:
public static void display(int[][] FirstArray, int[][] SecondArray)
{
int count=0;
for (int i = 0; i < FirstArray.length; i++) {
for (int j = 0; j < FirstArray.length; j++)
{
if(FirstArray[i][j]%2==1)
{
System.out.println(m1[i][j]);
}
}
}
for (int i = 0; i < SecondArray.length; i++) {
for (int j = 0; j < SecondArray.length; j++)
{
if(SecondArray[i][j]%2==1)
{
System.out.println(SecondArray[i][j]);
}
}
}
ex output:
3 3 3 3 3 3 3 3 3 (odd numbers displayed but in one line)
Ex output of what Im looking for(assuming i entered in even numbers too):
3 3 3
3 3 3
3 3
You can redress your print statements in both the loops as :
for (int i = 0; i < FirstArray.length; i++) {
for (int j = 0; j < FirstArray.length; j++) {
if(FirstArray[i][j]%2==1) {
System.out.print(m1[i][j] + " "); // odd number and space
} else {
System.out.print(" "); // blank space for even numbers
}
}
System.out.println(); // next line for next row
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers of rows : ");
int n = sc.nextInt();
System.out.println("Enter number of colmns : ");
int m = sc.nextInt();
int[][] array = new int[n][m];
System.out.println("Enter elements of array : ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(" X[ " + i + "," + j + "] = ");
array[i][j] = sc.nextInt();
}
}
System.out.print("Even numbers on position :");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] % 2 != 0) {
System.out.print(array[i][j] + " ");
}
}
}
I have all of my other methods that were required for my class program working properly, however I can not think of how to fix my row input and sum method and my column input and sum method. I also apologize for the ridiculously long method names, the methods for pre-named for the assignment.
import java.util.Scanner;
public class Two_D_Array_CMPS280_2016
{// begin class Two_D_Array_CMPS280_2016
public static void main(String args[])
{// begin main method
int[][] brianArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};// end array initialization
// Print segment to print values from methods for brianArray
System.out.print("The sum of all elements is " + Total_2DArray_Elements(brianArray));
System.out.print("\nThe average of all elements is " + Average_2DArray_Elements(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Row_Number(brianArray));
System.out.print("The sum is: " + Total_2DArray_Elements_by_Certain_Column_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Row_Number(brianArray));
System.out.print("The largest value is: " + The_Largest_Value_In_Certain_Column_Number(brianArray));
}// end main method
public static void printArray(int[][] myArray)
{// begin to print arrrays
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}// end printArray method
public static int Total_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
}
}
return total;
}
public static int Average_2DArray_Elements(int[][] myArray)
{// begin method to sum array values
int total = 0;
int average = 0;
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
total += myArray[i][j];
average = total / 16;
}
}
return average;
}// end method to sum array values
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[0].length; j++)
{
total += myArray[row][j];
}
}
return total;
}// end method to sum array by user input row
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[0].length; j++)
{
total += myArray[i][column];
}
}
return total;
}// end method to sum array by user input column
public static int The_Largest_Value_In_Certain_Row_Number(int[][] myArray)
{// begin method to return largest number by user input row
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the row you would like the highest value from: ");
int row = input.nextInt() - 1;
for (int i = row; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
if (myArray[row][j] > highestValue)
highestValue = myArray[row][j];
}
}
return highestValue;
}// end method to return largest number by user input row
public static int The_Largest_Value_In_Certain_Column_Number(int[][] myArray)
{// begin method to return largest number by user input column
java.util.Scanner input = new Scanner(System.in);
int highestValue = 0;
System.out.println("\nPlease enter the column you would like the highest value from: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++)
{
for (int j = column; j < myArray[i].length; j++)
{
if (myArray[i][column] > highestValue)
highestValue = myArray[i][column];
}
}
return highestValue;
}// end method to return largest number by user input column
}// end class
Here is Java 8 magic, which will help u sum, average etc of any row or colum
int[][] intArray =
{// initialize array and hard code values
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
//Sum specific column
int columnNo=0;
Integer sumOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).sum();
Double avgOfColum=Arrays.stream(intArray).mapToInt(i->i[columnNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfColum);
//Sum of specific row
int rowNo=0;
Integer sumOfRow=Arrays.stream(intArray[rowNo]).sum();
Double avgOfRow=Arrays.stream(intArray[rowNo]).average().getAsDouble();
System.out.println(sumOfColum);
System.out.println(avgOfRow);
Change your methods to the following, should do you good :
public static int Total_2DArray_Elements_by_Certain_Row_Number(int[][] myArray)
{// begin method to sum array by user input row
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the row you would like to sum: ");
int row = input.nextInt() - 1;
for (int j = 0; j < myArray[0].length; j++) {
total += myArray[row][j];
}
return total;
}// end..
and
public static int Total_2DArray_Elements_by_Certain_Column_Number(int[][] myArray)
{// begin method to sum array by user input column
java.util.Scanner input = new Scanner(System.in);
int total = 0;
System.out.println("\nPlease enter the column you would like to sum: ");
int column = input.nextInt() - 1;
for (int i = 0; i < myArray.length; i++) {
total += myArray[i][column];
}
return total;
}// end m..
I'm struggling to find an answer to the problem below. User inputs rows and columns. Example below is given for 4 x 4 matrix.
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
I cannot find how to relate the numbers when printing the array. The only obvious relation is how it goes downwards and upwards. From my perspective looks really hard. I'm just a beginner.
Not quite sure if there is any point to post the code, but it's just the basic lines:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
array[i][j]=...(stuck at the beginning);
}
Probably I'd need to use several loops , not only the above-mentioned or probably it is totally wrong ...
Thank you in advance!
I think this should do it.
int counter = 0;
boolean top_to_bottom=true;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
if(top_to_bottom)
array[i][j]=counter;
else
array[rows-1-i][j]=counter;
}
if(top_to_bottom)
top_to_bottom=false;
else top_to_bottom=true;
}
It serves the purpose
import java.util.*;
public class Seq
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
if(j%2==0)
{
for (int i = 0; i < rows; i++)
{
counter=counter+1;
array[i][j]=counter;
}
}
else
{
for (int i = rows-1; i >=0; i--)
{
counter=counter+1;
array[i][j]=counter;
}
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}