return values to main method - java

Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.
//Main
public class Lab_4_Practice {
public static void main(String[] args) {
//Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = (total / randomArray.length);
//Call Methods
random(randomArray);
displayRandom(randomArray);
largest(maxIndex, randomArray);
smallest(minIndex, randomArray);
sum(total, randomArray);
average(total, randomArray);
sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
//***************************************************
//Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
randomArray[i] = (int)(Math.random() * 300);
}
}
//Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
//Method identifies largest index and its element in array
public static void largest(int maxIndex, int[] randomArray) {
for (int l = 1; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
}
//Method identifies smallest index and its element in array
public static void smallest(int minIndex, int[] randomArray) {
for (int i = 1; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
}
//Method calculates sum of elements
public static int sum(int total, int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
total = total + randomArray[i];
}
return total;
}
//Method calculates average of elements
public static void average(int total, int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
i += randomArray[i];
}
}
//Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
//Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
//Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
}

Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -
public class Example{
public void assign(int[] Array){
for(int i=0;i<Array.length;i++){
Array[i]=(int)(Math.random()*300);
}
}
public void display(int[] Array){
System.out.println("The 10 elements of the array are:");
for(int i=0;i<Array.length;i++){
System.out.println(Array[i]);
}
}
public int sum(int[] Array) {
int total =0;
for(int i=0;i<Array.length;i++){
total=total+Array[i];
}
return total;
}
//write all other methods here in this class.
}
now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -
public static void main(String[] args) {
int[] randomArray=new int[10];
Example e=new Example();
e.assign(randomArray);//this must be called first to assign the values inside the array.
e.display(randomArray);//call this method if you wish to display the values.
System.out.println("The sum of the elements are: "+e.sum(randomArray));
}

I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.
public class StackProblem {
public static void main(String[] args) {
// Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = 0;
// Call Methods
random(randomArray);
displayRandom(randomArray);
sortArray(randomArray);
maxIndex=largest(randomArray);
minIndex=smallest(randomArray);
total=sum(randomArray);
average=average(total, randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 300);
}
}
// Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
int maxIndex=0;
for (int l = 0; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
int minIndex=0;
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Method calculates sum of elements
public static int sum(int[] randomArray) {
int localTotal=0;
for (int i = 0; i < randomArray.length; i++) {
localTotal+=randomArray[i];
}
return localTotal;
}
// Method calculates average of elements
public static int average(int total, int[] randomArray) {
return total/randomArray.length;
}
// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}

[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]
This is the typical pattern for a method calculating some value from the elements of an array:
public static int largest(int[] array) {
int maxIndex = 0;
for (int l = 1; l < array.length; l++) {
if (array[l] > array[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
And you call it like this:
int maxIndex = largest( randomArray );
Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.
If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.
Finally, the code for calculating the average is very much in error.
public static double average( int[] array ) {
return (double)sum( array )/array.length;
}
and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)

The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:
randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.

Related

how to add elements in each row seperately and print output in 2D array

Lets assume i have a 2x3 matrix where row denote student and column denote marks.
eg:[[67,80,56],
[32,26,31]]
need to find the average of each row and assign a grade based on avg. if avg>40 then return "p" else return "F".
import java.util.*;
public class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=2;
int m=5;
int mark[][]=new int[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
mark[i][j]=sc.nextInt();
}
}
String result=grade(mark);
System.out.println("RESULT:"+result);
}
public static String grade(int mark[][])
{
int n=2,m=5,avg=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int sum=0;
sum=sum+ mark[i][j];
if(j==m)
{
avg=sum/m;
}
}
if(avg>=90)
{
return "A+";
}
else if(avg<40)
{
return "F";
}
}
return null;
}
}
IN the above code my my average value is initialised to 0.scope of average in for loop is not reflected in outside loop.how to correct itenter image description here
You are declaring the sum variable inside your 2nd loop it should be declared before your 2nd loop starts. If you declare it inside it will not have the calculated value from the previous iteration.
Also you can easily calculate avg outside the loop and then gor for your cheking.
EG:
int n=2;
int m=3;
int[][] mark = { { 67,80,56 }, { 32,26,31} };
// grade function
for (int i = 0; i < n; i++) {
int sum=0;
for (int j = 0; j < m ; j++) {
sum=sum+ mark[i][j];
}
int avg = sum / m;
System.out.println(avg);
//your code to check pass/fail
}
Also Don't return if you want to print values for each row. Instead of return use print there.
if(avg>=90)
{
System.out.println("GRADE")
}
First of all, if you need to print the grade of every student separately you will need to call your grade method for every student's marks. So put your method call in a for loop.
for(int i = 0; i < n; i++) {
System.out.println(grade(mark[i]))
}
Consequently, the definition of your method changes to
public static String grade(int mark[]) {
...
}
And at last, your if(j==m) check will always be false, cause in your code, j will never reach m in your for loop. It comes to a simple calculation of array element's sum.
public static String grade(int mark[][])
{
int m = 5, avg = 0;
int sum = 0;
for(int j = 0;j < m; j++) {
sum = sum + mark[i][j];
}
avg = sum / m;
if(avg >= 90)
{
return "A+";
}
else if(avg < 40)
{
return "F";
}
}

