文章目录
输入与输出
1.输入
- 基本输入
Scanner sc=new Scanner(System.in);
Scanner in = new Scanner (new BufferedInputStream(System.in));//更快
- 输入格式
1. 只有一组数据:
Scanner sc=new Scanner(System.in);
int a=s.nextInt();
int b=s.nextInt();
2. 输入多组数据,不告知组数,也没有截止符
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){//判断是否数据结束
int a=s.nextInt();
int b=s.nextInt();
}
3. 输入多组数据,不告知组数,截止符为ch
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int c=sc.nextInt();
if(c==ch) return;
}
4. 输入多组数据,第一行是整数N,表示有N组数据,之后每行表示一组数据
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(int i=0;i<n;i++){
int a=sc.nextInt();
int b=sc.nextInt();
}
5.养成良好习惯,最后关闭输入流
sc.close();
- 输入挂(当输入规模达到106的时候,就需要输入挂,否则很有可能超时)
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
out.close();
}
}
class InputReader
{
BufferedReader buf;
StringTokenizer tok;
InputReader()
{
buf = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while(tok == null || !tok.hasMoreElements())
{
try
{
tok = new StringTokenizer(buf.readLine());
}
catch(Exception e)
{
return false;
}
}
return true;
}
String next()
{
if(hasNext()) return tok.nextToken();
return null;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
BigInteger nextBigInteger()
{
return new BigInteger(next());
}
BigDecimal nextBigDecimal()
{
return new BigDecimal(next());
}
}
2.输出
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));//使用缓存加速,比直接使用System.out快
out.print(n)//不换行
out.println(n); //自动换行
out.printf("%.2f\n", ans); // 与c语言中printf用法相同
3.文件读写
- 读
try {
FileInputStream fip = new FileInputStream("D:\\java\\maze.txt"); // str1为读取的文件路径
BufferedReader bfr = new BufferedReader(new InputStreamReader(fip));
// 如果单纯的使用fip.read()一个字节一个字节的读取,则比较耗费时间,
//采用BufferedReader则可以一行行的读取
} catch (IOException e) {
e.printStackTrace();
}
- 写
File file = new File(str);
try {
FileOutputStream fop = new FileOutputStream(file); // 创建输出流对象
String s = "hello,word!";
byte[] b = new byte[1024];
b = s.getBytes(); // 将String类型的s字符串以字符的形式赋给字节数组
try {
fop.write(b, 0, b.length);
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
大整数与高精度
1.大整数BigInteger
import java.math.BigInteger;
//主要有以下方法可以使用:
BigInteger add(BigInteger other) //加
BigInteger subtract(BigInteger other)//减
BigInteger multiply(BigInteger other) //乘
BigInteger divide(BigInteger other)//除
BigInteger [] dividedandRemainder(BigInteger other) //取余,数组第一位是商,第二位是余数
BigInteger pow(int other)//幂
BigInteger mod(BigInteger other) //模
BigInteger gcd(BigInteger other) //公约数
int compareTo(BigInteger other) //比较,小于返回负,等于返回0,大于返回正
static BigInteger valueOf(long x)//转型
//输出数字时直接使用 System.out.println(a) 即可
2.高精度BigDecimal
BigDecimal add(BigDecimal other)//加
BigDecimal subtract(BigDecimal other)//减
BigDecimal multiply(BigDecimal other)//乘
BigInteger divide(BigInteger other)//除
//除数,保留小数位数,保留方法四舍五入
BigDecimal divide(BigDecimal divisor, int scale, BigDecimal.ROUND_HALF_UP)
//用于格式化小数点,setScale(1)表示保留一位小数,默认四舍五入
BigDecimal.setScale()
字符串与进制转换
1.字符串基本操作
String s = "abcdefg";
char [] ch;
ch = s.toCharArray(); // 字符串转换为字符数组.
for (int i = 0; i < ch.length; i++){
ch[i] += 1; //字符数组可以像C++ 一样操作
}
System.out.println(ch); // 输出为“bcdefgh”.
2.进制转换
int num=150;
int Bnum=0b11;//二进制 3
int Onum=017;//八进制 15
int Hnum=0x1A;//十六进制 26
String numB=Integer.toBinaryString(num);//二进制 10010110
String numO=Integer.toOctalString(num);//八进制 226
String numH=Integer.toHexString(num);//十六进制 96
数据结构
1.set
在Java中主要使用HashSet类进行去重,HashSet中元素是无序的(可以理解为顺序不确定),LinkedHashSet是遍历时是按照插入顺序排序的,TreeSet是升序排列的,最接近C++中的set,但是在没有要求元素有序的情况下,Java中一般是使用HashSet的。下节的map的情况与之类似。
Set<Integer> set = new HashSet<Integer>();//无序,对应标准C++的unordered_set
set.add(1);//添加元素
System.out.println(s.contains(1));//查询
set.remove(1);//删除元素
如果使用有序的TreeSet,还可以进行如下的查找操作:
TreeSet<Integer> s = new TreeSet<Integer>();
//使用s.add(1);等把1-5都加进去,代码省略
System.out.println(s.ceiling(3)); //>=3的最小的数,输出3
System.out.println(s.floor(3)); //<=3的最大的数,输出3
System.out.println(s.higher(3)); //>3的最小的数,输出4
System.out.println(s.lower(3)); //<3的最大的数,输出2
System.out.println(s.headSet(3)); //<3的数组成的TreeSet,输出[1, 2]
System.out.println(s.tailSet(3)); //>=3的数组成的TreeSet,输出[3, 4, 5]
System.out.println(s.subSet(2,4)); //>=2且<4的数组成的TreeSet,输出[2, 3]
System.out.println(s.subSet(2,false,4,true)); //>2且<=4的数组成的TreeSet,输出[3, 4]
2.map
如果只需要C++中map的key对value的映射功能,而不关心顺序,Java中一般使用HashMap类,如需有序,与Set类似,有LinkedHashMap、TreeMap等类可以使用。
例子如下:
//定义与存取
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 111);
System.out.println(m.get(1));//如果get一个不存在的key,则返回null,否则返回对应value
//用迭代器遍历
Iterator<Entry<Integer, Integer>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<Integer, Integer> e = it.next();
System.out.println(e.getKey() + " " + e.getValue());
}
//根据key删除元素
map.remove(1);
//用for-each循环遍历
for(Map.Entry<Integer, Integer> e:map.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
3.vector(list)
在Java中,C++的vector对应的是ArrayList类,list对应LinkedList类,其基本用法跟ArrayList类似,只是实现上使用链表而不是数组,从而在一些操作的复杂度上有变化,将下文代码的ArrayList改为LinkedList可直接使用,故在此省略。(其实它还实现了C++中queue、deque、stack等的功能,有使用链表实现的这些数据结构的需求的话可以用它)虽然Java中也有Vector这个类,但它是历史遗留下来的,不建议使用。
ArrayList<Integer> a = new ArrayList<Integer>();//创建一个储存整形的ArrayList
a.add(1); //向其最后添加“1”这个元素
a.add(2); //向其最后添加“2”这个元素
a.add(1, 3); //向其index为1的位置添加“3”这个元素,原来index为1及后续元素向后顺延一位;index以0起始
a.remove(1); //删除index为1的元素,注意不是删除值为1的元素
a.remove(Integer.valueOf(1)); //删除值为1的元素
a.set(0, 1); //将index为0的元素的值改成1
System.out.println(a.get(0)); //取出index为0的元素并输出,结果为1
4.priority_queue
在Java中,C++的priority_queue对应的是PriorityQueue类。示例如下:
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();//定义一个储存整形的优先队列,值小的在前
pq.offer(1);//将1添加进去,不能用add(),虽然能过编译!!!
pq.offer(3);
pq.offer(2);
//跟C++的不同,你可以遍历它,但是你会发现遍历的结果并不是有序……此处输出1 3 2
for(int num:pq){
System.out.print(num + " ");
}
System.out.println(pq.peek());//取出第一个值但不删除它
System.out.println(pq.poll());//取出第一个值并且删除它
System.out.println(pq);//输出剩下的元素,结果是[2, 3],但是并不是排序之后的!!!这只是巧合,不信试试其他值
5.queue
C++中的queue在Java中可以使用ArrayDeque类,实例如下:
ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
queue.offer(1);//成功返回true,失败返回false,不要写成push,实现栈时使用
queue.offer(2);
queue.offer(3);
System.out.println(queue.peek());//取出第一个值但不删除它
while (!queue.isEmpty()) {
System.out.println(queue.pop());//取出第一个值并且删除它
}
6.stack
C++中的stack在Java中使用ArrayDeque类。Java也有Stack类,但也是历史遗留问题。语法基本相同,示例如下:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
stack.push(1);//此处采用push
stack.push(2);
stack.push(3);
System.out.println(stack.peek());//查看栈顶元素
while(!stack.isEmpty()){
System.out.println(stack.pop());//弹出栈顶元素
}