The Idea is to create a method that is static that will calculate the average salary for a partially-filled array. Assume that numEmployees holds the number of elements in the array that have valid data. numEmployees is passed to the method.
public static double getAverage(double[ ] numEmployees)
{
double total = 0;
double average;
for (int i = 0; i < numEmployees.length; i++)
total += numEmployees[i];
average = total / numEmployees.length;
return average;
}
Do I need to add a part in the method that counts the array that are filled?
like:
int count=0;
int p=0;
if (numEmployees[p]>0)
{
count++;
p++;
}
or should I add a part in my for loop inside the message and change my total to this:
for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
total += numEmployees[i];
Than farther down
average = total / i;
public static double getAverage(double[] numEmployees)
{
double total = 0;
double count = 0;
for (int i = 0; i < numEmployees.length; i++)
if (numEmployees[i] > 0) {
total += numEmployees[i];
count++;
}
return total / count;
}
Note that if there can be no more values after the first 0, it's also good to end the loop when one is detected. What i wrote here looks for any value greater than 0, no matter where the 0's occur.
Related
I want to see how long it takes for 10,000 random integers to be sorted. Since in a bubblesort, the arrays are sorted at each stage and it could also vary each time, I want to know the total time it takes for the final sorting array to appear. So my time calculations should be when each sorting of the array is taking place, and when the final sorting happens and the results appear, the output should tell me the time in seconds.
I have used System.currentTimeMillis(); for this task but how would I use it so it calculates the time at each sorting stage? I have used it inside the for (int k = 0; k < numbers.length; k++){ loop because this loops through all the stages of the sorting, but my program would not output anything. How would I fix that?
Code:
class Main {
public static void main(String[] args) {
// Clear screen
System.out.print("\033[H\033[2J");
System.out.flush();
double msStartTime = 0d;
double msEndTime = 0d;
// Initialize an int array variable and set the limit to 10,000
int numbers[] = new int[10000];
// Generate random 10,000 integers to bubblesort
for (int x = 0; x < numbers.length; x++) {
numbers[x] = (int) (Math.random() * 10001);
}
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
if (numbers[j] < numbers[i]) {
int temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
for (int k = 0; k < numbers.length; k++){
msStartTime = (double) System.currentTimeMillis();
}
}
msEndTime = (double) System.currentTimeMillis();
System.out
.println("To sort an array of 10,000 integers, it takes " + (msEndTime - msStartTime) / 1000 + " seconds");
}
}
i think you can use StopWatch.here is how u can add it to maven and use it
https://www.baeldung.com/java-measure-elapsed-time
Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;
I am now studying java and I'm having a lot of issues in this chapter of 1 dimensional arrays.
What I need to do in this question is to detect if , in the array, there are the same amount of numbers above the avarage than below the average. Now, what I dont know, after I detect the middle of the array, how I can calculate the average since I dont know how to add all the numbers together, remember that I cant just say array[1]+array[2]+array[3] because I simply dont know how many array elements there are...
Use a for loop:
double total = 0; //Total of all the numbers in the array
double average; //Average of all the numbers in the array
int belowCount = 0; //Number of numbers below the average
int aboveCount = 0; //Number of numbers above the average
int sameCount = 0; //Number of numbers at the average
for(int i = 0; i < array.length; i++){
total += array[i];
}
average = total/array.length;
for(int i = 0; i < array.length; i++){
if(array[i] < average){
belowCount++;
}
else if (array[i] > average){
aboveCount++;
}
else{
sameCount++;
}
}
if(belowCount==aboveCount)
{
return true;
}
else
{
return false;
}
I have a 2D array and I want to find the largest average set of results, so far I can calculate the average of each set of results but I'm not sure how to select the biggest from the output.
My code:
static int[][] studentMarksArray = new int[10][3];
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
}
An attempted solution:
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
double newTotal = total;
if(newTotal>total){
newTotal = total;
System.out.println(newTotal);
}
}
Like this:
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
max = Math.max(max, total);
}
or if you want the index:
int index = -1;
double max = 0;
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}
Ok if you want to have an array of averages at the end, do this:
int index = -1;
double max = 0;
double [] averages = new double[10];
for(int i = 0; i < 10; i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
averages[i] = total;
if(Math.max(max, total) == total) {
index = i;
max = total;
}
}
add this after variable initialisation
int largest=0,lp=0;
add this before forloop ends but after calculating total
if(largest<total){
largest=total;lp=i;
}
at the end of forloop you will have largest average in the variable largest and its position in variable i.
You can save the outPut at every step in to a priority queue(which saves the elements in natural ordering) and in the last step the pull() the highest value from this priority queue.
import java.util.PriorityQueue;
public class Test1 {
public static void main(String[] arg){
int[][] studentMarksArray = new int[10][3];
PriorityQueue<Double> pq = new PriorityQueue<Double>();
for(int i=0;i<10;i++){
double total = (studentMarksArray[i][0]*studentMarksArray[i][1]*studentMarksArray[i][2])/3;
System.out.println(total);
pq.add(total);
}
System.out.println(pq.poll());;
}
}
I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written.
But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.
Here's how:
// Create an array with room for 100 integers
int[] nums = new int[100];
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
nums[i] = i + 1; // +1 since we want 1-100 and not 0-99
// Compute sum
int sum = 0;
for (int n : nums)
sum += n;
// Print the result (5050)
System.out.println(sum);
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
To populate the array:
int[] numbers = new int[100];
for (int i = 0; i < 100; i++) {
numbers[i] = i+1;
}
and then to sum it:
int ans = 0;
for (int i = 0; i < numbers.length; i++) {
ans += numbers[i];
}
or in short, if you want the sum from 1 to n:
( n ( n +1) ) / 2
If your array of numbers always is starting with 1 and ending with X then you could use the following formula:
sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.
int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);
int[] nums = new int[100];
int sum = 0;
// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
{
nums[i] = i + 1;
sum += n;
}
System.out.println(sum);
The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.
Public Class Program
{
public static void main(String args[])
{
//Array Intialization
int my[] = new int[6];
for(int i=0;i<=5;i++)
{
//Storing array values in array
my[i]= i;
//Printing array values
System.out.println(my[i]);
}
}
}