How to set the initial value of a multidimensional array in java - java

2DI need to use a two-dimensional array of doubles to store grades. The first dimension of the array will represents each student while the second dimension represents the grade for each assignment. The maximum number of assignments for any course is provided when the course is created. I need to make it so that grades that have not been assigned are given an initial value of -1
I know that for single arrays you can do this
double[] grade = new double[10];
for (double i = 0; i < size; i++) {
array[i] = -1;
}
How would I do it for a 2D array?

try this
double[][] grade = new double[10][10];
for (double[] e : grade) {
Arrays.fill(e, -1);
}

First all, you can't do this
double[] grade = new int[10];
double[] and int[] are incompatible types.
To declare a 2D array just use two sets of square brackets
double[][] grade = new double[10][10];
This will give you a total of 100 indices, max index being [9][9], and min[0][0].
To iterate through the array you use a nested loop
for (int i = 0; i < grade.length; i++){ // iterates each student
for (int j = 0; j < grade[i].length; j++){ // iterates each grade
// do something with grade[i][j]
}
}

Related

How can you show how positions have changed after selection sort?

I coded a selection sort program and I was wondering if I wanted to add-on to it by showing how the positions of the values have changed, if it would be possible?
this is my selection sort code
import java.util.Scanner;
public class SelectionSort {
public static void main(String args[]) {
// int[] arr = {5,4,3,2,1}; // This is my array
int min = 0;
Scanner sc = new Scanner(System.in);
System.out.println("No of elements : ");
int noOfElements = sc.nextInt();
int[] arr = new int[noOfElements];
System.out.println("Give elements : ");
for (int i = 0; i < noOfElements; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < arr.length; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elemenst : " + arr[i]);
}
}
}
If you are trying to get array after each iteration, then you should print at the end of each iteration using Arrays#toString() to print complete array
for (int i = 0; i < arr.length; i++) {
...
.....
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elements : " + Arrays.toString(arr));
}
I don't know if your 'task' is to write your own sort method, but if you are looking for sorting an array you should use this:
public static void main(String[] args) {
int[] arr = {5,4,3,2,1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
Never assume what a User might enter and therefore never assume that the first entry will be the minimum value.
This question has been showing up a lot in StackOverflow and therefore I can only assume this is homework. With this in mind I'm sure the assignment intent is to accept a specific number of random integer values from the User, place those values into a Integer Array, then sort that array in ascending order. While the sorting process is taking place show (display in console) what steps are taking place (which values are swapped within the array).
Here's a tip, research the Bubble Sort and the little bit of code it takes to accomplish the sorting task of Integer numbers within a Integer Array. In general a Bubble Sort utilizes two for loops to carry out a sort. It is within the second for loop where you can detail the process (steps) taken to carry out the sort as towards which Array element values are swapped with other element values as the sort is carried out. It would be within the if statement code block which checks whether or not the previous Array element is greater than the current Array Element.
Good luck.

Operations on 1 Dimensional arrays

I am learning operations on 1 dim array.
It has three parts:
Set the 10 elements of integer array counts to zero.
Add one to each of the 15 elements of integer array bonus.
Display the five values of integer array best Scores in column format.
I have already figured out the 3. I need help in figuring out 1 and 2.
This is my code:
public class OneDimArrayOperations {
public static void main(String [] args){
// a) Set the 10 elements of integer array counts to zero.
int [] zeroArray = new int[10];
for (int i = 10; i == 0; i--) {
System.out.println("Count to zero from 10 elements" + zeroArray);
}
// b) Add one to each of the 15 elements of integer array bonus.
int [] arrayBonus = new int[15];
for (int i = 0; i <arrayBonus.length; i++) {
System.out.println("Bonus array values "+ arrayBonus[i]);
}
//c) Display the five values of integer array bestScores in column format.
int [] bestScores = {100,95,85,45,65};
System.out.printf("%n%s%12s %n", "Value", "BestScores");
for (int counter = 0; counter < bestScores.length ; counter++) {
System.out.printf( "%d%9d%n" , counter , bestScores[counter]);
}
}
}
part a:display:10,9,8,7,....1,0
for(int i=10;i>=0;i--)
part b:i havent understood your question
The line int[] zeroArray = new int[10]; will create an int array of size 10 and initialise all elements to zero. That's the default behaviour in Java.
for(int i = 0; i < arrayBonus.length; i++) { arrayBonus[i]++; } will solve your second problem.

How to make the max/min element of an array to 0? or remove them from the array

Say I enter values 1-10 in the array and when I try to run the code and print the values of my array, the max value of the element is still 10.0, how can I make that value to 0.0 or completely remove it from my array?
btw, I'm new to java and programming.
import java.util.Scanner;
public class Exer20 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double[] judges = new double[10];
for(int a=0; a < judges.length; a++){
judges[a] = input.nextDouble();
}
double max = judges[0];
double maxIndex = 0;
double min = judges[0];
for(int x = 0; x < judges.length; x++){
if(judges[x] > max)
max = judges[x];
maxIndex = x;
}
maxIndex = 0.0;
max = 0.0;
for(double b:judges)
System.out.println(b);
}
}
change this line:
max = 0.0;
to
judges[maxIndex] = 0.0
when you set primitive types they are copied by value. So when you change max it doesn't affect the judges array. You have to manipulate the array directly.
As your question already states that you are entering the values in your array of type double from 1-10 in sorted order,hence the minimum value in the array will be at 0th location and maximum value in array will be at last location, hence to make them 0 use the following code snippet:
judges[0]=0.0; //setting minimum to 0
judges[judges.length-1]=0.0; //setting maximum to 0
In case your array is not sorted,then make them in sorted order using any of sorting logic and apply the above given code snippet,as sorting of array will help to easily locate minimum and maximum value in array.

