Square Array Program - java

Using java, I am supposed to create a program that stores the square of the numbers 0, 1, 2 & 9 in an ArrayList of 10 elements.
I have created part of the code that displays the numbers and its squares but the program goes straight down with all the numbers and does not look organized. Can someone help me write it out like like this instead:
number: 0 square: 0
number: 1 square: 1
number: 2 square: 4
Code
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int value : temp) {
System.out.println(value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(value);
}
}

You need just one loop like this :
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i] + "\t" + (int)Math.pow(temp[i], 2));
}
}
OutPut
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
If you want to store your results in an ArrayList you can use :
List<int[]> array = new ArrayList<>();//create a List which take an array of int
int arr[] = new int[2];//create a temporary array of 2 elements
for (int i = 0; i < temp.length; i++) {
System.out.println("Number: " + temp[i] + " \tSquare: " + (int) Math.pow(temp[i], 2));
arr[0] = temp[i];//add your number to your array pos 1
arr[1] = (int) Math.pow(temp[i], 2);//add the power to the 2ed position
array.add(arr);//add your array to your list
}

public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
// here you are printing all your numbers in the array, so the output will be:
// 0
// 1
// ...
// 9
for (int value : temp) {
System.out.println(value);
}
// after that, you calculate and store them in the same array; so your array now look like this:
// [0,1,4,9,...,81]
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
// here you are printing again your array
// 0
// 1
// 4
// ...
// 81
for (int value : temp) {
System.out.println(value);
}
}
to get your desired outcome, you have to calculate the number before printing everything... one option will be to create another array
int[] square = new int[9];
calculate in the first for loop and save the result in the square array and print them, something like this:
for (int i = 0; i < temp.length; i++) {
square[i] = (int) Math.pow(temp[i],2);
System.out.println("number " + temp[i] + " square: " + square[i]);
}

Assuming the original question which referred to an ArrayList was correct (the OP's example only had an array), and assuming the results are supposed to be stored in the array (per the question), then the following will work:
public static void main(String[] args)
{
// instantiate ArrayList
List<Double> array = new ArrayList<>();
// load the values
for (int i = 0; i < 10; ++i) {
array.add(i, Math.pow(i, 2));
}
// output
for (int i = 0; i < array.size(); ++i) {
System.out.println(String.format("%2d\t%3.0f", i, array.get(i)));
}
}
Output:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81

Try this :
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
for (int value : temp) {
System.out.println("number : "value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(" square : " + value + "\n");
}
}

Related

I need to get all even numbers from random length 2D Array and make another 2D array with even numbers I've got

My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]

How to rotate a String of space delimited integers in Java?

