💻 CSC1003 LEC10-12 Midterm Revision
复习
-
.split("")以引号内的字符为介分开字符串 -
a.equals(b)比较 a 与 b 是否相等,常用于字符串,因为 “==” 不能比较字符串 -
int[] arr = new int[n]将类实例化的语法 -
String sc = new Scanner(System.in)同上,可用于实例化 Scanner -
.nextLine()用 Scanner 的实例化对象读取一个键盘输入的字符串常见问题:如果在使用 nextInt()、nextDouble() 等方法后立刻调用 nextLine(),可能会遇到问题:nextInt() 只读取了数字部分,但换行符仍然留在输入缓冲区中,因此 nextLine() 会读取到这个残留的换行符,返回一个空字符串。解决方案:在读取整数后,消耗掉换行符,添加一个额外的 nextLine()。
int age = scanner.nextInt(); scanner.nextLine(); // 消耗掉换行符 String name = scanner.nextLine(); -
Integer.parseInt(x)用于转换字符串的数据类型至整型或浮点型,注意不可以用于小数和整数相互转换。 -
int a = (int) 4.2强行转换数字的数据类型,注意不能用于数字与字符串相互转换。 -
Math.round()四舍五入
模拟题
int[] binary = new int[1000];
int id = 0;
while (num > 0) {
binary[id++] = num % 2;
num = num / 2;
}
for (int i = id - 1; i >= 0; i--)
System.out.print(binary[i] + "");
-
What is this clip of script most possibly used for? (To convert dec to bin number.)
-
What is the largest integer possible for variable “num” in decimal? (21000-1)
import java.util.Scanner;
public class TS {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
if (isValid(a, b, c)) {
double s = calc(a, b, c);
System.out.println(s);
} else {
System.out.println("invalid");
}
scanner.close();
}
public static double calc(double a, double b, double c) {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public static boolean isValid(double a, double b, double c) {
return (a + b > c) && (a + c > b) && (b + c > a);
}
}
-
What is the output of the code if the keyboard input is “6 5 9”? (Nothing, because the scanner which is designed to take three double data cannot process a single String data.)
-
What is a possible input if the output is “6”? (e.g. “3” “4” “5”)
import java.util.*;
public class BirthdayParadox {
public static int[] dayarray(int days) {
int[] a = new int[days];
Random random = new Random();
for (int i = 0; i < days; i++) {
a[i] = random.nextInt(365) + 1;
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int count = 0;
for (int n = 0; n < 1000000; n++) {
int[] arr = dayarray(x);
Set<Integer> set = new HashSet<>();
// this transforms an array into a set
for (int day : arr) {
set.add(day);
}
if (set.size() != arr.length) {
++count;
}
}
double result = (double) count * 100 / 1000000;
System.out.println(result + "%");
}
}
- What is the intended purpose of the program? (Calculate the possibility of a duplicated date of birth amongst x people by testing with random dates 1000000 times.)
- Can “1000000” be replaced by “1e7” in the program? (No. Because a loop cannot take a float value as part of its control statement, since they are very inaccurate.)