So far i have made a random numbers array but i am stuck on how to make a printarray method that i can call within the main. I need to invoke print array in the same class and print out all elements separated by one space
public class HunterIsaacsHw6
{
public static void main(String[] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
}
public static double printArray(doubleArray[]){
for(double n: doubleArray){
System.out.println(n+" ");
}
}
Your method declaration is incorrect and you are not even calling it. Try:
public static void main(String [] args)
{
System.out.println("Java, Online, Hunter Isaacs, hw6");
// define the range
int max = 100;
int min = 1;
int range = max - min + 1;
// combining both statements in one
double doubleArray[] = new double[10];
// generate random numbers within 1 to 10
for (int i = 0; i < 10; i++) {
doubleArray[i] = (Math.random() * range) + min;
}
printArray(doubleArray);
}
public static void printArray(double doubleArray[]){
for(double n: doubleArray){
System.out.println(n);
}
}
Also, nothing is being returned from printArray so it should be declared as void
Also I prefer the declaration as double[] doubleArray
edit
Also System.out.println(n); is sufficient, there is no need to append a space
Related
How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad
I am trying to create 3 methods which calculate the sum and average of a random array then outputting the result.
I am trying to get an output similar to -
java RandomArray 5
9 7 2 1 4
Sum: 23
Mean: 4.6
but I am getting "Usage: java RandomArray . Example: java RandomArray 5"
if you can spot the errors in my code and help with how to get this output.
public class RandomArray {
private int[] numbers; //instance variable
/**
* Constructor
*
*#param size The size of the array
*/
public RandomArray(int size){
numbers = new int[size];
for(int i=0; i<numbers.length;i++){
numbers[i] = (int)(Math.random()*10); // a random number between 0-9
}
}
/**
* a method to print the array elements
*/
public void printArray() {
for (int i = 0; i < numbers.length; i++)
System.out.print(i + " ");
}
/**
* A method to calculate the sum of all elements
*
*#return The sum
*/
public int calSum(){
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
/**
* A method to calculate the mean of all elements
*
*#return The mean
*/
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
/**
* a method to print the array elements in reverse order
*/
public void printReverse(){
}
/**
* A main method to test
*/
public static void main(String[] args) {
// Check to see if the user has actually sent a paramter to the method
if (args.length != 1){
System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
System.exit(-1);
}
// Create an instance of the class
RandomArray test = new RandomArray(Integer.parseInt(args[0]));
// Print the array
test.printArray();
// Calculate the sum of all the values in the array and print it
System.out.println("Sum: "+ test.calSum());
// Calculate the mean of all the values in the array and print it
System.out.println("Mean: "+ test.calMean());
System.out.print("Reverse: ");
test.printReverse();
}
}
Let’s look at your sum method first:
public int calSum(int sum) {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Why does this method accept a parameter? You just redeclare it on the next line anyway.
Looks good otherwise.
Here’s a cleaned up version:
public int calSum() {
int sum = 0;
for (int value : numbers) {
sum += value;
}
return sum;
}
Next up, mean average:
public double calMean(int[] array){
//Unsure which elements go here
}
Again, why the parameter?
Recall how we calculate the mean average: sum all elements, then divide by the number of elements.
We’ve already got a method for calculating the sum, so we can use that.
public double calMean() {
int sum = calSum();
int length = numbers.length;
return (double) sum / length;
}
Note the use of (double) here. Without it, cal / length would be integer division, and the result would be rounded to the nearest whole number.
Your method "printArray(int sum)" has the mistake. When you call the method you take a parameter sum, which is not needed. Then you try to create a second local variable with the name sum. This is impossible, because you already have a parameter called sum.
In your for loop you init antoher local variable called sum. You need a different name for that variable, since you only need it for counting the loop.
So remove your parameter sum and rename the variable used in the for loop.
This should work:
import java.util.Arrays;
public class ArrayCalculations
{
private int[] numbers;
public ArrayCalculations(int size)
{
this.numbers = new int[size];
for (int i = 0; i < size; i++)
{
int randomNumber = (int) (Math.random() * 10);
numbers[i] = randomNumber;
}
}
public int calculateSum()
{
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
return sum;
}
public float calculateAverage()
{
float sum = (float) calculateSum();
return sum / numbers.length;
}
public void printArray()
{
System.out.println(Arrays.toString(numbers));
}
public static void main(String[] args)
{
ArrayCalculations ac = new ArrayCalculations(5); // initiates an array with 5 elements
ac.printArray(); // prints the array to console
System.out.println("The sum is: " + ac.calculateSum()); // prints the sum
System.out.println("The average is: " + ac.calculateAverage()); // prints the average
}
}
I wrote the code to create user desired number of array and size, but there is no any random number displayed.
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
randomArray[i] = (int)(Math.random());
}
}
}
The problem is that Math.random() return a Double value from 0.0 to 1.0
0.1 to int = 0, ....... 0.5 to int = 0 .
If you need generate random number try it:
public static int randomNumber(int min, int max) {
Random rand = new Random();
int num = rand.nextInt(max - min + 1) + min;
return num;
}
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
//Example Generate random number between 1 and 9
randomArray[i] = randomNumber(1,9);
}
}
Here's a tiny modification to your code, that would fill your array with random ints from 0 to Integer.MAX_VALUE:
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
for (int i=0; i < randomArray.length; i++){
randomArray[i] = (int)(Math.random() * Integer.MAX_VALUE);
}
}
}
The thing here is that Math.random() returns a double in the range from 0 to 1. When you were casting it to (int) it always turned 0.
Alternatively you can take a look at class Random.
The random values aren't stored because function Math.random() generates values between 0.0 (inclusive) and 1.0 (exclusive) and hence, cast to int will always return 0. From official docs:
Returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Either multiply the Math.random() result with some fixed integer value and cast to int or use a Random instance's method random.nextInt() as:
int rand = (int)(Math.random() * FIXED_INT_VAL);
or
Random r = new Random();
int rand = r.nextInt();
The latter approach is recommend due to reason explained in this post.
So, your code becomes:
public class ArrayStats {
public static void fillRandomArray(int [] a, int max) {
int [] randomArray = new int[max];
Random r = new Random();
for (int i=0; i < randomArray.length; i++){
randomArray[i] = r.nextInt();
}
}
}
I am having problems understanding a program I need to write for class. My program works as it should, but the problem states that it wants me to not print within my methods. I am confused on how I should output my values because my methods must be void according to the problem (which doesn't return anything) and I can't print inside of them.
Here is the question:
Design and implement a java program (name it ArrayMethods), that defines 4 methods as follows:
int arrayMax (int[] array)
int arrayMin (int[] array)
void arraySquared (int[] array)
void arrayReverse (int[] array)
Test your methods by creating an array of length 5 within your main method and filling it with random numbers between 1 and 1000. Your program should then display the original array, display the smallest number in the array, display the greatest number in the array, display the revered array, and display the square of each value in the array. You main method shoudl invoke each method exactly once, with each invocation use the original array as the actual parameter. No printing within the methods. Document your code, and organize/space your outputs properly. Use escape characters and formatting objects when applicable.
So again my question is: How do I use those methods without printing anything if I can't return a value? If anyone could give me a clue on how to solve this, it would be greatly appreciated.
import java.util.Random;
import java.util.Arrays;
public class ArrayMethods
{
public static void main (String[] args)
{
int[] array = new int[5];
array[0] = (int)(Math.random() * (1000 - 1)) + 1;
array[1] = (int)(Math.random() * (1000 - 1)) + 1;
array[2] = (int)(Math.random() * (1000 - 1)) + 1;
array[3] = (int)(Math.random() * (1000 - 1)) + 1;
array[4] = (int)(Math.random() * (1000 - 1)) + 1;
System.out.println("The values within the array are: " + Arrays.toString(array));
System.out.println("The maximum value within the array is: " + arrayMax(array));
System.out.println("The minimum value of the array is: " + arrayMin(array));
System.out.print("The values within the array (squared) are: ");
arraySquared(array);
System.out.print("\n");
System.out.print("The array reversed is: ");
arrayReverse(array);
}
public static int arrayMax (int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static int arrayMin (int[] array)
{
int min = 1000;
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public static void arraySquared (int[] array)
{
int[] array2 = new int[5];
for (int i = 0; i < array.length; i++)
{
array2[i] = array[i] * array[i];
System.out.print(array2[i]);
while ( i < array.length - 1)
{
System.out.print(", ");
break;
}
}
}
public static void arrayReverse (int[] array)
{
for(int i = array.length - 1; i >= 0; i--)
{
System.out.print(array[i] + " ");
}
}
}
For the void functions, in C# you'd simply use an "out" or "ref" keyword. If they insist on Java, Java doesn't have an equivalent, but you can do something like that with an object.
public class PassArray
{
public int[] array;
public PassArray(int[] array)
{
this.array = array;
}
}
public static void Reverse(PassArray arrayHolder)
{
int[] reversed = new int[arrayHolder.array.Length];
int j = 0;
for (int i = arrayHolder.array.Length - 1; i >= 0; i--)
{
reversed[j] = arrayHolder.array[i];
j++;
}
arrayHolder.array = reversed;
}
static void Main(string[] args)
{
int[] toReverse = new[] { 10, 30, 2, 1, 3, 100, 340 };
PassArray passedObject = new PassArray(toReverse);
Reverse(passedObject);
// passedObject.array will now have the reversed array
}
Obviously this could can be improved but it should at least give the right idea.
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.