I went to a programming school in February of this year and got a job at an IT company in July. I wanted to output the language I learned, so I decided to start posting articles! This time I will post an article about Java that I did not study at programming school.
This time I tried it in a comprehensive development environment called "Eclipse". Please refer to this article to build a development environment.
Creating a Java development environment with Eclipse (Mac version)
class Main {
public static void main(String[] args) {
int[] numbers = {1, 5, 8, 10, 13, 18};
int oddSum = 0;
int evenSum = 0;
for (int number : numbers) {
if (number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}
}
System.out.println("The sum of odd numbers is" + oddSum + "is");
System.out.println("The sum of even numbers" + evenSum + "is");
}
}
I will explain the above code in order from the top!
Define the main method in the Main class.
class Main {
public static void main(String[] args) {
Write some integers you like in the variable number in an array with int type elements.
int[] numbers = {1, 5, 8, 10, 13, 18};
Define variables oddSum and evenSum in int type and put 0 in both variables.
int oddSum = 0;
int evenSum = 0;
Repeat the process with the for statement and create a conditional branch with the if statement. This time we will use something called an "extended for statement".
for(Data type variable:Array name) {
Iterative processing;
}
Enter the int type variable number and the array numbers in the statement. In the if statement, condition "when number is even".
+ =
Means that, for example, ʻa + = b is the same as ʻa = a + b
.for (int number : numbers) {
if (number % 2 == 0) {
evenSum += number;
} else {
oddSum += number;
}
}
And finally I will output it!
System.out.println("The sum of odd numbers is" + oddSum + "is");
System.out.println("The sum of even numbers" + evenSum + "is");
Don't forget the closing brackets for the Main class and main methods! ]
}
}
Execution result
The sum of odd numbers is 19.
The sum of even numbers is 36
Is displayed, it is successful!
There is a possibility that ;
is missing, so please check it!
Everyone who is studying programming, although I am also studying acclaim Let's be patient and work together to make coding fun! Thank you for watching till the end! !! !!
Recommended Posts