Union of multiple arrays

I am using this code in order to create a certain number of arrays and fill them with certain numbers:
public void CreateVars() {
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for (int j = 0; j < i; j++) {
System.out.println("Enter the number of values: ");
int p = s.nextInt();
System.out.println("Enter the numbers: ");
var[j] = new int[p];
for (int q = 0; q < p; q++) {
int n = s.nextInt();
var[j][q] = n;
}
}
}
How can I use the created arrays and do a union, for ex. A union B union C, since there is always a different number of arrays.
Thanks in advance
change your method to return the created array.
create a second method that takes the 2-dimansional array as parameter and returns a 1-dimensional array. This will to the union as I will show later
use Arrays.toString() to display the arrays content via System.out.println()
in the new method create a variable for the 1-dimensionl target array.
then loop over the first dimension of the parameter:
for(int[] subArray : parameterArray)
in that loop create a new temporary 1-dimensional array variable with the size of the current size of the target variable plus the size of the current subArray.
int[] tempArray = Arrays.copyOf(targetArray,targetArray.length+subArray.length]);
iterate over the subArray and copy the current value at the appropriate position in the temp array.
when finished the inner loop store the tempArray as targetArray
targetArray = tempArray;

Find the dimensions of a 2D array in java

I'm playing around with Arrays in Java and had this doubt. How do I find the dimensions of a 2D array in java? For example, I get an array input from System.in and pass it in another method like this:
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
findSize(arr);
/*
*
*Other code
*
*/
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
Both dimensions of the array are greater than 0. Appreciate the help.
This method:
findSize(int[] inputArr){
//I want to find the dimensions of the array here
}
is getting as parameter a 2 dimentional array
hence you should do:
findSize(int[][] inputArr){
int heiht = inputArr.length;
int width = inputArr[0].length;
}
I just need to access the 0th element of the array like this:
int size = inputArr[0].length;
This would do the trick!
A 2-dimensional array is an array of arrays. To get the actual length of the second dimension (which can be different for each array entry of the first dimension) do this:
int[] findSize(int[][] inputArr) {
int[] size = new int[inputArr.length];
for (int i = 0; i < inputArr.length; i++) {
size[i] = inputArr[i].length;
}
return size;
}
To get 2D-Array dimension 1:
int size_1 = inputArr.length;
To get 2D-Array dimension 2:
int[] size_2 = findSize(inputArr);

Categories

Resources