JavaOJ常用模板

Main类

通常情况程序都需要代码中必须存在一个public class Main。不允许出现其他的public class

即,

public class Main{
    public static void main(String[] args){
           //其他代码
    }
}

输入输出与常用处理

Scanner处理输入:

一个标准的程序示例程序如下:

​
import java.util.Scanner;//导入Scanner类
 
public class Main {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);//生成Scanner对象
        while (in.hasNext()) { //相当于EOF
            int a = in.nextInt(); //读下一个整型字符串
            int b = in.nextInt();

            System.out.println(a + b);
        }
        in.close(); //用完后关闭扫描器是一个好的习惯
    }
}

​

有两种方式定义Scanner

Scanner in1 = new Scanner(System.in);

Scanner in2 = new Scanner(new BufferedInputStream(System.in));
//使用in2进行输入的时候可能会比in1快一些。

Scaner对象常用方法:

输入:

  • hasNext() //返回true或false,看有无下一个标记(字符串类型)。比如对于a b c,现在处理到a,那么下一个标记就是b。
  • next() //返回类型为String(字符串),返回下一个标记。不会读取回车换行
  • hasNextInt() //返回true或false,看有无下一个整型字符串标记。
  • nextInt() //返回类型int,将下一个整型字符串标记转化为int型返回。
  • nextBoolean() //返回类型为boolean,可以处理字符串true或者false,
  • nextDouble() //返回类型为double,可以处理字符串如1 2.3 -1.3等。
  • nextLine() //返回类型为String(字符串对象),返回一整行。会读取回车换行符

输出:

  • System.out.print();     //类似于cout<<…….;
  • System.out.println();  //类似于cout<<……<<endl;
  • System.out.printf();    //类似于C中printf的功能

读取文件:

public class Main {

		public static void readTxt(String filePath) {
			 
			  try {
			    File file = new File(filePath);
			    if(file.isFile() && file.exists()) {
			      InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
			      BufferedReader br = new BufferedReader(isr);
			      String lineTxt = null;
			      while ((lineTxt = br.readLine()) != null) {
			        System.out.println(lineTxt);
			      }
			      br.close();
			    } else {
			      System.out.println("文件不存在!");
			    }
			  } catch (Exception e) {
			    System.out.println("文件读取错误!");
			  }			 
		}
			 
			 
		public static void main(String[] args) {
			 String filePath = "E:\\test.txt";
			 readTxt(filePath);
		}
}

基本数据类型

所有的基本类型的包装类都是不可变类。

值得注意的是通过valueOf创建Integer对象的时候,如果数值在区间[-128,127],那么便返回指向IntegerCache.cache数组中已经存在的对象的引用;否则创建一个新的Integer对象。简而言之,创建Integer包装器时,有一个数值在[-128,127]的缓冲池。当创建的对象数值在[-128,127]之间时,那么不需要再在内存中开辟一个空间存储,只需要将当前对象的引用指向该缓冲池中对应的对象,这样效率上得到了提高,资源也没有浪费。

String类的常用操作

这部分内容可以参考:JAVA之String函数的20个方法详解

以及官方API文档

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值