英文:
positive even number code help in java (Uncaught SyntaxError: Unexpected identifier",)
问题
以下是我的Java代码:
package javaApp;
public class EvenSum {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
for(j=0; j<=num; j++) {
if(j%2==0) {
even[j]=j;
sum=sum+j;
args[j]= Integer.toString(j);
}
evennums=String.join(",", args);
}
System.out.println(evennums);
System.out.println(sum);
}
}
通过上面的代码,我想实现一个Java应用程序,生成逗号分隔的正偶数,并计算它们的和。
英文:
below is my java code
package javaApp;
public class EvenSum {
public static void main(String[] args) {
int num = Integer.parseInt(args[0]);
int even[] = new int[num];
int sum = 0,j = 0;
String evennums = "";
for(j=0; j<=num; j++) {
if(num%2==0) {
even[j]=num;
sum=sum+num;
args[j]= Integer.toString(num);
}
evennums=String.join(",", args);
}
System.out.println(evennums);
System.out.println(sum);
}
}
with the above code, I want to achieve java application to generate comma-separated positive even numbers and also calculate their sum.
答案1
得分: 1
通过使用 java8
的 Arrays.setAll
和 Arrays.stream
方法,我们可以替换 for-loop
。
package javaApp;
import java.util.*;
public class EvenSum {
public static void main(String[] args) {
System.out.print("输入偶数个数:");
int n = new Scanner(System.in).nextInt();
int evens[] = new int[n];
Arrays.setAll(evens, i -> i * 2);
int sum = Arrays.stream(evens).sum();
System.out.println(Arrays.toString(evens));
System.out.println(sum);
}
}
或者您可以使用单个 for-loop
语句编写这个程序:
package javaApp;
import java.util.*;
public class EvenSum {
public static void main(String[] args) {
System.out.print("输入偶数个数:");
int n = new Scanner(System.in).nextInt();
int evens[] = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
evens[i] = 2 * i;
sum += 2 * i;
}
System.out.println(Arrays.toString(evens));
System.out.println(sum);
}
}
输出结果(输入为 6):
输入偶数个数:6
[0, 2, 4, 6, 8, 10]
30
英文:
By utilizing the java8
Arrays.setAll
and Arrays.stream
methods we can replace the for-loop
.
package javaApp;
import java.util.*;
public class EvenSum {
public static void main(String[] args) {
System.out.print("Input the amount of even numbers: ");
int n = new Scanner(System.in).nextInt();
int evens[] = new int[n];
Arrays.setAll(evens, i -> i * 2);
int sum = Arrays.stream(evens).sum();
System.out.println(Arrays.toString(evens));
System.out.println(sum);
}
}
Alternatively you could write this with a single for-loop
statement:
package javaApp;
import java.util.*;
public class EvenSum {
public static void main(String[] args) {
System.out.print("Input the amount of even numbers: ");
int n = new Scanner(System.in).nextInt();
int evens[] = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
evens[i] = 2 * i;
sum += 2 * i;
}
System.out.println(Arrays.toString(evens));
System.out.println(sum);
}
}
Output (with an input of 6):
Input the amount of even numbers: 6
[0, 2, 4, 6, 8, 10]
30
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论