关于Java的基本程序
由于以前自学了一段时间Java,但是缺少实操,过了一两个月,就又全忘了,现在决定重新捡起之前忘掉的部分。所以从一个基本的Java程序写起,后面回一步一步的加上很多的基础知识的内容,做一个备用库。
基本的一个Java程序
import java.io.*;
public class EmployeeTest{
public static void main(String []args){
Employee empOne= new Employee("RUNOOB1");
Employee empTwo= new Employee("RUNOOB2");
empOne.empAge(26);
empOne.empDesignation("高级工程师");
empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21);
empTwo.empDesignation("菜鸟工程师");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
- 第一个public class定义与文件名字相同,第二个里面的public static void main,是主函数,固定格式,前面的import 是引用的包,自己写的包,要写清楚路径,
- 输出用 system.out.println
- 输入有三种方法,但是并不推荐用第一种
– 从控制台接收一个字符,然后将其打印出来(只能接收一个字符)
public static void main(String [] args) throws IOException{
System.out.print(“Enter a Char:”);
char i = (char) System.in.read();
System.out.println(“your char is :”+i);
}
}
– 从控制台接收一个字符串,然后将其打印出来。在这个题目中,我们需要用到BufferedReader类和InputStreamReader类
import java.io.*;
public class BRRead {
public static void main(String args[]) throws IOException {
String c;
// 使用 System.in 创建 BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入字符, 按下 'q' 键退出。");
// 读取字符
do {
//c = (char) br.read();
c=(String) br.readLine();
System.out.println(c);
} while (!c.equals( "q"));
}
}
– 用Scanner类
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入你的姓名:”);
String name = sc.nextLine();
System.out.println(“请输入你的年龄:”);
int age = sc.nextInt();
System.out.println(“请输入你的工资:”);
float salary = sc.nextFloat();
System.out.println(“你的信息如下:”);
System.out.println(“姓名:”+name+“\n”+“年龄:”+age+“\n”+“工资:”+salary);
}