英文:
Need help creating a method that accepts three integers and returns an integer representing the sum of only the even integer
问题
我是Java和编程的初学者。我在筛选出偶数并将它们相加方面遇到了很多困难。我明白如何设置扫描器,并要求用户输入3个不同的整数,但是底部的部分让我完全迷失了。我在“布尔运算的禅意”部分的笔记中写着要使用(n1 % 2 != 0 && n2 % 2 != 0)
作为一个测试,但我不知道如何使用它。我想强调我是非常新手,几乎是在不到2周之前才开始编程的。我已经写了:
import java.util.*;
public class U3L8Lab3
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.print("Enter 3 Intergers:");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
System.out.println(sumOfEvens(num1, num2, num3));
}
public static int sumOfEvens(int num1, int num2, int num3)
{
}
}
英文:
I'm a beginner in Java and coding in general. I'm having a lot of trouble on filtering out even numbers and adding them together. I understood how to set up the scanner, and having the user input 3 different int's, but the bottom segment is where I'm completely lost. My notes in "Boolean Zen" section say to use (n1 % 2 != 0 && n2 % 2 != 0)
as a test, but I can't figure out how to use it. I should repeat that I am very new, and started coding barely even 2 weeks ago. I've written:
import java.util.*;
public class U3L8Lab3
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.print("Enter 3 Intergers:");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
System.out.println(sumOfEvens(num1, num2, num3));
}
public static int sumOfEvens(int num1, int num2, int num3)
{
}
答案1
得分: 0
你的任务是对偶数进行求和。根据我的理解,如果用户必须输入3个奇数,那么结果应该为0 - 这是我在提供答案时的假设。
首先,你需要确定哪些数字是偶数 - 这就是取模(%)功能的作用。如果任何数字模2的结果为0,那么它是偶数。所以:
public static int sumOfEvens(int num1, int num2, int num3)
{
int sum = 0;
if (num1 % 2 == 0) {
sum += num1;
}
if (num2 % 2 == 0) {
sum += num2;
}
if (num3 % 2 == 0) {
sum += num3;
}
return sum;
}
这可能不是最优雅的解决方案,但我希望你能理解要点。
英文:
So you are tasked at summing the even numbers only. From what I understand, if the user had to input 3 uneven numbers, then the result should be 0 - that is the assumption I will make when providing you my answer.
Firstly, you need to determine which of the numbers are even - this is what the mod (%) functionality is for. If any number mod 2 results in 0, it means it is even. So:
public static int sumOfEvens(int num1, int num2, int num3)
{
int sum = 0;
if (num1 % 2 == 0) {
sum += num1;
}
if (num2 % 2 == 0) {
sum += num2;
}
if (num3 % 2 == 0) {
sum += num3;
}
return sum;
}
Not the most elegant solution, but I hope you get the gist of it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论