Passing the array to method (using random numbers) - java

I am writing a program piece by piece. I continue to receive compile errors. Can you look at my code to determine my issue?
So here, I am saying that array can store 1000 elements of the double type. Now I want to pass the array to my main method and place 1000 random numbers into the array. So I will create a new method.
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
}
}
Here, I have created a new method named passArray. I am trying to say that for each array element at its respective index (based on the count) assign a random integer until we reach 1000.
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
x[counter]=(int)(Math.random()*1000);
}
Okay, so now I want to print my results to determine if my code does what I want it to do. In my main method, I will use an enhanced for loop:
for(double k: array)
System.out.println(k);
}//End of main Method
The problem I continue to encounter is a compile error. However, the output displays 999 values as a double value at random. What in the world am I missing here?

I think you have a typo ( remove the '}' from the for loop )
and you need to pass the array to the method to make it work.
This compiles and runs :
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
// calling the method
passArray(array);
// print the array
for(double k: array)
System.out.println(k);
//End of main Method
}
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
// compiles ... but why cast to int if you have double[] ?
x[counter]=(int)(Math.random()*1000);
}
}
}

Not sure about the compile error, but your int to double problem is at the start of your code.
You declared an array of type double:
double[] array = new double[1000];
You're trying to type cast your random values to type int, which the compiler should accept.
x[counter] = (int) (Math.random() * 1000);
However since this is an array of type double, then you're storing the values as doubles. i.e. the values get cast back to double immediately. All that java is really doing is, changing from a double, eg. 567.97, to an int 567, and stroing it as a double again 567.0. Notice that it has now lost all its floating point information from being cast to an int. Or in geekier terms, the mantissa has been set to all 0's.
Either you will have to declare your array as type integer. Or cast back to int every time you access a value.
eg.
int[] array = new int[1000];
public static void passArray(int[] x) {
// code
}
or
System.out.println((int)k);
Edit: Are you getting a compiler error, or warning? There's a big difference. A warning will allow it to run, which your posts suggests is happening, an error will not compile, and thus not run. You may just be getting a warning about the type cast from int to double.

Related

Why should I define a method as another variable for integers but not for array in java?

The following code:
public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}
will return error and I need to write
int x = sum(first,second);
System.out.println(sum);
and define that method as integer x and print x.
But for array,
public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}
public static void main(String[] args) {
//code
removeLast(persons);
System.out.println(persons);
}
will print the returned value of array without defining as another array as the was with the previous one.
I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.
Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.
For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.
But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.
Because Java is pass by value, but the value of reference types (including arrays) is a reference to the Object (in this case, a List). You might use a variadic function and (in Java 8+) an IntStream to implement it like
public static int sum(int... arr) {
return IntStream.of(arr).sum();
}
Then you can call sum with as many (or few) int arguments as you like.
Will print the returned value of array without defining as another
array as the was with the previous one ?
Whatever #yeedle mentioned above is correct, but one point to add as below:
ArrayList class (actual type of persons object) has overridden the toString() method such that it
could print the array details when you invoke
System.out.println(persons);.
You need to know that for your objects (created for your custom
classes like Product, Employee, etc..), you need to override
toString() method (inherited from java.lang.Object) to print the
values like how you wanted, otherwise simply using
System.out.println(object); will print the hashcode of the
object (like #HA5431 etc..).
You can look here and here

Adding numbers to arrays with methods in another class?

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

method result type

In the following code the method array1 won't return the avarage because its return type is void.
I know what void means but can someone explain to me what is a void result type and how to make this method return the avarage:
public class JavaApplication4 {
public static void main(String[] args) {
int[] a = {1,2,3,4};
double result = array1 (a);
}
public static array1 (int[] b) {
double avarage;
int total = 0;
for (int x:b) {
total += x;
}
avarage = total / b.length;
return avarage;
}
The "result type" or "return type" is set in the function declaration. It just means what type of data is going to be returned after the function is called. Your function should look like:
public static double array1(int[] b) {
double average;
int total=0;
for(int x:b){
total +=x;
}
average = (double) total/b.length;
return average;
}
This will return the value of average after the function is done. So result will hold the same thing as the final value of average after the function completes.
You need to declare array1 as returning double. Change its declaration to:
public static double array1(int [] b ) {
A void function -- void array1(...) -- does not return a value.
Note that there's another error in your code:
avarage = total / b.length;
The above uses integer division, meaning that the result is truncated to integer, and only then converted to double. To fix, change the line to:
avarage = total / (double)b.length;
A return type of void means that a method doesn't return anything. This is useful when you want to preform an operation on an array, but there isn't any value associated with the operation. For example, say that you wanted to swap the first and last element in an array, you could write some method like this (ignore the necessary error checking)
public void swapArrayLocs(int[] swapping){
int temp = swapping[0];
swapping[0] = swapping[swapping.length - 1];
swapping[swapping.length - 1] = temp;
}
When you call this method, you're not expecting any sort of result from it, you're expecting your program to just take care of business and continue executing.
In this case, you actually want your array1(int[]) method to make its available to the rest of the program. You do this by specifying the return type of the function, which tells the rest of the program what type of information you expect that function to return. In your case, you'd do this by changing your method declaration to.
public static double array1(int[] b){
//the same method body
}
Note how in this case the word double is inserted after static. This tells the calling function that when it executes array1, the method will give back a value of type double. Contrast this with what you had before which said that the method would not give back any type of information.

Adding/Appending elements to an array - Java

I am building a method which takes as argument, an array of decimal numbers, and a decimal threshold. The method should output all numbers from the list that are greater than the threshold.
My plan is to execute a for loop and examine each number in the array, and if that number (i) is greater than the threshold (x), to append to my result list. My problem is that I'm unable to add/append to the result list.
I have System.out.println("Nothing here"); just to help me see if it's actually going through the for loop or not, but my IDE is saying that calling list.add(a[i]); is wrong. I am a beginning programmer and not sure on how to fix this. Here is my code:
public class a10 {
public static void main(String[] args) {
double a[] = {42, 956, 3,4};
threshold(a, 2);
}
public static void threshold(double[] a, double x){
double list[] = {};
for (double i:a){
if (i<22){
list.add(a[i]);
}else{
System.out.println("Nothing here");
}
}
}
Your list is actually an array (double[]), which is NOT an object with the method add. You should treat it as a regular array (which in your case between, you have initialized to be an empty array, which means you can't set any elements in it).
What you should do is use an actual implementation of Lis instead (e.g an ArrayList) and then you can actually use the add method:
List<Double> result = new ArrayList<Double>();
for (double i:a){
if (i>x){
list.add(a[i]);
}else{
System.out.println("Nothing here");
}
}
Notice also that you had the number '22' hard coded (you should use x)
There's no method add for arrays in Java. You should declare list as:
List<Double> list = new ArrayList<Double>(); //or some other type of list

Array and methods?

I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.

Categories