Java未知个数求和,数字求和
1. 从键盘输入n个数,并完成累加求和输出。
提示: n为输入值。使用Scanner类的nextXXX()方法。
解答:
第一种:n 从键盘输入
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
sum += sc.nextInt();
}
System.out.println("sum = " + sum);
}
}
4
1 2 3 4
sum = 10
第二种:n 为任意个数,不需要提前设定
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
String str = in.nextLine();
// 输入内容以空格分割
String[] ch = str.split(" ");
for (String i : ch) {
sum += Integer.parseInt(i);
}
System.out.println("sum = " + sum);
}
}
1 2 3 4 5 6
sum = 21
2. 写出下面程序运行结果。
public class Test {
public static void main (String args[ ]){
boolean boo = false;
if(boo = true){
System.out.print("hello");System.out.print("你好");
}
else {
System.out.print("ok");System.out.print("yes");
}
}
}
解答:
hello 你好
分析:因为 boo = true 中间只有一个等号,相当于一个赋值语句,所以无论 boo 原来什么值,boo = true 这个表达式的值都是 true,所以会输出“hello 你好”