Suppose I have the following String: "10 30 20 12 34". Now I want to rotate the String but keep the first and last integers fixed. So I should get the 3 outputs should be as follows:
10 20 30 12 34
10 30 12 20 34
10 12 20 30 34
Now, I am trying to first convert the String into an int[] array such that it looks like [10, 30,20, 12, 34] and then create another array, get each element of the original array and insert them in the new array.
This is what I have so far:
String[] arr1 = tree.getPreOrder().split(" ");
int[] arr2 = new int[5];
arr2[0] = Integer.parseInt(arr1[0]);
arr2[1] = Integer.parseInt(arr1[3]);
arr2[2] = Integer.parseInt(arr1[2]);
arr2[3] = Integer.parseInt(arr1[1]);
arr2[4] = Integer.parseInt(arr1[4]);
My issue is, how do I now convert arr2 into the format 10 12 20 30 34. I tried to use join() but it doesn't work.
Also, is there a simpler way to do what I'm trying to do as currently, I am hard coding those values.
Thanks
UPDATE
I created a method which basically rotates the middle values now. However, I got into an issue where one randomly generated String was the same as the original and I would like to avoid that. I'm basically trying to generate only exactly 3 variations of the original string if that helps.
Here's my updated code:
static String randomizeAnswer(String ans) {
String[] arr = ans.split(" ");
int arraySize = arr.length;
String firstElement = arr[0];
String lastElement = arr[arraySize - 1];
String[] arr2 = new String[arraySize - 2];
String arr3[] = new String[arraySize];
arr3[0] = firstElement;
for (int i = 0; i < arraySize - 2; i++) {
arr2[i] = arr[i + 1];
}
Collections.shuffle(Arrays.asList(arr2));
for (int j = 0; j < arr2.length; j++) {
arr3[j + 1] = arr2[j];
}
arr3[arraySize - 1] = lastElement;
return String.join(" ", arr3);
}
for int(i = 0; i<3; i++){
System.out.println(randomizeAnswer("10 30 20 12 34"));
}
UPDATE 2
I eventually managed to make a solution which works but the answer by #WJS below is much better.
static String randomizeAnswer(String ans) {
String[] arr = ans.split(" ");
int arraySize = arr.length;
String firstElement = arr[0];
String lastElement = arr[arraySize - 1];
String[] arr2 = new String[arraySize - 2];
String arr3[] = new String[arraySize];
arr3[0] = firstElement;
for (int i = 0; i < arraySize - 2; i++) {
arr2[i] = arr[i + 1];
}
Collections.shuffle(Arrays.asList(arr2));
for (int j = 0; j < arr2.length; j++) {
arr3[j + 1] = arr2[j];
}
arr3[arraySize - 1] = lastElement;
return String.join(" ", arr3);
}
static String[] generateAnswers(String ans) {
String[] answers = new String[5];
answers[0] = ans;
answers[4] = "None of the answers are correct";
for (int x = 0; x < 3; x++) {
while (true) {
String randomAns = randomizeAnswer(ans);
if (Arrays.stream(answers).anyMatch(randomAns::equals)) {
continue;
} else {
answers[x+1] = randomAns;
break;
}
}
}
return answers;
}
Convert the array to ints. Note that the string values could be rotated without parsing to an int.
String str = "10 30 20 12 34";
int[] vals = Arrays.stream(str.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
The range to rotate
int start = 1;
int end = 4; // exclusive
An array to save the rotated array of values.
String[] results = new String[end - start];
And now rotating them, converting to a string and storing. Note that the previously rotated array needs to be fed back into the method. But that array is not changed because it is copied in the rotate method.
for (int i = 0; i < end - start; i++) {
vals = rotate(vals, start, end);
// convert to String - can't use join since these are not strings.
// this just streams the results, converts to a string, and joins them into
// a single string.
results[i] =
Arrays.stream(vals).mapToObj(v -> Integer.toString(v))
.collect(Collectors.joining(" "));
}
for (String rotated : results) {
System.out.println(rotated);
}
prints
10 20 12 30 34
10 12 30 20 34
10 30 20 12 34
This simply rotates the array one cell to the left within the specified range. It first makes a copy of the original array. Note the end is exclusive.
public static int[] rotate(int[] arr, int start, int end) {
arr = Arrays.copyOf(arr, arr.length);
int v = arr[start];
for (int i = start; i < end-1; i++) {
arr[i] = arr[i+1];
}
arr[end-1] = v;
return arr;
}
Another example:
public static void main(String[] args) {
String treePreOrder = "10 30 20 12 34";
String rot1 = rotateMiddle(treePreOrder);
String rot2 = rotateMiddle(rot1);
System.out.println(treePreOrder);
System.out.println(rot1);
System.out.println(rot2);
}
public static String rotateMiddle(String values) {
String[] arr = values.split(" ");
if (arr.length >= 4) {
String temp = arr[1];
for(int i=1; i<=(arr.length-3); i++) {
arr[i] = arr[i+1];
}
arr[arr.length-2] = temp;
}
return String.join(" ", arr);
}
Output:
10 30 20 12 34
10 20 12 30 34
10 12 30 20 34
Here's my two cents using Java Streams.
private static int[] rotate(int[] array, int count) {
if (array.length >= 0 && array.length <= 2) {
return array;
}
return IntStream.range(0, array.length)
.map(i -> (i == 0 || i == array.length - 1) ? i : (i - 1 + count) % (array.length - 2) + 1)
.map(i -> array[i])
.toArray();
}
This rotates the given array count positions to the right, but leaves the first and last indexes unharmed. For example, when count = 1, the array [10, 30, 20, 12, 34] becomes [10, 12, 30, 20, 34].
If you want to generate an n number of random sequences, you could use the snippet below. This generates arrays which are not equal to the original array.
int array = { … };
int n = 2;
ThreadLocalRandom.current().ints(n, 1, array.length - 2)
.mapToObj(randomInt -> rotate(array, randomInt))
.forEach(result -> System.out.println(Arrays.toString(result)));
// Or, if you want to convert it back to a String:
//.collect(Collectors.mapping(String::valueOf, Collectors.joining(" ")));
Collections::shuffle
Of course, you can also simply shuffle the elements minus the first and last ones using Collections::shuffle and List::subList. This method is generic, so it really does not matter whether the elements are actually integers or not. For instance, a List<String> is yielded with Arrays.asList("10 30 20 12 34".split(" ")).
public static <T> List<T> shuffleMid(List<T> list) {
List<T> newList = new ArrayList<>(list);
do {
Collections.shuffle(newList.subList(1, newList.size() - 1));
} while (newList.equals(list)); // Make sure it is unequal to the original
return newList;
}
The do-while loop makes sure the shuffled list is not equal to the original list. This may be a naive implementation.
String[] array = new String[5];
for(int i = 0; i < 5; i++)
array[i] = i + 1 + "";
//array[0] = 1, array[1] = 2, array[3] = 3, array[4] = 4, array[5] = 5
int first = 0;
int last = array.length - 1;
for(int i = 1; i < array.length / 2; i++){
first = i;
last = array.length - i - 1;
String aux = array[first];
array[first] = array[last];
array[last] = aux;
first++;
last--;
}
for(int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
The output will be: 1 4 3 2 5
To rotate the elements (except the first and last elements) you can use this:
use another helping array:
String in = "10 30 20 12 34";
String[] arr_in = in.split(" ");
String[] arr_out = new String[arr_in.length];
arr_out[0] = arr_in[0];
arr_out[arr_out.length-1] = arr_in[arr_in.length-1];
for(int i=arr_in.length-2, j=1; i>0; i--,j++)
{
arr_out[j] = arr_in[i];
}
// print:
for(int i=0; i<arr_out.length;i++)
{
System.out.println(arr_out[i]);
}
in place :
public static void main(String[] args) {
String in = "10 30 20 12 34";
String[] arr = in.split(" ");
String tmp;
for(int i=arr_in.length-2, j=1; i>(arr_in.length/2); i--,j++)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// print:
for(int i=0; i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
There most definitely is a better way to leverage other APIs in the JDK... but here is what I came up with.
// shifts by [direction] spaces (-ve and +ve) for left/right. So far so good with not throwing IndexOutOfBoundsExceptions :)
private static int[] shift(int[] values, int direction) {
int[] result = new int[values.length];
for (int i = 0; i < result.length; i++) {
result[i] = values[(values.length + (i + direction % values.length)) % values.length];
}
return result;
}
public static void main(String[] args) {
int[] values = new int[]{101, 1, 2, 3, 100};
int[] middleValues = Arrays.copyOfRange(values, 1, values.length-1);
int[][] allCombos = new int[middleValues.length][values.length];
int shiftPtr = 0;
for (int[] row : allCombos) {
row[0] = values[0];
row[row.length-1] = values[values.length-1];
int[] shifted = shift(middleValues, shiftPtr);
for (int i = 0; i < middleValues.length; i++) {
row[i + 1] = shifted[i];
}
shiftPtr++;
// and print out to test...
System.out.println(Arrays.toString(row));
}
}
And you end up with this output....
> [101, 1, 2, 3, 100]
> [101, 2, 3, 1, 100]
> [101, 3, 1, 2, 100]

Create a reverse order array from given array

I have an assignment to create a class in which I create an array of size 10, called source, and assign random integers in the range 0-10 to all indexes in it, and then call a method that creates a new array in reverse order. I tried the code below:
public class Exercise7_4 {
// reverse array method
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length - 1; i++) {
reverse[i] = arr[arr.length - 1 - i];
}
return reverse;
}
// print array in ascending order
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
System.out.printf("%d\t", arr[i]);
}
System.out.println();
}
public static void main(String[] args) {
int[] source = new int[10];
for (int i = 0; i < source.length - 1; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
int[] reverse = reverseArray(source);
printArray(source);
printArray(reverse);
}
}
The problem is that the output i get looks like this:
7 1 3 7 10 9 6 2 6
0 6 2 6 9 10 7 3 1
meaning, the reverseArray method doesn't work properly on reverse[0] for some reason.
I would like to know why this is happening and how I can fix it.
Thanks in Advance!
change all your for-loops from
for (int i = 0; i < source.length - 1; i++)
to
for (int i = 0; i < source.length; i++)
Your reverse method is completely correct (if you change the loop). The mistake you made is that you created an array of size 10, filled it with 9 random values (the value of index 10 will therefore be 0).
You could check wich index are consulted in each iteration of your for loop.
This is your solution
for (int i = 0; i < reverse.length - 1; i++) {
System.out.println("" + i + " " + (reverse.length - 1 - i));
}
And it prints:
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
The 'i' don't get the value 9, and the (reverse.length - 1 - i) don't get the value 0.
Changing the testing condition for this:
i < reverse.length
gives you the last position:
9 0
Change reverseArray function as follows:
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length; i++) {
reverse[i] = arr[arr.length - i];
}
return reverse;
}
You need not to -1 from arr.length.
Change another for loop also:
for (int i = 0; i < source.length; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
Here, also you do not need to do -1 from source.length.
package com.test;
public class SortArray {
private int[] getSortedArry(int[] arr){
int arrLen = arr.length;
int reversedArry[] = new int[arrLen];
System.out.println("array lenght: " +arr.length);
int j = 0;
for(int i=arrLen-1; i>=0; i--){
reversedArry[j] = arr[i];
j++;
}
System.out.print("\n");
return reversedArry;
}
public static void main(String[] args){
int arr[] = {10,2,3,4,5,12,23,43,45,65};
SortArray sortArray = new SortArray();
int reversedArry[] = sortArray.getSortedArry(arr);
for(int i=0;i<reversedArry.length;i++){
System.out.print(reversedArry[i] + " ");
}
}
}

working with array and summing the elements

I have to solve the following problem: Given an array of integers and given an integer value, list all possible numbers form the array that sums up to the given value.
Example:
Input: array = {1, 2, 2, 3, 4, 5}, int N = 5
Output: {1, 2, 2}, {1, 4}, {5} {2, 3}.
here is my code till now, can anybody help me?
import java.util.Scanner;
public class sumarray {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int[] array = new int[3];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] + array[j] == 5) {
System.out.println("{" + array[i] + "," + array[j] + "}");
}
}
}
}
}
This is a common Dynamic Programming problem called Subset Sum.
You can do this like so if you only want to print (note that you have {2, 3} twice because there are two 2s):
public class Main {
public static void main(String[] args){
int[] arr = {1, 2, 2, 3, 4, 5};
subsetSum(arr, 5);
}
private static void subsetSum(int[] arr, int sum) {
subsetSum(arr, 0, sum, "");
}
private static String lineSep = System.getProperty("line.separator");
private static void subsetSum(int[] arr, int i, int sum, String aggregated) {
if (sum == 0){
System.out.println("Success with:" + aggregated);
System.out.println("And done.");
System.out.println();
return;
}
if (arr.length <= i){
// failed (uncomment following lines to see why)
// System.out.println("Failed with:" + aggregated);
// System.out.println();
return;
}
int current = arr[i];
subsetSum(arr, i+1, sum, aggregated + lineSep + "not " + current);
subsetSum(arr, i+1, sum - current, aggregated + lineSep + current);
return;
}
}
This uses the fact that String is immutable (so a new string is created for every frame), and does forward aggregation of selected numbers. I've added some text to make it descriptive so you see what's going on.
Output:
not 1
not 2
not 2
not 3
not 4
5
And done.
not 1
not 2
2
3
And done.
not 1
2
not 2
3
And done.
1
not 2
not 2
not 3
4
And done.
1
2
2
And done.
This is problem called Subset Sum.
and this my code and i know not professional but it is solution for this specific problem
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] array = new int[6];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
int N=5; //N= the given value
int a1=0; // for use to sure not duplicate answer in this case is {2,3}
int a2=0; // for use to sure not duplicate answer
// and we put in a1 and a2 numbers if we add together dose not equal N which is here equal(5)
for (int i = 0; i < array.length; i++) {
if (array[i]==N)
System.out.println("{" + array[i] +"}");
for (int j = i+1; j < array.length; j++) {
for (int f = j+1; f < array.length; f++){
if(array[j]+array[i] == 5 ){
if(a1!=array[i] && a2!=array[j]){ // make sure dose not same number that is done.
System.out.println("{" + array[i] + ","+ array[j] + "}");
a1=array[i];
a2=array[j];}}
else if(array[i] + array[j]+array[f] == 5){
System.out.println("{" + array[i] + "," + array[j] + ","+ array[f] + "}");}
}}}}
the output is :
{1,2,2} {1,4} {2,3} {5}
i hope this help you :)