Java swap lowest number in array with chosen number

I don't know how to swap the smallest number in an array with a number that I choose. The method I have to use in order to do this is swapNum(). Then after I do that, I have to print out the array, but with the modifications I did from swapNum()
public class Data
{
private int numbers[] = {1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10,};
private int smallNum = numbers[0];
private int largeNum = numbers[0];
private int countNum = 0;
public void setsmallNum(int smallNum)
{ this.smallNum = smallNum; }
public void setlargeNum(int largeNum)
{ this.largeNum = largeNum; }
public void setcountNum(int countNum)
{ this.countNum = countNum; }
public int getsmallNum()
{
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] < smallNum)
{
smallNum = numbers[i];
}
}
return smallNum;
}
public int getlargeNum()
{
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] > largeNum)
{
largeNum = numbers[i];
}
}
return largeNum;
}
public int getcountNum()
{
int counter = 0;
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] == countNum)
{
counter++;
System.out.println("Number is at index: " + i);
}
}
return counter;
}
public int swapNum()
{
/* swap lowest number in array with a selected number
that I choose such as d.setcountNum(5)
*/
}
public static void main(String[] args)
{
Data d = new Data();
d.getlargeNum();
d.getsmallNum();
d.setcountNum(5);
System.out.println("Largest number: " + d.getlargeNum());
System.out.println("Smallest number: " + d.getsmallNum());
System.out.println("Number appears " + d.getcountNum() + " times");
// System.out.println(Print out the modified array from swapNum() method)
}
}
As per your code, smallest number is stored in the global smallNum variable.
Using this value create a function that takes a number of your choice as an argument. Then find the smallest number in the array and swap using temp variable.
public int swapNum(int num){
int temp = 0;
for(int i=0; i<numbers.length; i++)
if(numbers[i] == smallNum){ //find smallest value in array.
temp = numbers[i];
numbers[i] = num;
}
}
return temp; //You can return the value that was swapped
}
Create another function that displays the content of numbers array. Call it whenever you want.
public void display(){
for(int i=0; i<numbers.length; i++){
System.out.print(numbers[i]+" ");
}
System.out.println();
}
Several modifications can be done to improve code efficiency.

Need a sort method in Java with user input using the scanner class [duplicate]

This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have a method to output the highest value, lowest value, average value and I need a sort method. I have tried to put what is called a "bubble method" but it isn't working out. Anyone know other sort methods I can use?
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
//System.out.println ( "\nLargest " + max (1, 3, 5) );
System.out.println("sorting" + sort(array));
System.out.println("The highest number in the array is " + max(array));
System.out.println("The smallest number in the array is " + min(array));
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static int sort(int[] arg) {
for (int i = 1; i < arg.length - 1; i++) {
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
int arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
return arrange;
}
public static int max(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int largest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] > largest) {
largest = arg[i];
}
}
return largest;
}
public static int min(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int smallest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] < smallest) {
smallest = arg[i];
}
}
return smallest;
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
}
There are many other sort methods you can use. The one you were trying to use is called "Bubble Sort" and is very expensive on large data sets unless they are somewhat ordered. I would recommend using selection sort or insertion sort for what you are trying to accomplish.
Here is a link to the many sorting algorithms you can implement: Sorting Algorithms
Here are some animations showing the process of these sorts (Highly recommend you look at these before implementing your algorithm):
Helpful animations
You can use any sorting method as your convenient and according to your requirement. After sorted the array you can easily pick up the minimum and maximum value from the sorted array, first element and the last element of the array.
For calculate the average you have to use separate method as you used or you can use static variable to calculate the total inside the sorting method.
Refer this code.
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
sin.close();
System.out.println("sorting");
printArray(array); //Before sort
sort(array);
printArray(array); //After sort
System.out.println("The highest number in the array is " + array[array.length - 1]);
System.out.println("The smallest number in the array is " + array[0]);
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
public static void printArray(int[] arr) {
for (int value : arr) {
// print elements according to your convenient
System.out.println(value);
}
}
To print the array you have traversal through the array. See Above code method.

Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000

this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()

Java method to sum any number of ints

I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.

Categories