Skip to content

学习Java时遇到的问题

Q1 输出流混乱

Scanner in = new Scanner(System.in);
boolean okay;
do {
    System.out.print("Enter a number: ");
    if (in.hasNextDouble()) {
        okay = true;
    } else {
        okay = false;
        String word = in.next();
        System.err.println(word + " is not a number");
    }
} while (!okay);
double x = in.nextDouble();

当输入非数字时,会先输出 Enter a number: ,再提示错误信息,如:

Enter a number: h
Enter a number: h is not a number

Q2 starting index?

int index = fruit.indexOf('a', 2);

If the letter happens to appear at the starting index, the starting index is the answer. So fruit.indexOf('a', 5) returns 5.

What does it mean?

超出个数选最后那个?

Q3 如何在终端运行Java程序呢

Q4 debug: BigInteger Pow

public static BigInteger bigPow(BigInteger x, BigInteger n) {
    if (n.equals(BigInteger.ZERO)) {
        return BigInteger.ONE;
    }
    if (n.equals(BigInteger.ONE)) {
        return x;
    }

    BigInteger t = bigPow(x, n.divide(BigInteger.TWO));
    BigInteger result;
    if (n.divide(BigInteger.TWO).equals(BigInteger.ZERO)) {
        result = t.multiply(t);
    } else {
        result = t.multiply(t).multiply(x);
    }
    return result;
}