Sum of the two dimentional array in Java - java

This is a homework question and im still a newbie to java.
Write a code segment that computes the sum of all the values in marks.
This is my answer and it has compilation errors. Please help
class myArray{
public static void main(String args []){
int [] [] marks = {{1,2,3,4,5}, {6,7,8,9}, {10,11,12}};
for(int i = 0; i<marks.length; i++){
int sum = 0;
for(int j = 0; j <marks[i].length; j++) {
sum = sum + makrs[j][i];
}
}
System.out.println(sum);
}
}

There are two syntactical errors and one type.
Move int sum =0; above for loop as you need it outside the loop to print the value
Correct marks reading index from marks[j][i] to marks[i][j]
Correct the typo in the same line as above (sum = sum + makrs[j][i];). You have typed makrs in place of marks
int [] [] marks = {{1,2,3,4,5}, {6,7,8,9}, {10,11,12}};
int sum = 0;
for(int i = 0; i<marks.length; i++){
for(int j = 0; j <marks[i].length; j++){
sum = sum + marks[i][j];
}
}
System.out.println(sum);

Related

Modifying a static method to add two counters when comparing arrays using for loops in Java

Using this segment of code I already have, I want to modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time two data items are actually swapped, increment the data swap counter.
So far this is what I have tried to add the counters. However, I receive an error "Unresolved compilation problem: counter cannot be resolved to a variable".
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
int counter = 0;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
counter += 1;
}
System.out.println("The size of the sorted array is " + list.length + " and the count is " + counter);
}
I have the main method prepared below.
public static void main(String[] args) {
final int NUM_ELEMENTS = 10;
double[] lo2Hi = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
lo2Hi[i] = i + 1;
}
selectionSort(lo2Hi);
double[] hi2Lo = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
hi2Lo[i] = 10 - i;
}
selectionSort(hi2Lo);
double[] random = new double[NUM_ELEMENTS];
for (int i = 0; i < random.length; i++) {
random[i] = Math.random();
}
selectionSort(random);
}
Your println() at the end of selectionSort() is trying to acces the variable counter, but counter is "out of scope" at that point. Variables only exist within the pair of {}'s they were declared inside (that's what "scope" is).
Move the int counter = 0; statement out of the for loop, and put it at top of the method. Then it will be in-scope for the print statement.

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

Locate the largest element in a multidimensional arrays

I have to write a program using a method that returns the location of the largest element in a two dimensional array.
example
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
I have finished my code but it isn't working. How can I fix it? All I got are the following errors:
symbol : variable maxvalue
location: class int[]
if (a[i][j] > largest.maxvalue)
^
homework1a.java:51: row is already defined in locateLargest(double[][])
double row = i;
^
homework1a.java:52: column is already defined in locateLargest(double[][])
double column = j;
^
homework1a.java:53: maxValue is already defined in locateLargest(double[][])
double maxValue = a[i][j];
^
homework1a.java:88: i is already defined in main(java.lang.String[])
for (int i = 0; i < 2; i++)
^
5 errors
My code
import java.util.Scanner;
public class hwm1 {
public static int[] locateLargest(double[][] a)
{
int[] largest = new int[2];
double row = 0;
double column = 0;
double maxValue = a[0][0];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)
{
double row = i;
double column = j;
double maxValue = a[i][j];
}
}
}
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
int[] largest = locateLargest(a);
System.out.println("The location of the largest element is at "+ "("+largest[0] +", " + largest[1] + ")");
for (int i = 0; i < 2; i++)
{
System.out.print(largest[i]);
}
}
}
}
You are declaring the variables row, column and maxValue twice.
Also, in the line:
if (a[i][j] > largest.maxvalue)
There is no such thing as maxvalue in your code, and neither is it a member of largest
In this part of your code:
Since i is already declared in the outer for-loop, you don't need to declare it again. Just use:
...
for(i = 0; i < 2; i++){
...
}
homework1a.java:51:, homework1a.java:52:, homework1a.java:53:
For these three, remove 'double'. If you state the type when referencing the variable, Java will assume you are trying to define the variable in question. Here you already have those three defined. Additionally, since you don't use row or column at all, I suggest that you simply remove them.
homework1a.java:88: i is already defined in main(java.lang.String[])
For this one, you have a nested for loop, but it uses i as well. You should use k for the second of the nested for loops (the one after the one using j).
. You don't need to post full code below code snippet is sufficient
double row = 0; //declaring first time
double column = 0;//declaring first time
double maxValue = a[0][0];//declaring first time
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a.length; j++)
{
if (a[i][j] > largest.maxvalue)// there is no variable maxvalue in Array class in java
{
double row = i; // declaring again
double column = j;// declaring again
double maxValue = a[i][j];// declaring again
}
}
}
return largest;
Issues:
Loop on j should be using a[i].length
the lines in if block is re-declaring the variables, remove the keyword 'double '
You are not declaring setting largest anywhere so you have a logic issue
Using a largest.maxValue is logically incorrect as it should contain the row and column number and not the actual max value
I would solve this by re-writing the code as follows which I believe is the most efficient way of achieving the goal:
public static int[] locateLargest(double[][] a)
{
int maxRow=-1,maxCol=-1;
double maxVal=-1;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if (a[i][j] > maxVal)
{
maxRow = i;
maxCol = j;
maxVal = a[i][j];
}
}
}
return new int[]{maxRow,maxCol};
}
Good luck!

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Printing pyramid in Java on the console

