1. 大家的.java程序都需要在一个“缺省包”(default package)下编写\运行\提交,不要去命名新的package
- 系统不支持package control, 亦即希望大家的java类都在缺省包下。
2. for, if, while等,后面包含多条语句时,需要用花括号括起来
3. Scanner对象在定义以后没有关闭,eclipse会提示一个warning. 消除这个warning的方法是在代码最后加上一句:
public class YourClass {
public static void main(String[] args) {
// ..
for (int i = 1; i <= repeat; ++ i){
// ..
}
in.close(); // 在"main的结尾,main的结尾,main的结尾"加上这句
}
}
更新
这么做的原因姑且参考一份非正式的回答Closing Streams in Java.
不正式地说:
- 对于输入流,关不关可能没什么影响
- 对于输出流:如往磁盘文件中写数据,如果这个输入流没有被显示关闭,那么数据可能还保留在缓存(buffer, 类似内存)中,未来得及写入磁盘。那么如果这个输出流没有被关闭,那么就可能造成这些数据丢失;如果我们显式地关闭了这个输出流(close the output stream explicitly), 那么缓存中的数据将被冲刷(flushed)进磁盘,确保输出的数据不会丢失。
40001. 求1+1/2+1/3+……+1/n
1. 整数 / 整数 = 整数
2. 如何进行从1到n的循环:
for (int i = 1; i <= n; ++ i) {
// todo
}
3. 答案错误,输出4.429的同学,可以计算一下1.5 + 2.929的和。
如何在每次迭代(iteration, 非正式的可以理解成“一次循环”)中改变符号:
flag = 1;
for (...) {
flag = -flag;
}
40007. 摄氏温度和华氏温度转换表
1. 如何在[x1, x2]区间内循环
可以参考上文给出的循环样例,加以修改。
2. 如何在一行中输出多个数字
可以参考之前实验的代码
3. 请原样复制题目中的给出的输出语句。
40008. 求奇数和
1. 在每次迭代中,如何读到-1处停止
1.1 可以参考我在 [Java] 实验5参考代码 -- 字母转换那题给出的for循环(不理解可以问我);或者自行回忆实验5中,是如何解决字母转换这题的。
1.2 也可参考下面给出完整代码:
import java.util.Scanner;
public class SumOfOdds {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int repeat = in.nextInt();
while (repeat-- != 0) {
int sum = 0;
// Using this for loop, we could achieve input infinite numbers,
// until we receive an non-positive one. (if <= 0, then terminate)
for (int num = in.nextInt(); num > 0; num = in.nextInt()) {
// Question mark expression, which is equivalent to
// sum = sum + num, when num is odd
// sum = sum + 0, when num is even
sum += num % 2 == 1? num: 0;
}
System.out.println(sum);
}
}
}
40009. 求最大值
看清题意
看清题意
看清题意