Except for an extra column produced by the code, everything works fine except my avg method which was meant to average the value in each row. I'm new to coding, so maybe I'm not seeing the problem, but the method isn't working as intended. At first I thought it was an issue with the sum but changing it didn't really resolve the initial problem. A column input of (2,1,3) will produce an exception error at 1 but does not occur when the input is (1,3,2). Also the avg is producing only 2 regardless of column length.
I'm aiming for the code to print this when column input of (1,2,3) is entered:
A:2.0 [1.0]
B:2.0 2.0 [2.0]
C:2.0 2.0 2.0 [3.0]
where the bracketed term is the average for that row.
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
// 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 + 1][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) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
public static double avg(double temp[][]) {
int sum = 0;
int avg = 0;
for (int row = 0; row < temp.length; row++){
for (int col = 0; col < temp[col].length; col++)
sum += temp[row][col];
}
avg = sum / temp.length;
return avg;
}
}
I think what you are doing wrong is instead of summing up all elements of a row and taking average, you are summing up the whole matrix and taking average which will always be the same value.
Related
In this program, I have to fill a 2D array with user-inputted values and find the average of all the array's elements. However, the program instead finds the average by dividing the sum by the number of rows instead of the number of numbers. I tried setting average to a 2D array in itself but it only recognized one reference instead of both of them. Halp
public static void main(String[] args) {
int[][] array = createArray();
System.out.printf("The average of this array is " + "%.2f", average(array));
}
public static int[][] createArray() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = sc.nextInt();
System.out.print("Enter the number of columns: ");
int numColumns = sc.nextInt();
int[][] array = new int[numRows][numColumns];
System.out.println("Enter " + array.length + " rows and " + array[0].length + " columns");
for (int row = 0; row < array.length; row++)
for (int column = 0; column < array[0].length; column++)
array[row][column] = sc.nextInt();
return array;
}
public static double average(int[][] a) {
int sum = 0;
double average = 0;
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
average = sum / a.length;
}
return average;
}
}
The problem is here:
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
average = sum / a.length;
}
The issue is that you are re-assigning average on every iteration through the loop. Instead, you should calculate it after all of the loops are done:
for (int row = 0; row < a.length; row++) {
for (int column = 0; column < a[row].length; column++) {
sum += a[row][column];
}
}
average = (double) sum / (a.length * a[0].length);
The product (a.length * a[0].length) will give you the size of all of the arrays in the array. You add the cast to (double) in the calculation of the average to avoid integer arithmetic problems (e.g., 25/6 is 4).
Note that if the arrays are large enough, it is possible for sum to overflow.
import java.util.*;
public class triangle{
public static void main(String args[]){
Scanner input_Obj = new Scanner(System.in);
System.out.println("Enter the number of lines in the triangle");
int sum = 0;
int mat_size = input_Obj.nextInt(); //input of the size of the triangle
System.out.println("enter the inputs");
int input_Array[][] = new int[mat_size][mat_size];
for (int row = 0; row < mat_size; row++){
for (int col = 0; col < col; col++){
input_Array[row][col] = input_Obj.nextInt();
}
}
if (mat_size >= 3){
int[] sum_array = new int[2*(mat_size-2)];
for (int row = 1; row < mat_size; row++){
for(int col = 0;col<=row;col++){
sum += input_Array[row][col];
}
sum_array[row-1] = sum;
}
}
else if(mat_size == 2){
if (input_Array[1][0]<input_Array[1][1]){
System.out.println("minimum of the two elements in second line is:" +input_Array[1][0]);
}
else{
System.out.println("minimum of the two elements in second line is:" +input_Array[1][1]);
}
}
else{
System.out.println("minimum sum can't be calculated");
}
}
}
It is not storing values in the input array
It is taking the input in mat_size but not taking inputs into the array
I'm trying to find the minimum sum inside the triangle
for (int col = 0; col < col; col++)
col < col this is the issue as condition is never satisfied that is why it is not taking any input, change this condition to
for (int col = 0; col < mat_size; col++)
I want to write code which will add only diagonal elements.
import java.util.Scanner;
public class SabMat {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double [][] matrix = new double [4][4];
System.out.print("Enter matrix elements by row");
for (int i=0; i < matrix.length; i++) {
matrix[i][0] = input.nextDouble();
matrix[i][1] = input.nextDouble();
matrix[i][2] = input.nextDouble();
matrix[i][3] = input.nextDouble();
}
int total=0;
for (int row=0; row < matrix.length; row++) {
for (int column=0; column < matrix[row].length; column++) {
if (row == column){
total += total + matrix[row][column];
} else if (row!=column){
total = 0;
}
}
}
System.out.println("The sum of elements in the major diagonal is"+total);
}
}
The result is not good!
The problem is only (3,3) element is added to total not the previous three.
How to solve this?
Your code does not work because it resets the total every time you're off the main diagonal.
Note that you do not need two loops if all you want is to total the elements of the diagonal: rather than running two nested loops and waiting for row == column, run a single loop, and total up the values of matrix[i][i].
for (int i = 0 ; i != matrix.length ; i++) {
total += matrix[i][i];
}
I have a problem figuring out how to pad the strings printed from my array values. I thought I had a good way to do it, but it doesn't read x.length correctly so I'm curious to alternative methods or even an explanation to the bug.
import java.util.Scanner;
//================================================================
public class Array {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice ;
String str = " ";
double sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
double average = 0;
int S;
int diff = 0;
int totalChar=0;
int minLen = 20;
String x= "";
// creating 2d array
System.out.print("Please enter number of rows : ");
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();
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] = 0.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;
x = " "+figures[row][col];
diff = minLen - x.length();
System.out.printf("%1$" + diff + "s", x);
System.out.print(" ");
}
System.out.print("["+average+"]");
System.out.println();
}
}
}
I want to produce a table that looks like this:
A: 0.0 0.0 0.0 - [ 0.0, 0.0]
B: 0.0 0.0 0.0 0.0 - [ 0.0, 0.0]
C: 0.0 0.0 0.0 0.0 0.0 - [ 0.0, 0.0]
Where the - is where I want to fill with space until an arbitrary length. In other words I want my print array section to be able to print each line and add spaces up to a point. Is it possible to make a method for that? I'm not to familiar with all the java methods yet so any help is appreciated.
If this is a repeated question, I would appreciate a redirection to the original and I'll try to delete this one. Also sorry for the inconvenience in that case.
I am assuming you know how to build the string on the left and on the right, using StringBuilder or String concatenation.
Once you have your strings built, you can use printf as below to pad the output on the right to as many whitespace characters as you desire. In the sample code below, I have used 20 as the number of characters to pad to.
public class Pad {
public static void main(String[] args) {
String a = "0.0 0.0 0.0 ";
String b = "0.0 0.0 0.0 0.0";
String c = "[ 0.0, 0.0]";
System.out.printf("%-20s %s\n", a, c);
System.out.printf("%-20s %s\n", b, c);
}
}
You can use this idea in your code above by replacing your last loop with:
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing data row
StringBuilder sb = new StringBuilder();
group = (char)((row)+(int)'A');
sb.append(group+" : ");
for(int col=0; col<figures[row].length; ++col) {
sum += figures[row][col];
average = sum/figures[row].length;
x = " "+figures[row][col];
diff = minLen - x.length();
sb.append(String.format("%1$" + diff + "s", x));
sb.append(" ");
}
System.out.printf("%-75s[%f]\n", sb.toString(), average);
}
You need find the maximum number of column size and iterate in each row upto max column, and place the value if the length is less than actual row length and else blank spaces.
It will solve the issue.
I have added the changed code :
public class Array {
// String result = String.format("The format method is %s!", "great");
// System.out.println(result);
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter, letter;
String choice;
String str = " ";
double sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
double average = 0;
int S;
int diff = 0;
int totalChar = 0;
int minLen = 20;
String x = "";
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
double[][] figures = new double[rows][num];
int maxSize = 0;
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();
if (columns > maxSize) {
maxSize = columns;
}
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] = 0.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 < maxSize; ++col) {
if (col < figures[row].length) {
sum += figures[row][col];
average = sum / figures[row].length;
x = " " + figures[row][col];
diff = minLen - x.length();
System.out.printf("%1$" + diff + "s", x);
System.out.print(" ");
} else {
System.out.print(" ");
}
}
System.out.print("[" + average + "]");
System.out.println();
}
}
}
While working on a code for making a irregular 2D-array, I discovered a weird error while messing with different inputted values for the column. While the row works, the column length input returns either the wrong amount or a null pointer error occurs. I'm not sure what might be causing this since inputs such as ( 1 , 2 , 3) returns the correct table but (2 , 1, 3) will not. Also in a row of 4 with column inputs of (2, 3, 4, 5) returns "index out of bounds exception: 5" when there shouldn't be able to be out of bounds because of the while loop that should keep it with in reasonable range. Neither the main nor the display method seems to be saving the intended column length correctly and I can't seem to spot why.
It seems the array is set to 3 rows with column length of 1 , 2 , 3.
The output for row(3) and column(2,3,1) gives:
A:2.0
B:2.0 2.0
C:2.0 2.0 2.0
when I want is:
A:2.0 2.0
B:2.0 2.0 2.0
C:2.0
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
//greetings
System.out.println("");
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
// 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 + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+(int)'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();
}
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
}
// 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 = 1; row < figures.length; ++row) {
// printing data row
group = (char)((row-1)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
//----------MENU
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");
choice = Keyboard.next();
letter = choice.charAt(0);
letter = Character.toUpperCase(letter);
if(letter == 'P') {
display(figures);
}
}
public static void display(double x[][]) {
int average, total;
char group;
System.out.println(" ");
for(int row=1;row<x.length;row++) {
group = (char)((row-1)+(int)'A');
System.out.print(group+" : ");
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+" ");
}
System.out.print("["+","+avg(x)+"]");
System.out.println();
}
}
public static int avg(double[][] temp) {
int sum = 0;
int avg = 0;
for (int col = 0; col < temp[0].length; col++) {
sum = 0;
for (int row = 0; row < temp.length; row++)
sum += temp[row][col];
System.out.println(sum);
}
avg = sum / temp.length;
return avg;
}
}
In Creating 2D Array,
Change this
double[][] figures = new double[rows + 1][num];
to
double[][] figures = new double[rows][num];
and
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
to
figures[t] = new double[columns] ;
In Printing Array
Change this
for(int row = 1; row < figures.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < figures.length; ++row) {
group = (char)((row)+(int)'A');
In display function
Change this
for(int row = 1; row < x.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < x.length; ++row) {
group = (char)((row)+(int)'A');
It's this
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
I think you meant actually
figures[t] = new double[columns];