java编程(从键盘输入10个数,存入数组,然后把他们显示出来,并求他们的和) 谢谢啦
1个回答
展开全部
import java.util.Scanner;
public class Du {
public static void main(String[] args) {
final int length = 10;
int[] ary = getAryFromInput(length);
int sum = 0;
System.out.print("Inputed element are: ");
for(int i = 0; i < ary.length; i++){
System.out.print(ary[i] + "\t");
sum += ary[i];
}
System.out.println("\nSum for the inputed elements are: " + sum);
}
private static int[] getAryFromInput(int length) {
int[] ary = new int[length];
int i = 0;
while(i < length){
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a number for arrary item " + (i+1) + ": ");
ary[i++] = scanner.nextInt();
}
return ary;
}
}
-----------------------
Please input a number for arrary item 1: 50
Please input a number for arrary item 2: 35
Please input a number for arrary item 3: 98
Please input a number for arrary item 4: 25
Please input a number for arrary item 5: 36
Please input a number for arrary item 6: 45
Please input a number for arrary item 7: 28
Please input a number for arrary item 8: 123
Please input a number for arrary item 9: 45
Please input a number for arrary item 10: 125
Inputed element are: 50 35 98 25 36 45 28 123 45 125
Sum for the inputed elements are: 610
public class Du {
public static void main(String[] args) {
final int length = 10;
int[] ary = getAryFromInput(length);
int sum = 0;
System.out.print("Inputed element are: ");
for(int i = 0; i < ary.length; i++){
System.out.print(ary[i] + "\t");
sum += ary[i];
}
System.out.println("\nSum for the inputed elements are: " + sum);
}
private static int[] getAryFromInput(int length) {
int[] ary = new int[length];
int i = 0;
while(i < length){
Scanner scanner = new Scanner(System.in);
System.out.print("Please input a number for arrary item " + (i+1) + ": ");
ary[i++] = scanner.nextInt();
}
return ary;
}
}
-----------------------
Please input a number for arrary item 1: 50
Please input a number for arrary item 2: 35
Please input a number for arrary item 3: 98
Please input a number for arrary item 4: 25
Please input a number for arrary item 5: 36
Please input a number for arrary item 6: 45
Please input a number for arrary item 7: 28
Please input a number for arrary item 8: 123
Please input a number for arrary item 9: 45
Please input a number for arrary item 10: 125
Inputed element are: 50 35 98 25 36 45 28 123 45 125
Sum for the inputed elements are: 610
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询