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文档