Printing out a non-variable int in a different method in Java - java

I am trying to test whether my method to find the number of odd numbers in an array works with a System.out.println() call. I know there are no issues with the array itself, as I've printed it successfully with the toString() call. Here is my method:
public static int ODD(int[] oddnumbers)
{
int countOdds = 0;
for(int i = 0; i < oddnumbers.length; i++)
{
if(oddnumbers[i] % 2 == 1) // check if it's odd
countOdds++; // keep counting
}
return countOdds;
}
And then earlier on in the main method, I called ODD and tested it with System.out.println:
public static void main(String args[])
{
ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}
Basically the question I have is, how do I get the return countOdds into a variable that I can pass to be printed in System.out.println() in the main method?

Either use a temporary variable to store the returned value and print that, or include the method call in the print statement. For more information, see Returning a Value from a Method.

Just do :
System.out.println("And here are how many odd numbers there are in that array: " + ODD(randomThirty));

Use int countOdds = ODD(randomThirty); in your main method.
Your countOdds variable in your function is local to that function. Variables defined in functions in java are local not global.

You just need to assign the result of the ODD method call to a variable:
public static void main(String args[])
{
int result = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + result);
}

You will need to store the return result of your call to ODD in a variable, like so:
public static void main(String args[])
{
int countOdds = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}

Just save the result like any other variable:
int countOdds = ODD(randomThirty);

public static void main(String args[]) {
int countOdds = ODD(randomThirty);
...
}

To get the returned value you have to pass the argument into the method and call it.
int ans = ODD(randomThirty);
System.out.println(ans);
This is really all you need to do. You can call methods while passing an argument and assign a variable to the returned answer.

Related

What is the difference between void and return even though I can get same output on both?

i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.

Passing the array to method (using random numbers)

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.

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);
}

Why do primitive array fields print out null pointer exceptions?

public class Whatever {
static double d;
static char c;
static String[] s;
static char[] b;
static double[] dd;
static Whatever w;
static Whatever[] ww;
public static void main(String[] args) {
System.out.println(Whatever.d); //prints out 0.0
System.out.println("hi"+Whatever.c+"hi"); //prints out hi hi
System.out.println(s); //prints out null
System.out.println(b); //null pointer exception!
System.out.println(Whatever.dd);
System.out.println(Whatever.w);
System.out.println(Whatever.ww);
}
}
Why do I get a null pointer exception?
Please explain in terms of memory if you can, however I have a basic understanding of memory so don't get too in depth either.
Okay, now that you've posted your full code its easier to help! This is normally what happens when you invoke PrintStream.println with a primitive array:
String s = String.valueOf(x);
Which eventually does this:
return (obj == null) ? "null" : obj.toString();
As you can see, the possibility of the supplied object being null is explicitly handled. However, there is a specific overload on the PrintStream class, just for char arrays. Here is a rough trace of the logic:
write(cbuf, 0, cbuf.length);
Where cbuf is the given char array. As you can see, it tries to reference the character arrays length, which will blow up with an NPE if the array is not initialized. It's an odd and unfortunate inconsistency in the implementation.
So now you understand why the NPE is occurring - to fix it simply initialize the char array before trying to print it out.
There's a few problems here:
1. You're not allocating any space for `int x`
2. If you want to print the contents of `x`, it should be `x.toString()`
3. What did you expect the output to be from your sample code?
I'm guessing #3 isn't what you're actually working with, I would suggest you show your real code to get a real answer :)
Hopefully this can clear it up a bit for you.
$ cat Whatever.java
public class Whatever {
static final int MAX = 5;
int[] x = new int[MAX]; // allocate array to sizeof '5'
public Whatever() {
// do stuff
}
public void addStuff() {
for(int i=0; i<MAX; i++)
x[i] = i + 2;
}
public void printX() {
for(int i=0; i<MAX; i++)
System.out.println(i + ": " + x[i]);
}
public static void main(String[] args){
Whatever w = new Whatever(); // new instance of 'Whatever'
w.addStuff(); // add some ints to the array
w.printX(); // print out the array
// print the Array 'x'
System.out.println("Array: " + w.x);
}
}
$ java Whatever
0: 2
1: 3
2: 4
3: 5
4: 6
Array: [I#870114c
The problem is basically rooted in how PrintStream.println(...) is implemented. Except for char[], a primitive array is treated as a java.lang.Object. So the println overload used is println(Object). Underneath, printing an object involves calling the object's toString(). Hence the NPE.
If you want to be defensive of nulls, you should consider using String.valueOf(Object).

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.

Categories