I'm new to java programming and i just cant figure out how to find the average of an array nor do i know how to print the array backwards. This is my code so far:
public static void forwards(int nums, int arrayNums[]){
for(int a=0;a<arrayNums.length;a++){
nums =(int)(Math.random()*90+10);
System.out.print(nums+" ");
}
System.out.println();
System.out.println();
//Average of the array
int average=0;
for(int b=0;b<arrayNums.length; b++){
average=(average+arrayNums[b]);
}
System.out.println();
System.out.println(average);
}
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length; a>0;a--){
System.out.print(nums+" ");
}
}
public static void main (String [] args){
int[] arrayNums = new int [Integer.parseInt
(JOptionPane.showInputDialog("How many numbers do you want to input?"))];
int nums = 1;
forwards(nums,arrayNums);
System.out.println();
backwards(nums,arrayNums);
For average ---->
for (int i = 0; i < array.length; i++)
{
sum += array[i];
}
int avegare = sum / array.length;
For Backwards ---->
for(int i = Array.length - 1; i >= 0;i--)
Backwards should start with arrayNums.length-1:
public static void backwards(int nums, int[] arrayNums){
//backwards of the array
for(int a=arrayNums.length-1; a >= 0; a--){
System.out.print(arrayNums[a]+" ");
}
}
The reason is that indices go from 0 to array.length-1. That's basically what happens in a for loop.
For the average, you forgot a division by the number of elements...
"i just cant figure out how to find the average of an array nor do i know how to print the array backwards."
For averages, you should use a different method, instead of trying to it in the forwards method
public static double average(int[] arrayNums) {
double sum = 0;
...
double average = // how do you get the average of something?
return average;
}
I started you off with the basic outline. You basically need to add all the numbers to the sum, by looping through the array, then get the average by diving it by the total of numbers in the array. Then you can print out the average like
double average = average(array);
System.out.println(average)
for backwards, you want to print arrayNums[a] instead of nums. You should also start the loop from arrayNum.length - 1 as there is no index in the array arrayNums.length so you would get an ArerayOutOfBounds exception. Also you want the 0th index, so you want to use >=
for(int a = arrayNums.length - 1; a >= 0 ;a--) {
// print arrayNums[a]
You seem to be doing the same wrong thing for forwards as you are in backwards. You want to print the arrays value for each index a, and not nums
I would also create the random array in a different method
public static int[] randomArray(int num) {
int[] random = new int[nums];
.... may array by looping
return random;
}
Then you the main you could just do
int[] array = randomArray(num);
forwards(array);
backwards(array);
double average = average(array);
System.out.println(average);
As you can see, I pass no nums to the methods. I think you should take tha parameter out of the method signatures. I see no use for them.
Here is a simple way to find the average. Just add up each of the elements, and then divide by the total number of elements in the array:
public static double average(int[] array)
{
int average =0;
for(int i =0; i< array.length; i++ )
{
average += array[i];
}
return average/array.length;
}
Here is a backwards method. Start at array.length-1, which is the last index. From there, iterate down i--, and then end when i is zero.
public static void printBackwards(int[] array)
{
for(int i =array.length-1; i>= 0; i--)
{
System.out.print(array[i] +" ");
}
}
When you call the methods, this is the syntax you should use:
double avg = average(arrayNums);
System.out.println(avg);
printBackwards(arrayNums);
Related
public static Word[] simpleSelect(Word[] array, int k){
k= array.length;
for(int i = 0; i< k-1; i++){
for(int j = 0; j<k-i-1; j++){
if(array[j].compareTo(array[j+1]) < 0){
swap(array,j, j+1);
}
}
}
return array;
}
I created this above code to return the K biggest elements from an array through a bubble sort. I am suppose to make this method O(nk).
I have wrote this code and figured that the returned array doesn't print an array with k size. Instead, it just prints the original array with the same length, just bubble sorted.
For example, if I my original array is {1,19, 7 ,26 ,9 ,85} and my k value is 2, I want it to return {85,26}.
Instead, currently this code is returning {85,26,19,9,7,1} no matter what the k value is.
I would like to know what i am doing wrong here and also would like to know if I am coding right in O(nk) times.
k is re-assigned on line 2: k = array.length; it's the reason why the method behaves regardless of the value of k.
As for complexity bubble sort has an average complexity of O(n^2), it must be adapted to meet your O(nk) requirements.
Assume we have the following array of numbers
static int[] arr = {456, 12 , 998, 546, 12, 987, 6456, 66, 9789};
We are going to construct the array of k largest numbers by iteratively finding the largest number of the array and then marking that number so that it does not get picked again.
This is the method that will find the k largest elements:
private static int[] kLargest(int[] arr, int k){
int[] klargest = new int[k];
for(int i=0;i<k;i++){
klargest[i] = findAndMarkLargest(arr);
}
return klargest;
}
And this is the method that find the single largest element, and then marks it (by setting the elements to Integer.MIN_VALUE)
private static int findAndMarkLargest(int[] arr){
int largest = Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
if(arr[i] > largest){
largest = arr[i];
}
}
for(int i=0;i<arr.length;i++){
if(arr[i] == largest){
arr[i] = Integer.MIN_VALUE;
}
}
return largest;
}
The main method (that simply calls the kLargest method) looks like this:
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
System.out.println(Arrays.toString(kLargest(arr, 3)));
}
And outputs:
[9789, 6456, 998]
Each call to findAndMarkLargest takes 2*n operations (since it runs over the array twice).
The method findAndMarkLargest is called k times by 'kLargest'. So, in terms of big O notation, this is O(2kn) which is equivalent to O(nk)
Below is what I have so far. The instructions are to create a simple java program that calculates the avg of a variable quantity of ints. Args array for main, no Scanner object, find and display highest and lowest value. Static method that takes user input as argument & returns values. Should display welcome message at launch.
So I think the start of my code is correct! It compiles for me. But I'm not sure how to get user input w/o scanner. I assume I need to use an array in the static method to translate the input into an argument. Which at execution would be java CalculateAverage 1, 2, 5, 9, 20?
And then would I call MATH? So I can display all the values of min max & avg? Am I on the right track..? The questions are specific in the code. Sorry, first time posting here!
public class CalculateAverage {
public static void main(String[] args) {
System.out.print("Hello welcome to the Average Calculator");
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
//do i just keep going and adding letters til j?
//or is there an easier way to do this..?
minArray(array);
maxArray(array);
sumArray(array);
avgArray(array);
}
public static double maxArray(double[] array){
double max = Double.NEGATIVE_INFINITY;
//tbh i saw this on a tutorial, idk if NEGATIVE_INFINITY would
//work for me?
for (int i = 0; i < n; i++)
if (array[i] > max) max = array[i];
System.out.println("The maximum of your array is:" + max);
}
public static double avgArray(double[] array){
double sum = 0.0;
for(int i = 0; i < n; i++)
sum += array[i];
double avg = sum / n;
System.out.println("The average value of your array is: " + avg);
} //then i would make another static for the min but probably before max
}
From the command line, you want to execute
javac CalculateAverage.java
to have Java compile the class and prepare to run it. Then you can execute the code with
java CalculateAverage arg0 arg1 arg2 ...
Now, in your main( string[] args ) method, I see you're creating an array with 11 elements. This is not necessary, and it is not ideal - what if the user gives more than 11 arguments when they're running the program? The better way to do this is:
int[] array = new int[ args.length ]()
This creates a new array of ints, of the same length as the array args - every array has that property length that states how many elements the array has. Now, we haven't actually put anything in array yet, but we know that it has space for the same number of arguments as the program gave. Now, to initialize each element:
for(int i = 0; i < args.length; i++) {
array[i] = Integer.parseInt(args[i])
}
A for loop creates a variable i (this is the int i = 0 part), initialized to 0, and then executes the code inside the curly brackets. After it's done, it increases the value of i by one (this is the i++ part), and runs the code inside the curly brackets again, continuously, until the condition i < args.length is false. Altogether, this iterates through every element of args and initializes the corresponding element of array.
Now, you could use the Math module to do the calculations for you, but you're almost there in doing it yourself. Here's a slight touch-up to maxArray, for example:
public static int maxarray(int[] array) {
int max = array[0]
for (int i = 1; i < array.length; i++) {
if (array[i] > max) max = array[i];
}
}
System.out.println("The maximum of your array is:" + max);
}
I'm using int here because the inputs were ints. In general you should probably make sure that everything is the same type of variable; either make all the numbers ints or make them all doubles, but don't try to go back and forth between them.
You don't actually need negative infinity for anything; you can just start with the first number in your array, call that the maximum, and then for every number afterwards, replace the maximum if it's larger. We use the for loop in the same way here, to iterate over the entire array.
Similarly, you're doing avgArray(double[] array) correctly already - except that I don't know where you got the variable n from (you should be using array.length again).
Overall, I recommend looking back over your notes for this class so far, and carefully make sure you know what everything means and how it applies to this example. Review what you've been taught about how Arrays work; and about the differences between ints and doubles.
This is what I would do. Hopefully the code is simple and self-explanatory but let me know if any questions:
public static void main(String[] args) {
System.out.println("Hello welcome to the Average Calculator");
int numArgs = args.length; //Since args is an array we can get the number of elements with .length
int min = Integer.MAX_VALUE; //The maximum possible value an int can be
int max = Integer.MIN_VALUE; //The minimum possible value an int can be
double total = 0;
for(int i = 0; i < numArgs; i++) {
int nextI = Integer.parseInt(args[i]);
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
System.out.println("The average is: " + total/numArgs);
System.out.println("The min is: " + min);
System.out.println("The max is: " + max);
}
Then, you would run the code like this:
java CalculateAverages 1 2 3 4 5 6 7 8 9
Hello welcome to the Average Calculator
The average is: 5.0
The min is: 1
The max is: 9
Edit:
The instructions said "To find these value, make static methods that
take the user input as arguments & returns the value"
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
System.out.println("The average is: " + getInputAverage(userIntInputs));
System.out.println("The min is: " + getInputMin(userIntInputs));
System.out.println("The max is: " + getInputMax(userIntInputs));
}
private static int getInputMax(int[] userIntInputs) {
int max = Integer.MIN_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] > max) {
max = userIntInputs[i];
}
}
return max;
}
private static int getInputMin(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
for(int i = 0; i < userIntInputs.length; i++) {
if(userIntInputs[i] < min) {
min = userIntInputs[i];
}
}
return min;
}
private static double getInputAverage(int[] userIntInputs) {
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
total += userIntInputs[i];
}
return total/userIntInputs.length;
}
One Method Alternative
Idk if she means to make a method for each value or one method!
Yeah teachers can be confusing all right. Here's a one method approach...
public static void main(String[] args) {
int numArgs = args.length;
int[] userIntInputs = new int[numArgs];
for(int i = 0; i < numArgs; i++) {
userIntInputs[i] = Integer.parseInt(args[i]);
}
Object[] inputMetrics = getInputMetrics(userIntInputs);
System.out.println("The average is: " + inputMetrics[0]);
System.out.println("The min is: " + inputMetrics[1]);
System.out.println("The max is: " + inputMetrics[2]);
}
private static Object[] getInputMetrics(int[] userIntInputs) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double total = 0;
for(int i = 0; i < userIntInputs.length; i++) {
int nextI = userIntInputs[i];
total += nextI;
if(nextI < min) {
min = nextI;
}
if(nextI > max) {
max = nextI;
}
}
Object[] metrics = {total/userIntInputs.length, min, max};
return metrics;
}
Simplicity is IMHO the best way. This does the whole thing:
DoubleSummaryStatistics stats = Arrays.stream(args)
.collect(Collectors.summarizingDouble(Double::parseDouble));
System.out.println("The minimum of your array is: "+ stats.getMin());
System.out.println("The maximum of your array is: "+ stats.getMax());
System.out.println("The sum of your array is: "+ stats.getSum());
System.out.println("The average of your array is: "+ stats.getAverage());
When there's a built-in library to handle something, use it.
I have
public int average(int grades[]){return **}
and I call it with: average({80, 90, 100})
I want to separate the array into three individual ints.
public int average1 = average[0];
public int average2 = average[1];
public int average3 = average[2];
Hope i helped :)
Edit: Whoops forgot to put a semicolon xD
If you're looking to compute the average of several integers in your grades array, as is implied by the name of your method, and regardless of how many items are in the array, you can use Java 8 streams. Just a suggestion.
public int average(int[] grades)
{
OptionalDouble od = Arrays.stream(grades).average();
if(od.isPresent())
{
return (int)od.getAsDouble();
}
return 0; //error condition to be checked by calling method.
}
The fact that the data is in an array, you already have "n" individual ints. Each element of the array is an individual int that you can access via an index value ranging from 0 to (n - 1), where n is the length of the array.
So an array of 3 ints would have indices 0, 1, 2.
With that, if your average() is to compute the average of the ints you have in your array, just loop through your array and accumulate the values into a sum and divide that sum by the number of ints that you have.
public static void main(String[] args) throws Exception {
System.out.println("Average: " + average(new int[] {80, 90, 100}));
}
public static int average(int[] grades) {
int sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}
return sum / grades.length;
}
Results:
Average: 90
I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and not 3.
import java.util.*;
public class test7 {
public static int findLargest(int[] a, int max) {
int i=0, j=0, tempmax=0;
if (a.length == 1) return a[0]>max ? a[0]:max;
else if(max < a[i]){
max = a[i];
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
else{
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
}
public static void main(String[] args) {
int[] values = new int[100];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements in your list: ");
int x = scan.nextInt();
if(x>1 || x<100){
for (int i=0; i<=(x-1); i++){
System.out.print("Enter your number: ");
System.out.println();
values[i] = scan.nextInt();
}
System.out.println();
System.out.println("The largest number is: "+findLargest(values, x));
}
else System.out.println("The maximum number of elements must be less than 100");
}
}
You call your method with:
System.out.println("The largest number is: "+findLargest(values, x))
This tells it to assume the largest number is x and try to find anything in the list that is greater than that. Of course, this produces the exact problem you described.
In general, when finding a maximum number, you want to initialize your candidate to the lowest number possible, or to the first number in your array.
If you initialize to the lowest number possible (Integer.MIN_VALUE) then as soon as you start your algorithm, the first number will definitely be bigger than it and will be chosen as the next candidate for maximum.
If you initialize to the first item in your array, then if that number is the highest, all well and good. If it is not, then when you encounter the next higher number, it will become the candidate, and all is good.
Which one you choose is up to you (and depends also on whether an empty array is possible), but the thing to remember is never to select an initial candidate that might be greater than all the elements in the array.
Try this working example:
public static void main(String[] args)
{
int[] numbers = {2, 5134, 333, 123, 8466};
int largest = numbers[0];
for(int i = 1;i<numbers.length;i++)
{
largest = Math.max(largest, numbers[i]);
}
System.out.println("Largest number: "+largest);
}
As a method that would look like this:
public static int max(int first, int... more)
{
for(int element:more)
{
first = Math.max(first, element);
}
return first;
}
You can then call it using something like max(1,23,564,234,543);
Continuing on my attempt at an app and I'm stuck again on the very next object.
Last time I asked about my Performer.java object which receives an array of 5 integers.
This time I am trying to manipulate the data through my Calculations object.
(Please correct me if I am labelling the wrong things objects)
import java.util.List;
public class Calculations {
public static int performCalcs() {
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
for(int i=0 ; i<=arrayOne.size() ; i++) {
int sumTotal = 0;
return sumTotal;
}
}
}
I am literally stuck. I know it doesn't make any sense, but what I am trying to do is add up all the numbers in my array and also calculate the average of the numbers in my array.
I think I did the "i" correctly, and I was able to retrieve my array into arrayOne, but don't know how to implement the "i" and make it perform either addition or multiplication until i<=arrayOne.size.
Thanks guys!
for(int i=0 ; i<=arrayOne.size() ; i++){
int sumTotal = 0;
return sumTotal;
}
What you are doing in the above code, is that you are entering the loop, and after the first interation you return sumTotal (which will be 0)
This is what you want to do
int sumTotal = 0; // declare the variable you want to to summerize outside the loop. If you declare it inside the loop it will be garbage collected once the loop finishes and the variable is lost
for(int i=0 ; i<arrayOne.size() ; i++){
sumTotal+=arrayOne.get(i); // add the value that is at the current index each iteration
}
//After the loop, somTotal will have the total added value of the integers in the `List`. Now you can continue from here
You should move sumTotal outside the for loop. Otherwise the sumTotal variable is re-initialized every time.
You should loop till i < arrayOne.size(). O.w. you'll get an IndexOutOfBoundsException
You do retrieve the i-th number in this way: arrayOne.get(i)
Then compute the average value by dividing sumTotal for the number of values in the arrayOne list.
Here's the code:
import java.util.List;
public class Calculations {
public static int performCalcs() {
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
// Sum the numbers in the array
// Repeat until i < arrayOne.size()
for (int i = 0; i < arrayOne.size(); i++) {
int num = arrayOne.get(i);
sumTotal += num;
}
// Check that the array is not empty.
// If it is not, compute the average, o.w. return 0.
double avg = arrayOne.isEmpty() ? .0 : (sumTotal / arrayOne.size());
System.out.println("average: " + avg);
return avg;
}
}
The best way is to use for-each loop:
int sumTotal = 0;
for(Integer val: arrayOne) {
sumTotal += val.intValue();
}
To sum all the numbers in any Iterable you need to do this:
//Declare the variable to hold the total outside the loop.
int total = 0;
//Loop over the integers to sum.
for (Integer i : integers)
{
//Add the current integer to the total.
total += i;
}
//The total will now equal the sum of all the integers.
System.out.println("Total: " + total);
System.out.println("Average: " + (total / integers.size()));
The two important bits that your code was missing are:
the total variable must be declared outside the loop else it is simple reinitialized with each iteration.
you need to add the integers values together.
I guess it should look like this
public class Calculations {
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
for(int i=0 ; i<=arrayOne.size() ; i++){
int sumTotal += i;
}
return sumTotal;
}
}
The issue here is that you are using "return" inside your loop. The i++ part is fine. Use the return outside of the loop. All of the answers above show this.
If you use "return" in your loop, it will only iterate once.
Move int sumTotal = 0; out of the loop (above) and return ... also (below). Inside the loop put sumTotal += arrayOne[I]. You are learning the hard way, aren't you?
you should pull the sum init and the return out of your loop
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
for(int i=0 ; i < arrayOne.size(); i++){
return sumTotal += arrayOne.get(i);
}
return sumTotal;
}
Note how sumTotal is returned within the loop, meaning that on the very first time through the loop it returns the first value. You want it to say
import java.util.List;
public class Calculations {
public static int performCalcs(){
Performer getInput = new Performer();
List<Integer> arrayOne = getInput.getUnit();
int sumTotal = 0;
for(int i=0 ; i<arrayOne.size() ; i++){
sumTotal+=arrayOne.get(i);
}
return sumTotal;
}
}
returns work in java (and most programming languages) that there can be many in a function, and the first one that it finds the function ends and returns whatevers after the return, for example
public double someFunction(int a){
if (a!=5){
return a;
}else{
return 12;
}
return 999; //this return is never used under any circumstances because the function has already returned, good IDEs won't even allow it
}
Two returns and it uses the first one it finds
Edit:
As Maroun Maroun correctly states the for loop should be
for(int i=0 ; i<arrayOne.size() ; i++){
not
for(int i=0 ; i<=arrayOne.size() ; i++){
This is because java array indexes start at 0, so an array with 5 entries will have indexes 0,1,2,3,4