Reputation: 33
I am not sure how print the values of arrays when called from methods, I have to solve these:
1- create an array consisting of 100 random integers in the range 100 to 500, including the end points. (This part i am OK, the next 2 points i am quite doubtful on how solve it)
2- make a method to print the array, 5 numbers per line, with a space between each. (I got almost everything right except I don't know how Return the value, I tried return System.outprint.....
but didn't work either anyway the method has a void some made it worse)
3- make a method to print the smallest number in the array. (this i got no clue how to do it!)
This is my code so far:
package randomhundred;
import java.util.Arrays;
public class RandomHundred {
private static int[] rand;
public static void main(String[] args) {
// TODO code application logic here
//setting the 100 array
/* PART I*/
int rand [] = new int [100];
int numb;
for(int i=0; i<rand.length; i++){
numb = (int) (100 + (Math.random() * ( (500 - 100) + 1)));
numb = rand[i];
}
}
/* PART II */
public static void arai (){
for (int i=0; i<100; i++){
System.out.print(rand[i] + " ");
if( i%5 == 0){
System.out.println();
}
else{
System.out.print(rand[i] + " ");
}
}
/**
PART IV
*/
public static int suma(){
int ad;
for(int i=0; i<100; i++){
ad =+rand[i];
}
return ad;
}
}
}
Upvotes: 0
Views: 1762
Reputation: 25864
First of all, when setting your numbers, you need to set the array index... e.g.
rand[i] = (int) (100 + (Math.random() * 401)); // 100-500
Part 2 should read:
for (int i=0; i<rand.size(); i++){
if( i%5 == 4){
System.out.println(rand[i] + " ");
} else{
System.out.print(rand[i] + " ");
}
}
Part 3 should read:
int ad = 500;
for(int i=0; i<100; i++){
ad = Math.min(ad, rand[i]);
}
System.out.println("Smallest="+ad);
Upvotes: 1
Reputation: 5076
For part 3, you're going to want to
By the end of this loop the integer we created must be the smallest possible number, as we went through every possible variable to see if there was a smaller one. All you have to do now is print it out.
Also I don't know why you would want to return the values in part 2, a void function doesn't have to return anything and you can just print out the numbers straight from the function.
Upvotes: 0