How can I print a pyramid in Java like this
1
23
456
78910
My current code looks like this:
public class T {
public static void main(String[] args) {
int i, j, num = 1;
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.println(num);
num++;
}
System.out.println(" ");
}
}
}
If I try this removing declared i & j then it shows an array out of bounds exception
However 'i' & 'j' are creating the problem. What should my code look like.
int val=1;
for(int i=0;i<6;i++){
for(int j=1;j<i;j++){
System.out.print(val);
val++;
}
System.out.print("\n");
}
initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn't run. then you get the first value as 1. Then it will point to new line.
When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.
so on this will work
public static void main(String[] args) {
int num = 1;
//i is how many numbers per row
for(int i = 1; i < 5; i++){
//prints i numbers because j increases from 0 to i, incrementing num each time
for(int j = 0; j < i; j++){
System.out.print(num++);
}
System.out.println();
}
}
This code will work for your purposes.
Now, please read on if you would like to understand Java better and see why the compiler was throwing errors in your code. You shouldn't use stackoverflow to copy in paste someone else's code without understanding it. In your code, you were declaringi and j twice. In Java, you cannot declare a variable twice. You did it first in int i,j, num = 1; and then again in each for loop for (int i = 1; i <= lines; i++). You could correct this by saying for(i = 1; i <= lines; i++). Notice how the int is left out in the second version of the for loop. You can simply assign a value to a variable in a for loop rather than creating a new variable as you do when declare the type int i = 1
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
As for the array out of bounds error that you receive, you are trying to read in a command line argument in the statement int n = Integer.parseInt(args[0]); Notice how the main method has a parameter String[] args. These are called command line arguments and can be passed in if you manually run the program from the command line. You were trying to read in args[0] which is outside of the bounds of args[].
In other words, if you run
java MyProgram one two
Then args contains:
[ "one", "two" ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
I suppose you give the number of lines as your only argument, so the code would be
public static void main(String[] args)
{
int lines = Integer.parseInt(args[0]);
int num = 1;
for (int i = 1; i <= lines; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num);
num++;
}
System.out.println("");
}
}
int l=1;
for (int i=0; i<5; i++)
{
for (int k=0; k<5-i; k++)
{
System.out.print(" ");
}
for (int j=0; j<(i*2)+1; j++)
{
if(j%2!=0){
System.out.print(l++);
}else {
System.out.print(" ");
}
}
System.out.println("");
}
public static void pyramid(int max) {
int num = 1;
max = 4;
for (int row = 0; row < max; row++) {
for (int column = 0; column < max; column++)
System.out.print(column <= row ? num++ : " ");
System.out.println();
}
}
import java.util.Scanner;
/**
*
* #author shelc
*/
public class PrintNumberPyramid {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the count : ");
int number = scanner.nextInt();
//enter the number of rows you want to print
pyramid(number);
}
public static void pyramid(int rows) {
int count = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(j <= i ? count++ : " ");
}
System.out.println();
}
}
}

Categories

Resources