I've been running into the issue of calling the class that's supposed to print even and odd numbers into the main method, printing each number without overwriting the previous one. I've tried replacing the public int with public void, and it still didn't work, if you guys could help me it would help a lot. this is the code:
package myprojects;
import java.util.*;
class ArrayMethod {
private int[] Array;
public void Calc(int[] Array) {
this.Array = Array;
}
public int Sum() {
int sum = 0;
for (int i = 0; i < Array.length; i ) {
sum = Array[i];
}
return sum;
}
public double Average() {
return Sum() / Array.length;
}
public int PrintOdd() {
for (int i = 0; i < Array.length; i )
if (Array[i] % 2 != 0) {
int Odd = Array[i];
System.out.println(Odd);
}
}
public int PrintEven() {
for (int i = 0; i < Array.length; i )
if (Array[i] % 2 == 0) {
int Even = Array[i];
System.out.println(Even);
}
}
}
public class ArrayEX {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
ArrayMethod B = new ArrayMethod();
int[] A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
B.Calc(A);
System.out.println("Sum of the numbers inside array is " B.Sum());
System.out.println("Average of the numbers inside array is " B.Average());
System.out.println("Even numbers " B.PrintEven());
System.out.println("Odd Numebrs " B.PrintOdd());
}
}
CodePudding user response:
If your function return nothing, you need to use void
type method.
First you can update PrindOdd and PrintEven method to print each odd and even numbers when these functions are called:
class ArrayMethod {
...
public void PrintOdd() {
System.out.println("PrintOdd");
for (int i = 0; i < Array.length; i )
if (Array[i] % 2 != 0) {
int Odd = Array[i];
System.out.print(Odd " ");
}
}
public void PrintEven() {
System.out.println("PrintEven");
for (int i = 0; i < Array.length; i )
if (Array[i] % 2 == 0) {
int Even = Array[i];
System.out.print(Even " ");
}
System.out.println();
}
}
To print the result you need to update the way to call these functions:
public class Main {
public static void main(String[] args) {
....
B.PrintEven();
B.PrintOdd();
}
}
I hope that answers your question
CodePudding user response:
thank you to everyone who answered my question, the issue was resolved by making PrintOdd and PrintEven methods into Void type and calling it to main method outside of a print System.
my dearest thanks to @popovko57 and @zapl, who provided the solution.