I have to add the votes per state of the 2008 elections on a 2 dimensional array, but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:
State Obama McCain Other Total by state
Alabama 813479 1266546 19794 2099819 2426016 72985 etc...
Alaska 123594 193841 8762 2099819 2426016 72985 etc...
But i needed to add the total votes on each state only once per row.
public static void main(String[] args) throws IOException
{
// TODO code application logic here
File election = new File("voting_2008.txt");
Scanner sc = new Scanner(election);
String[] states = new String[51];
int[][]votes = new int[51][4];
int[] Totalbystate = new int[votes.length];
for (int s=0; s < 51; s++)
{
states[s] = sc.nextLine();
}
for(int c=0; c < 3; c++)
{
for(int s=0; s < 51; s++)
{
votes[s][c] = sc.nextInt();
}
}
Formatter fmt = new Formatter();
fmt.format("%20s%12s%12s%12s%21s", "State", "Obama", "McCain", "Other", "Total by state");
System.out.println(fmt);
for (int s=0; s < 51; s++)
{
fmt = new Formatter();
fmt.format("%20s", states[s]);
System.out.print(fmt);
for(int c=0; c < 3; c++)
{
fmt = new Formatter();
fmt.format("%12d", votes[s][c]);
System.out.print(fmt);
}
int sum =0;
for(int row=0; row < votes.length; row++)
{
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
}
System.out.println();
}
}
but when I run the code it sums only the first row and then keeps adding itself to the previous sum 51 times to the right side like this:
Look at your code:
int sum =0;
for(int row=0; row < votes.length; row++)
{
for (int col=0; col < votes[row].length; col++)
{
sum = sum + votes[row][col];
}
fmt = new Formatter();
fmt.format("%21d", sum);
System.out.print(fmt);
}
Look at where you're setting sum to 0. Now think about where you should be setting it to 0...
Related
I'm trying to sum of rows of Matrix
When I just put elements in 2D array output is right but when I'm trying using Scanner output result is different
SAMPLE INPUT
2
1 2
3 4
Output:
3
7
Below code result correct
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int a[][] = {
{1, 2,},
{ 3, 4}
};
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
Result incorrect if I'm trying with Scanner
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int column = sc.nextInt();
int [][] a = new int[row][column];
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
With the sample input you've provided, you shouldn't be reading the number of rows and columns, but just a single int for the number of both rows and columns:
int size = sc.nextInt();
int [][] a = new int[size][size];
for (int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
a[i][j] = sc.nextInt();
}
}
I do not see any logical problem with your code. However, it is equally important to keep your code clean and user friendly. I recommend you address the following points if you are serious about programming:
The following declaration is unnecessary:
rows = a.length;
cols = a[0].length;
You can simply use row and column instead of creating rows and cols for the same thing.
You should remove all such unnecessary things which create noise in your code.
You have missed printing the sum of each column i.e.
System.out.println(sumCol);
You do not need to declare throws IOException with main for this code.
You should always display a message describing the input; otherwise, the user remains clueless about what he/she is supposed to input.
Given below is the code incorporating these comments:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int row = sc.nextInt();
System.out.print("Enter the number of columns: ");
int column = sc.nextInt();
int[][] a = new int[row][column];
for (int i = 0; i < row; i++) {
System.out.println("Enter " + column + " integers: ");
for (int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int sumRow, sumCol;
// Calculates sum of each row of given matrix
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < column; j++) {
sumRow = sumRow + a[i][j];
}
System.out.println("Sum of row " + i + ": " + sumRow);
}
// Calculates sum of each column of given matrix
for (int i = 0; i < column; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + a[j][i];
}
System.out.println("Sum of column " + i + ": " + sumCol);
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 4
Enter 4 integers:
1 9 2 8
Enter 4 integers:
2 8 3 7
Enter 4 integers:
3 7 4 6
Sum of row 0: 20
Sum of row 1: 20
Sum of row 2: 20
Sum of column 0: 6
Sum of column 1: 24
Sum of column 2: 9
Sum of column 3: 21
I want to create an multidimensional array that will count.
This is the code I have so far and don't know where to go from here. When I print this out I want it to look like 0,1,2,3,4,5,6,7,8,9,10,etc.
public static void main(String[] args) {
int car[][] = new int[4][4];
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
you're creating empty array so every field has value 0
try this:
public static void main(String[] args) {
int car[][] = new int[4][4];
int index = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = index++;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
You need to set the values before printing them
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = row * 4 + col;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
But it's silly and pointless to use a multi-dimensional array like this.In my experience, Multi-dimensional arrays are useful in a much more limited scope than how people play with them when they are learning.
Use this:
public static void main(String[] agrs) {
int car[][] = new int[4][4];
int i = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = i++;
System.out.print(car[row][col] + ",");
}
}
}
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length + amount; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount < original.length) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
Hi,
I am trying to write a method that will shift the elements in my 2-D array to the left by some arbitrary amount. I don't want to loop the values back around, but instead fill the empty arrays with some fill_value which is already predefined. And if the shift amount is more than the orignial length, I would just return an image with only fill_value. However, this function is throwing an arrayindexoutofbound Error. But I can't think of how I should change my for loop to fix the error. Any help is appreciated! Thank you!
I believe it's because in your second outer for loop, the condition is cols < length + amount, so it will continue past the edge of the array if amount > 0. You could step through your code with a debugger and see exactly where it's going out of bounds.
The error is occurring because of following line:
shifted[cols][rows] = original[cols - amount][rows];
When cols=0, rows=0, amount=2 (say), it is trying to access original[-2][0] which does not exist.
Instead you may use following:
public class overflow1 {
static int a[][] = {{1,2,3,4,5,6},{2,3,4,5,6,7},{3,4,5,6,7,8}, {4,5,6,7,8,9}, {5,6,7,8,9,10}, {6,7,8,9,10,11}};
static int b[][] ;
static int FILL_VALUE =0;
public static int[][] shift(final int[][] original, final int amount) {
int[][] shifted = new int[original.length][original[0].length];
for (int col = 0; col < original.length; col++) {
for (int row = 0; row < original[col].length; row++) {
shifted[col][row] = FILL_VALUE;
}
for (int cols = 0; cols < original.length ; cols++) {
for (int rows = 0; rows < original[cols].length; rows++) {
if (cols - amount >=0) {
shifted[cols][rows] = original[cols - amount][rows];
}
}
}
}
return shifted;
}
public static void main(String[] arggs) {
b=shift(a,2);
System.out.println("Original array:");
for(int i=0; i<a.length; i++){
for (int j=0; j<a[i].length; j++){
System.out.print(a[i][j]+ ":");
}
System.out.println();
}
System.out.println("After shift by 2 array:");
for(int i=0; i<b.length; i++){
for (int j=0; j<b[i].length; j++){
System.out.print(b[i][j]+ ":");
}
System.out.println();
}
}
}
Here is the output for the sample:
Original array:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
5:6:7:8:9:10:
6:7:8:9:10:11:
After shift by 2, array:
0:0:0:0:0:0:
0:0:0:0:0:0:
1:2:3:4:5:6:
2:3:4:5:6:7:
3:4:5:6:7:8:
4:5:6:7:8:9:
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];
I'm looking for a way to add up the elements of the rows of an array and get that sum. I have to get the column's sum as well.
The array looks something like this:
{{45.24, 54.67, 32.55, 25.61},
{65.29, 49.75, 32.08, 26.11},
{25.24, 54.33, 34.55, 28.16}};
For example, I would add 45.24, 65.29, and 25.24 to get the sum of that part of the columns. I would then have to add the other 3 columns up as well.
Same goes for the rows.
I keep getting errors concerning the variable types. Is there a way to do this? Thanks.
The logic Would be --->
for(i = 0; i < columns; i++)
{
for(j=0; j<rows; j++)
{
sum+=arr[j][i];
}
}
Opposite for Columns
I think you should define the type of numbers your array will handle, if I use float numbers I can have some code like the class bellow to do the type of operations you are asked for. You can also add some decimal formatting.
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
float myarray[][]= {
{45.24f, 54.67f, 32.55f, 25.61f},
{65.29f, 49.75f, 32.08f, 26.11f},
{25.24f, 54.33f, 34.55f, 28.16f}
};
float row[] = new float[3];
float column[] = new float[4];
for (int i=0; i < 3; i++) {
float rowvalue = 0f;
for (int j=0; j < 4; j++) {
System.out.print(myarray[i][j]+" ");
rowvalue+=myarray[i][j];
}
row[i]=rowvalue;
System.out.println("");
}
System.out.println("");
for (int i=0; i < 4; i++) {
float colvalue = 0f;
for (int j=0; j < 3; j++) {
System.out.print(myarray[j][i]+" ");
colvalue+=myarray[j][i];
}
column[i]=colvalue;
System.out.println("");
}
System.out.println("Rows answer:");
for (int i=0; i < 3; i++) {
System.out.println(row[i]);
}
System.out.println("Columns answer:");
for (int i=0; i < 4; i++) {
System.out.println(column[i]);
}
}
}
Suppose you have nxn matrix. The idea is to identify the pattern.
Row values
i j
0 0
0 1
0 2
Column values
i j
0 0
1 0
2 0
The position of i and j values is reversed.
Let's assume we have an array a[][]. The logic would be:
for (int i=0; i<n; i++) {
int row = 0, col = 0;
for (int j=0; j<n; j++) {
row += a[i][j];
col += a[j][i];
}
System.out.println("row" + i + " = " + row);
System.out.println("col" + i + " = " + col);
}
I assumed you wanted the sum of each row and column separately. You can modify it accordingly.