「CodeNote」 JAVA简单语法

Posted by Dawn-K's Blog on September 22, 2019

JAVA简单语法

简介

总结一下java的简单语法,比赛用

格式

1
2
3
4
5
6
7
8
9
10
// 注意java没有 long long ,只有long
import java.io.*;
import java.util.*;
import java.math.BigInteger;
Scanner cin = new Scanner(new BufferedInputStream(System.in));
// Scanner cin = new Scanner(System.in);
while (cin.hasNext()) { // 判断是否数据结束
    int a = cin.nextInt();
    int b = cin.nextInt();
}

数组

1
int num[] = new int[100];

idea可以在使用时检测数组有没有越界.数组范围依旧是[0,99],这一点和c++一样

字符串

读入

cmd为例

1
String cmd = cin.nextLine();

但是要注意,java不支持cmd[2]等操作,需要用函数,也就是 形如System.out.printf("%c", cmd.charAt(40));来读取单个位置上的字符

字符串长度

1
System.out.println(cmd.length());

字符串的读入

1
2
String cmd=cin.next();
String cmd=cin.nextLine();

next 类似%s,读入以空格为分界

nextLine 类似getline,会读取一行,猜想应是回车符被读取后丢弃,不存入字符串中

字符串的输出

1
2
3
System.out.println(cmd); // 换行
System.out.print(cmd);   // 不换行
System.out.printf("%s", cmd);  // c++风格

大数

参考资料

大数定义

1
BigInteger two=new BigInteger("2"); // 注意双引号不能省略
1
2
3
private static BigInteger trans(int x) { // 将数值转化为大数,此处的int改成long也是可以的
    return new BigInteger(String.valueOf(x));
}

读入

1
a = cin.nextBigInteger();

运算

1
2
3
4
5
6
7
8
9
10
//  大数运算一定要用其内置的函数,用运算符号可能有问题
System.out.println(a.add(b));
System.out.println(a.subtract(b));
System.out.println(a.multiply(b));
System.out.println(a.divide(b));
System.out.println(a.mod(b));
// 大数gcd
BigInteger gcd = fz.gcd(fm);
fz = fz.divide(gcd);
fm = fm.divide(gcd);

比较

1
2
3
//  类似c++中,返回(a-b)的符号
System.out.println(a.compareTo(b));
System.out.println(b.compareTo(a));