I have matrix and I need to sum up all of the values around a specified row & column, including the provided position. Then output the average

I have a program to sum up all the values around the specified place but I can not determine how to determine and output the average of those values.
Matrix to be used
1 2 3 4 5
15 7 8 9 71
6 7 11 2 5
6 7 8 9 14
5 4 3 2 33
Data file
3
2 2
0 0
4 3
Class
class Average
{
public static void main (String[] args) throws IOException
{
Scanner f = new Scanner( new File( "pr20.dat" ) );
int times = f.nextInt();
f.nextLine();
for(int x=0;x<times;x++)
{
int [][] matrix ={ {1,2,3,4,5},
{15,7,8,9,71},
{6,7,11,2,5},
{6,7,8,9,14},
{5,4,3,2,33} };
int r = f.nextInt();
int c = f.nextInt();
int sum = 0;
if(r-1<0&&c-1<0)//top left corner WORKS
{
for(int rows=r;rows<r+2;rows++)
for(int col=c;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(r+2>5&&c+2>5)//bottom right corner WORKS
{
for(int rows=r-1;rows<=r;rows++)
for(int col=c-1;col<=c;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(r+2>5&&c-1<0)//bottom left corner WORKS
{
for(int rows=r-1;rows<=r;rows++)
for(int col=c;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(r+2>5)//along the bottom WORKS
{
for(int rows=r-1;rows<=r;rows++)
for(int col=c-1;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(c-1<0)//along the left WORKS
{
for(int rows=r-1;rows<r+2;rows++)
for(int col=c;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(c+2>5&&r-1<0)//top right corner WORKS
{
for(int rows=r;rows<r+2;rows++)
for(int col=c-1;col<=c;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(r-1<0)//along the top WORKS
{
for(int rows=r;rows<r+2;rows++)
for(int col=c-1;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else if(c+2>5)//along the right WORKS
{
for(int rows=r-1;rows<r+2;rows++)
for(int col=c-1;col<=c;col++)
sum+=matrix[rows][col];
out.println(sum);
}
else //no boundaries WORKS
{
for(int rows=r-1;rows<r+2;rows++)
for(int col=c-1;col<c+2;col++)
sum+=matrix[rows][col];
out.println(sum);
}
out.println();
}
}
}
If you're looking for the mean:
Sum them up and divide by the number of elements you summed up.
As #MrUsefull said you need to sum and divide to get the average but your code may be much simpler not differentiating cases but restricting boundaries:
class Average {
private static PrintStream out = System.out;
public static void main(String[] args) throws IOException {
/* Constant definitions */
final int absMinRow = 0;
final int absMinCol = 0;
final int absMaxRow = 4;
final int absMaxCol = 4;
final int[][] matrix = {
{ 1, 2, 3, 4, 5 },
{ 15, 7, 8, 9, 71 },
{ 6, 7, 11, 2, 5 },
{ 6, 7, 8, 9, 14 },
{ 5, 4, 3, 2, 33 } };
try (Scanner f = new Scanner(new File("pr20.dat"))) {
int times = f.nextInt();
f.nextLine();
for (int x = 0; x < times; x++) {
/* Next input data */
int r = f.nextInt();
int c = f.nextInt();
/* variable boundaries */
int minRow = Math.max(r - 1, absMinRow);
int maxRow = Math.min(r + 1, absMaxRow);
int minCol = Math.max(c - 1, absMinCol);
int maxCol = Math.min(c + 1, absMaxCol);
int sum = 0;
int count = 0; // <--!!!!
for (int i = minRow; i <= maxRow; i++) {
for (int j = minCol; j <= maxCol; j++) {
sum += matrix[i][j];
count++; // <--!!!!
}
}
out.println(sum);
out.println(count);
out.println(sum / count); // <-- Average!!!!
out.println();
}
}
}
}
You obviously have to store and not only to print out the sums to calculate an average value over all of them.

Categories