在这里插入代码片
public class first {
public static void main(String[] args) {
System.out.println("this is the first java program");
}
}
/**************************************************************************************/
import javax.swing.*;
public class firstGUI {
public static void main(String[] args) {
String output;
output = "java语言";
JOptionPane.showMessageDialog(null,output);
}
}
/**************************************************************************************/
public class BirthDay {
public static void main(String[] args) {
int year,month,day;
year = 2011;
month = 8;
day = 10;
System.out.println("生日是" + year + "年" + month + "月" + day + "日");
}
}
/**************************************************************************************/
public class BreakTest0 {
public static void main(String[] args) {
for(int i=0; i<4; i++){
System.out.println("loop1");
for(int j=0; j<4; j++){
System.out.println(" " + i + " " + j);
if( j==1 ) {
break;
}
System.out.println("loop2");
}
}
}
}
/**************************************************************************************/
public class BreakTest {
public static void main(String[] args) {
L2: for (int i=0; i<4; i++){
System.out.println("loop1");
for (int j=0; j<4; j++){
System.out.println(" " + i + " " + j);
if( j==1){
break L2;
}
System.out.println("loop2");
}
System.out.println("out of all loops");
}
}
}
/**************************************************************************************/
public class ContinueTest {
public static void main(String[] args) {
L2: for(int i=0; i<4; i++){
System.out.println("loop1");
for(int j=0; j<4; j++){
System.out.println(" " + i + " " +j);
if( j==1 ) {
continue L2;
}
System.out.println("loop2");
}
}
System.out.println("out of all loops");
}
}
/**************************************************************************************/
public class BirthTest {
public class BirthDay{
int year,month,day;
}
public static void main(String[] args) {
BirthTest birthTest = new BirthTest();
BirthDay tombth = birthTest.new BirthDay();
BirthDay marybth = birthTest.new BirthDay();
tombth.year = 1999;
tombth.month = 9;
tombth.day = 10;
marybth.year = 2000;
System.out.println("tom was born in" + tombth.year);
System.out.println("mary was born in" + marybth.year);
}
}
/**************************************************************************************/
public class BirthTest1 {
int year,month,day;
public static void main(String[] args) {
BirthTest1 tombth,marybth;
tombth = new BirthTest1();
marybth = new BirthTest1();
tombth.year = 1999;
tombth.month = 9;
tombth.day = 10;
marybth.year = 2000;
System.out.println("Tom was born in " + tombth.year);
System.out.println("mary was born in " + marybth.year);
}
}
/**************************************************************************************/
public class BirthTest2 {
public class BirthDay{
int year,month,day;
void setBirthDay(int y,int m,int d){
year = y;
month = m;
day = d;
}
String showBirthDay(){
return ("BirthDay(yy/mm/dd): " + year + "," + month + "," + day);
}
}
public static void main(String[] args) {
BirthTest2 birthTest2 = new BirthTest2();
BirthDay tombth = birthTest2.new BirthDay();
BirthDay marybh = birthTest2.new BirthDay();
tombth.setBirthDay(1999,9,10);
marybh.setBirthDay(2000,8,25);
System.out.println("Tom's Birthday: " + tombth.showBirthDay());
System.out.println("mary's Birthday: " + marybh.showBirthDay());
}
}
/**************************************************************************************/
public class BirthDay1 {
int year,month,day;
void setBirthDay(int y, int m, int d){
year = y;
month = m;
day = d;
}
String showBirthDay(){
return ("BirthDay(yy/mm/dd): " + year + "," + month + "," + day);
}
void printBirthDay(){
System.out.println("BirthDay: " + showBirthDay());
}
}
/**************************************************************************************/
public class ParamTest {
public class BirthDay{
int year,month,day;
}
void test(BirthDay b1,BirthDay b2,int nn){
b1.day = nn;
nn = 26;
b2 = new BirthDay();
b2.day = 10;
}
public static void main(String[] args) {
ParamTest paramTest = new ParamTest();
int n=10;
BirthDay bth1 = paramTest.new BirthDay();
BirthDay bth2 = paramTest.new BirthDay();
bth1.day = 1;
bth2.day = 2;
System.out.println("before test: ");
System.out.println(bth1.day);
System.out.println(bth2.day);
System.out.println(n);
paramTest.test(bth1,bth2,n);
System.out.println("after test: ");
System.out.println(bth1.day);
System.out.println(bth2.day);
System.out.println(n);
}
}
/**************************************************************************************/
public class SumTest {
public class CalSum{
void sum(short i,short j){
System.out.println("short: " + (i + j));
}
void sum(int i, int j){
System.out.println("int: " + (i + j));
}
}
public static void main(String[] args) {
SumTest sumTest = new SumTest();
CalSum cs = sumTest.new CalSum();
cs.sum(3,34);
short x = 3 , y = 34;
cs.sum(x,y);
}
}
/**************************************************************************************/
public class SumTest2 {
public class CalSum1{
void sum(){
System.out.println("nothing");
}
void sum(int i ,int j){
System.out.println("int: " + (i + j));
}
}
public static void main(String[] args) {
SumTest2 sumTest2 = new SumTest2();
CalSum1 cs = sumTest2.new CalSum1();
cs.sum(3,34);
short x = 3, y = 34;
cs.sum(x,y);
}
}
/**************************************************************************************/
public class BankBookTest {
public class BankBook{
long bnum;
int password;
double balance;
void stbnum(long bn){
bnum = bn;
}
void setPassword(int pw){
password = pw;
}
void addmoney(double am){
balance = balance + am;
}
boolean checkpw(int pw){
if(password == pw){
return true;
}else {
return false;
}
}
boolean getmoney(int pw, double gm){
if(checkpw(pw) & (gm <= balance)){
balance = balance - gm;
return true;
}
return false;
}
double getBalance(){
return balance;
}
}
public static void main(String[] args) {
BankBookTest bankBookTest = new BankBookTest();
BankBook bankBook = bankBookTest.new BankBook();
bankBook.balance = 1000;
System.out.println("balance " + bankBook.balance);
bankBook.password = 123456;
System.out.println("passwd " + bankBook.password);
bankBook.balance = bankBook.balance - 2000;
System.out.println("balance " + bankBook.balance);
}
}
/**************************************************************************************/
public class BankBookTest {
public class BankBook{
private long bnum;
private int passwd;
private double balance;
void setnum(long bn){
bnum = bn;
}
void setPasswd(int pw){
passwd = pw;
}
void addmoney(double am){
balance = balance + am;
}
boolean checkpw(int pw){
if(passwd == pw){
return true;
}else {
return false;
}
}
boolean getmoney(int pw,double gm){
if(checkpw(pw) && (gm <= balance)){
balance = balance - gm;
return true;
}
return false;
}
double getbalance(){
return balance;
}
}
public static void main(String[] args) {
BankBookTest bankBookTest = new BankBookTest();
BankBook bk1 = bankBookTest.new BankBook();
bk1.addmoney(1000);
System.out.println("balance " + bk1.getbalance());
bk1.setPasswd(123456);
if(!(bk1.getmoney(123456,2000))){
System.out.println("密码错误或余额不足");
}
System.out.println("balance " + bk1.getbalance());
}
}
/**************************************************************************************/
public class BirthTest3 {
public class BirthDay{
int year,month,day;
BirthDay(int y, int m, int d){
year =y;
month = m;
day = d;
}
String showBirthDay(){
return ("BirthDay(yy/mm/dd): " + year + "," + month + "," + day);
}
}
public static void main(String[] args) {
BirthTest3 birthTest3 = new BirthTest3();
BirthDay tombth = birthTest3.new BirthDay(1999,9,10);
BirthDay marybth = birthTest3.new BirthDay(2000,8,25);
System.out.println("Tom's BirthDay: " + tombth.showBirthDay());
System.out.println("mary's BirthDay: " + marybth.showBirthDay());
}
}
/**************************************************************************************/
public class BirthTest4 {
public class BirthDay{
int year,month,day;
BirthDay(int y,int m,int d){
year = y;
month = m;
day = d;
}
BirthDay(int m,int d){
year = 2011;
month = m;
day = d;
}
BirthDay(){
year = 2011;
month = 9;
day = 10;
}
String showBirthday(){
return ("BirthDay(yy/mm/dd): " + year + "," + month + "," + day);
}
}
public static void main(String[] args) {
BirthTest4 bt = new BirthTest4();
BirthDay tombth = bt.new BirthDay();
BirthDay marybth = bt.new BirthDay(2000,8,25);
BirthDay jackbth = bt.new BirthDay(1,25);
System.out.println("tom's birthday: " + tombth.showBirthday());
System.out.println("mary's birthday: " + marybth.showBirthday());
System.out.println("jack's birthday: " + jackbth.showBirthday());
}
}
/**************************************************************************************/
public class BirthDay {
int year,month,day;
BirthDay(int y,int m,int d){
year = y;
month = m;
day = d;
}
BirthDay(int m,int d){
this(2011,m,d);
}
BirthDay(){
this(2011,9,10);
}
String showBirthday(){
return ("BirthDay(yy/mm/dd): " + year + "," + month + "," +day);
}
}
/**************************************************************************************/
public class VarTest {
public class Var{
int x,y;
void aa(){
int x,y;
x = 1;
y = 2;
this.x = 3;
System.out.println("aa:x = " + x + "; y = " + y + "; this,x = " + this.x);
}
void bb(){
int y = 4;
this.y = 5;
System.out.println("bb: y = " + y + ";this.y = " + this.y);
}
}
public static void main(String[] args) {
VarTest varTest = new VarTest();
Var var = varTest.new Var();
var.aa();
var.bb();
}
}
/**************************************************************************************/
public class Point_Line {
public class MyPoint{
int x,y;
MyPoint(int x1,int y1){
x = x1;
y = y1;
}
double getd(MyLine line){
double d = Math.abs(line.a * x + line.b * y + line.c)/Math.sqrt(line.a * line.a + line.b * line.b);
return (d);
}
}
public class MyLine{
MyPoint p1,p2;
double a,b,c;
MyLine(MyPoint p1,MyPoint p2){
//(y1 - y2) * X + (x2 - x1) * Y + x1 * y2 - x2 * y1 = 0
a = p1.y - p2.y;
b = p2.x - p1.x;
c = p1.x * p2.y - p2.x * p1.y;
}
public void pass(MyPoint p){
double h = p.getd(this);
if(h < 0.2){
System.out.println("Alomost pass line");
}else {
System.out.println("Not paass line");
}
}
}
public static void main(String[] args) {
Point_Line pline = new Point_Line();
MyPoint p1 = pline.new MyPoint(1,1);
MyPoint p2 = pline.new MyPoint(2,2);
MyPoint p3 = pline.new MyPoint(4,4);
MyPoint p4 = pline.new MyPoint(2,4);
MyLine line = pline.new MyLine(p1,p2);
System.out.println("p3: ");
line.pass(p3);
System.out.println("p4: ");
line.pass(p4);
}
}
/**************************************************************************************/
public class Sttest0 {
public class Student{
String studentNo,name;
void showInfo(){
System.out.println("学号: " + studentNo);
System.out.println("姓名: " + name);
}
}
public class Collegian extends Student{
String major;
}
public static void main(String[] args) {
Sttest0 sttest0 = new Sttest0();
Collegian collegian = sttest0.new Collegian();
collegian.studentNo = "150810123";
collegian.name = "张三";
collegian.major = "计算机";
collegian.showInfo();
}
}
/**************************************************************************************/
public class Sttest {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn;
name = nm;
}
void showInfo(){
System.out.println("学号: " + studentNo);
System.out.println("姓名: " + name);
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
@Override
void showInfo(){
super.showInfo();
System.out.println("专业: " + major);
}
}
public static void main(String[] args) {
Sttest sttest = new Sttest();
Student student = sttest.new Student("651003","王五");
student.showInfo();
student.studentNo = "150811203";
Collegian collegian = sttest.new Collegian("150810123","张三","计算机");
collegian.showInfo();
}
}
/**************************************************************************************/
//这一段是无法执行的,和下面一段对比执行。
public class Sttest1 {
public class Student{
private String studentNo,name;
void showInfo(){
System.out.println("学号: " + studentNo);
System.out.println("姓名: " + name);
}
}
public class Collegian extends Student{
String major;
@Override
void showInfo(){
System.out.println("姓名: " + name);
}
}
public static void main(String[] args) {
Sttest1 sttest1 = new Sttest1();
Collegian collegian = sttest1.new Collegian();
collegian.studentNo = "150810123";
collegian.name = "张三";
collegian.major = "计算机";
collegian.showInfo();
}
}
public class Sttest2 {
public class Student{
private String studentNo,name;
void setInfo(String sn,String nm){
studentNo = sn;
name = nm;
}
void showInfo(){
System.out.println("学号: " + studentNo);
System.out.println("姓名: " + name);
}
}
public class Collegian extends Student{
String major;
void setInfo(String sn,String nm,String mj){
super.setInfo(sn, nm);
major = mj;
}
@Override
void showInfo(){
super.showInfo();
System.out.println("姓名: " + major);
}
}
public static void main(String[] args) {
Sttest2 sttest2 = new Sttest2();
Collegian collegian = sttest2.new Collegian();
collegian.setInfo("150810123","张三","计算机");
collegian.showInfo();
}
}
/**************************************************************************************/
public class Test1 {
public class Base{
public void amethod(int i){
System.out.println("i = " + i);
}
}
public class Scope extends Base{
public void amethod(int i,float f){
System.out.println("i = " + i);
System.out.println("f = " + f);
}
}
public static void main(String[] args) {
Test1 test1 = new Test1();
Scope s1 = test1.new Scope();
s1.amethod(10);
s1.amethod(10,2.3f);
}
}
/**************************************************************************************/
public class Test2 {
public class Father{
String var = "Father's variable";
}
public class Son extends Father{
String var = "Son's variable";
void test(){
System.out.println("var is " + var);
System.out.println("super.var is " + super.var);
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
Son son = test2.new Son();
son.test();
}
}
/**************************************************************************************/
public class Array1 {
public class D_Card{
long card_num;
double balance;
D_Card(){}
D_Card(long n,double b){
card_num = n;
balance = b;
}
}
public static void main(String[] args) {
Array1 array1 = new Array1();
D_Card d_card [];
d_card = new D_Card[2];
System.out.println("d_card = " + d_card);
System.out.println(d_card[0]);
}
}
/**************************************************************************************/
public class Test2 {
public class Father{
String var = "Father's variable";
}
public class Son extends Father{
String var = "Son's variable";
void test(){
System.out.println("var is " + var);
System.out.println("super.var is " + super.var);
}
}
public static void main(String[] args) {
Test2 test2 = new Test2();
//Son son = test2.new Son();
Son son[];
son = new Son[8];
son[0] = test2.new Son();
son[0].test();
//System.out.println(son[0]);
}
}
/**************************************************************************************/
public class Array21 {
public static void main(String[] args) {
int y[][];
y = new int[2][3];
System.out.println("y = " + y);
System.out.println("y[0] = " + y[0]);
System.out.println("y[1] = " + y[1]);
System.out.println("y.length = " + y.length);
System.out.println("y[0].length = " + y[0].length);
System.out.println("y[1].length = " + y[1].length);
}
}
/**************************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Io1 {
public static void main(String[] args) {
String s = null;
int n = 0;
try {
System.out.println("输入年龄: " );
InputStream in;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
n = Integer.parseInt(s);
}catch (IOException e){
}
System.out.println("年龄: " + n);
}
}
/**************************************************************************************/
import javax.swing.*;
public class Iow1 {
public static void main(String[] args) {
String input1,input2,output;
int result;
input1 = JOptionPane.showInputDialog("请输入姓名");
input2 = JOptionPane.showInputDialog("请输入年龄");
output = input1 + input2;
JOptionPane.showMessageDialog(null,output);
}
}
/**************************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Arr2 {
public class Arr{
int a[];
Arr(){}
Arr(int n){
a = new int[n];
}
int getmax(){
int max = a[0];
for (int i=0; i<a.length; i++){
if(a[i]>max){
max = a[i];
}
}
return max;
}
int getmin(){
int min = a[0];
for (int i=0; i<a.length; i++){
if(a[i]<min){
min = a[i];
}
}
return min;
}
int getsum(){
int sum=0;
for (int i=0; i<a.length; i++){
sum = sum + a[i];
}
return sum;
}
int getaverage(){
int aver = getsum()/a.length;
return aver;
}
}
public static void main(String[] args) {
Arr2 Ar = new Arr2();
String s = null;int n = 0; Arr ab = null;
try {
System.out.println("输入数组元素个数n: ");
InputStream in;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
n = Integer.parseInt(s);
ab = Ar.new Arr(n);
for(int i=0; i<ab.a.length; i++){
System.out.println("输入a[" + i + "]:");
s = br.readLine();ab.a[i] = Integer.parseInt(s);
}
}catch (IOException e){
System.out.println(e.toString());
}
System.out.println("max = " + ab.getmax());
System.out.println("min = " + ab.getmin());
System.out.println("getaverage = " + ab.getaverage());
System.out.println("sum = " + ab.getsum());
}
}
/**************************************************************************************/
import javax.swing.*;
public class Arr2w {
public class Arr{
int a[];
Arr(){}
Arr(int n){
a = new int[n];
}
int getmax(){
int max = a[0];
for (int i=0; i<a.length; i++){
if(a[i]>max){
max = a[i];
}
}
return max;
}
int getmin(){
int min = a[0];
for (int i=0; i<a.length; i++){
if(a[i]<min){
min = a[i];
}
}
return min;
}
int getsum(){
int sum=0;
for (int i=0; i<a.length; i++){
sum = sum + a[i];
}
return sum;
}
int getaverage(){
int aver = getsum()/a.length;
return aver;
}
}
public static void main(String[] args) {
Arr2w Ar = new Arr2w();
String s = null;int n = 0; Arr ab = null;
try {
s = JOptionPane.showInputDialog("输入n: ");
n = Integer.parseInt(s);
ab = Ar.new Arr(n);
for(int i=0; i<ab.a.length; i++){
s = JOptionPane.showInputDialog("输入a[" + i + "]: ");
ab.a[i] = Integer.parseInt(s);
}
}catch (Exception e){
System.out.println(e.toString());
}
JOptionPane.showMessageDialog(null,"max= " + ab.getmax());
JOptionPane.showMessageDialog(null,"average= " + ab.getaverage());
}
}
/**************************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class St {
public class Pst{
Student st[] = new Student[3];
void mkst(){
String sn = null,nm = null,ss = null,as = null;
int a = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i=0; i<st.length; i++){
System.out.println("StudentNo: ");
sn = br.readLine();
System.out.println("StudentName: ");
nm = br.readLine();
System.out.println("StudentSex: ");
ss = br.readLine();
System.out.println("StudentAge: ");
as = br.readLine();
a = Integer.parseInt(as);
st[i] = new Student(sn,nm,ss,a);
}
}catch (IOException e){
System.out.println(e.toString());
}
}
void sortp(){
int i=0,j=0,flag=0;
Student t = null;
for(i=0;i<st.length;i++){
flag=0;
for (j=0;j<st.length-i-1;j++){
if(st[j].age>st[j+1].age){//需要交换时,要交换整个对象
t = st[j];
st[j] = st[j+1];
st[j+1] = t;
flag = 1;
}
}
if(flag ==0 ){//flag是冒泡排序已经完成的标志
break;
}
}
for (i=0;i<st.length;i++){
System.out.println(st[i].toString());
}
}
void search(String sn){
int i=0;
for(i=0;i<st.length;i++){
if(st[i].studentNo.equals(sn)){
st[i].updateage(st[i].getAge() + 1);
System.out.println(st[i].toString());
break;
}
}
}
}
public class Student{
String studentNo,name,sex;
int age;
String getStudentNo(){
return studentNo;
}
String getName(){
return name;
}
String getSex(){
return sex;
}
int getAge(){
return age;
}
void updateage(int a){
age = a;
}
Student(String sn,String nm,String psex,int a){
studentNo = sn;
name = nm;
sex = psex;
age = a;
}
@Override
public String toString(){
return (studentNo + ";" + name + ";" + sex + ";" + age + ";");
}
}
public static void main(String[] args) {
St st = new St();
int i;
String sn;
Pst pst = st.new Pst();
pst.mkst();
pst.sortp();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("StudentNo: ");
sn = br.readLine();
pst.search(sn);
}catch (IOException e){
System.out.println(e.toString());
}
}
}
/**************************************************************************************/
public class Sttest1 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo =sn;
name = nm;
}
void showInfo(){
System.out.println("学号: " + studentNo);
System.out.println("姓名: " + name);
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
@Override
void showInfo(){
super.showInfo();
System.out.println("专业: " + major);
}
}
public static void main(String[] args) {
Sttest1 sttest1 = new Sttest1();
Student s1 = sttest1.new Student("150810103","王五");
s1.showInfo();
Student s2 ;
s2= sttest1.new Collegian("150810123","张三","计算机");
System.out.println("s2:姓名:" + s2.name);
System.out.println("专业:" + ((Collegian)s2).major);
//System.out.println("专业:" + s2.major);//报错
s2.showInfo();
}
}
/**************************************************************************************/
public class Sttest3 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void main(String[] args) {
Sttest3 sttest3 = new Sttest3();
Student s[] = new Student[2];
s[0] = sttest3.new Student("150810103","王五");
showInfo(s[0]);
s[1] = sttest3.new Collegian("150810123","张三","计算机");
showInfo(s[1]);
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
}
/**************************************************************************************/
public class Convert1 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
public static void main(String[] args) {
Convert1 convert1 = new Convert1();
Student student = convert1.new Student();
Collegian collegian = convert1.new Collegian("150810123","张三","计算机");
student = collegian;
showInfo(student);
}
}
/**************************************************************************************/
public class Convert2 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
public static void main(String[] args) {
Convert2 convert2 = new Convert2();
Student student = convert2.new Student("150810123","张三");
Collegian collegian ;
collegian = student;//错误集锦
showInfo(collegian);
}
}
/**************************************************************************************/
public class Convert3 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
public static void main(String[] args) {
Convert3 convert3 = new Convert3();
Student student = convert3.new Student("150810123","张三");
Collegian collegian ;
collegian = (Collegian)student;//错误集锦
showInfo(collegian);
}
}
/**************************************************************************************/
public class Convert4 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
public static void main(String[] args) {
Convert4 convert4 = new Convert4();
Student student = convert4.new Student("150810123","张三","计算机");
Collegian collegian ;
collegian = student;//错误集锦
showInfo(collegian);
}
}
/**************************************************************************************/
public class Convert5 {
public class Student{
String studentNo,name;
Student(){}
Student(String sn,String nm){
studentNo = sn; name = nm;
}
}
public class Collegian extends Student{
String major;
Collegian(){}
Collegian(String sn,String nm,String mj){
super(sn,nm);
major = mj;
}
}
public static void showInfo(Student s){
System.out.println("学号:" + s.studentNo);
System.out.println("姓名:" + s.name);
if(s instanceof Collegian){
System.out.println("专业:" + ((Collegian)s).major);
}
}
public static void main(String[] args) {
Convert5 convert5 = new Convert5();
Collegian collegian ;
Student student ;
student = convert5.new Collegian("150810123","张三","计算机");;
collegian = (Collegian)student;//错误集锦
showInfo(collegian);
}
}
/**************************************************************************************/
public class Scope {
static int a;
int b;
public static void main(String[] args) {
a++;
Scope s1 = new Scope();
s1.a++;
s1.b++;
Scope s2 = new Scope();
s2.a++;
s2.b++;
Scope.a++;
System.out.println("a= " + a);
System.out.println("s1.a= " + s1.a);
System.out.println("s2.a= " + s2.a);
System.out.println("s1.b= " + s1.b);
System.out.println("s2.b= " + s2.b);
}
}
/**************************************************************************************/
public class Scope1 {
static int a;
int b;
void test(){
a++;
System.out.println("a= " + a);
b++;
System.out.println("b= " + b);
}
public static void main(String[] args) {
Scope1 s1 = new Scope1();
s1.test();
}
}
/**************************************************************************************/
public class Statict {
public static class Card{
static long nextCardN;
long cardN;
double balance;
static {//静态初始化器
nextCardN = 20018001;
}
Card(double b){
cardN = nextCardN++;
balance = b;
}
}
public static void main(String[] args) {
Card c1 = new Card(50.0);
Card c2 = new Card(100.0);
System.out.println("The first card number is " + c1.cardN);
System.out.println("The second card number is " + c2.cardN);
}
}
/**************************************************************************************/
public class F1 {
public final class first{
int a = 1;
}
public class second extends first{//错误集锦
void tt(){
System.out.println("a " + a);
}
}
}
/**************************************************************************************/
public class F2 {
public class first{
int a = 1;
final void tt(){
System.out.println("a " + a);
}
}
public class second extends first{
@Override
void tt(){//错误集锦
a++;
System.out.println("a " + a);
}
}
}
/**************************************************************************************/
public class F3 {
public static void main(String[] args) {
final int x=1;
x++;//错误集锦
System.out.println("x = " + x);;
}
}
/**************************************************************************************/
public abstract class Father {
}
public class Son extends Father {
static void tt(){
System.out.println("Son");
}
public static void main(String[] args) {
Son s = new Son();
tt();
}
}
/**************************************************************************************/
public class Company {
public abstract class Vehicle {
int kil;
abstract int getfuel();
}
public class Car extends Vehicle {
Car(int k1){
kil = k1;
}
@Override
int getfuel(){
return (7*kil/100);
}
}
public class Bus extends Vehicle{
Bus(int k1){
kil = k1;
}
@Override
int getfuel(){
return (10*kil/100);
}
}
Vehicle fleet[];
Company(){
fleet = new Vehicle[3];
fleet[0] = new Car(300);
fleet[1] = new Bus(500);
fleet[2] = new Car(400);
}
int rf(){
int ff = 0;
for (int i=0; i<fleet.length; i++){
ff = ff + fleet[i].getfuel();
}
return (ff);
}
public static void main(String[] args) {
Company company = new Company();
System.out.println("sum= " + company.rf());
}
}
/**************************************************************************************/
public class Interface2 {
interface first{
int a=1;
void f1();
}
interface second{
void s1();
}
public class C1 implements first,second{
@Override
public void f1(){
System.out.println("a= " + a);
}
@Override
public void s1(){
}
}
public static void main(String[] args) {
Interface2 interface2 = new Interface2();
C1 c1 = interface2.new C1();
c1.f1();
}
}
/**************************************************************************************/
public class Company {
interface Vehicle{
int getfuel();
}
public class Bus implements Vehicle{
int kil;
Bus(int k1){
kil = k1;
}
@Override
public int getfuel(){
return (10*kil/100);
}
}
public class Car implements Vehicle{
int kil;
Car(int k1){
kil = k1;
}
@Override
public int getfuel(){
return (7*kil/100);
}
}
Vehicle fleet[];
Company(){
fleet = new Vehicle[3];
fleet[0] = new Car(300);
fleet[1] = new Bus(500);
fleet[2] = new Car(400);
}
int rf(){
int ff = 0;
for(int i=0; i<fleet.length; i++){
ff = ff + fleet[i].getfuel();
}
return (ff);
}
public static void main(String[] args) {
Company company = new Company();
System.out.println("sum= " + company.rf());
}
}
/**************************************************************************************/
public class Pack {
public class Father{
public void tt(){
System.out.println("Father");
}
}
public class Son extends Father{
@Override
public void tt(){
System.out.println("Son");
}
}
}
/**************************************************************************************/
public class Outer {
private int i = 10;
public void makeIn(){
Inner in = new Inner();//外部类的非静态类中创建内部类
in.fIn();
System.out.println("outer");
}
class Inner{
public void fIn(){
System.out.println("inner: i " + i);
}
}
public static void main(String[] args) {
Outer out = new Outer();
out.makeIn();
Outer.Inner in = out.new Inner();//外部类的静态方法中创建内部类
in.fIn();
}
}
/**************************************************************************************/
在这里插入代码片
/********************************************************************************************/
public class Outer2 {
private int i = 10;
class Inner{
int i;
public void fIn(){
Outer2.this.i = 1;
this.i = 2;
int i = 3;
System.out.println("inner - fIn: i " + i);
System.out.println("inner: i " + this.i);
System.out.println("outer: i " + Outer2.this.i);
}
}
public static void main(String[] args) {
Outer2 out = new Outer2();
Outer2.Inner in = out.new Inner();
in.fIn();
}
}
/********************************************************************************************/
public class Outer5 {
static class Inner{
public void FIn(){
System.out.println("inner5");
}
}
public static void main(String[] args) {
Inner in = new Inner();
in.FIn();
}
}
/********************************************************************************************/
public class Outer6 {
static int i = 10;
int j = 20;
static class Inner{
public void FIn(){
System.out.println("i= " + i);
Outer6 out = new Outer6();
System.out.println("j= " + out.j);//静态内部类对类外成员的访问
}
}
public static void main(String[] args) {
Inner in = new Inner();
in.FIn();
}
}
/********************************************************************************************/
public class Outer6 {
static int i = 10;
int j = 20;
static class Inner{
public void FIn(){
System.out.println("i= " + i);
Outer6 out = new Outer6();
System.out.println("j= " + out.j);//静态内部类对类外成员的访问
}
}
public static void main(String[] args) {
Inner in = new Inner();
in.FIn();
}
}
/********************************************************************************************/
public class Outer7 {
public void fout1(){
class Inner{//方法内部类
public void fIn(){
System.out.println("inner");
}
}
Inner in = new Inner();
in.fIn();
}
public void fout2(){
}
}
/********************************************************************************************/
interface Intf{
public void drive();
}
abstract class Car implements Intf{
}
public class Test {
public static void main(String[] args) {
Intf f = new Intf() {//匿名内部类
@Override
public void drive() {
System.out.println("interface");
}
};
f.drive();
Car c = new Car(){//匿名内部类
@Override
public void drive(){
System.out.println("abstract");
}
};
c.drive();
}
}
/********************************************************************************************/
public class str1 {
public static void main(String[] args) {
String s1,s2,s3,s4;
s1 = new String("Hello");
s2 = new String("Hello");
System.out.println("new: " + (s1.equals(s2)));
System.out.println("new: " + (s1 == s2));
s3 = "Hello";
s4 = "Hello";
System.out.println("without new: " + (s3.equals(s4)));
System.out.println("without new: " + (s3 == s4));
}
}
/********************************************************************************************/
public class Strb {
public static void main(String[] args) {
StringBuilder str = new StringBuilder();
str.append("这是一本书");
System.out.println(str);//直接输出字符串缓冲区中的内容
str.insert(4,"java");
str.append(32.5f);
System.out.println(str.toString());
System.out.println("Its length is " + str.length());
}
}
/********************************************************************************************/
class xx{
int x=1;
}
class yy{
int y=2;
}
import java.util.Vector;
public class Vector1 {
public static void main(String[] args) {
Vector v1 = new Vector();
System.out.println(v1.capacity() + "," + v1.size());
for (int i=1; i<=10; i++){
v1.addElement(new xx());
}
System.out.println(v1.capacity() + "," + v1.size());
v1.insertElementAt(new xx(),0);
v1.addElement(new yy());
System.out.println(v1.capacity() + "," + v1.size());
}
}
/********************************************************************************************/
import java.util.Vector;
public class Vector2 {
public static void main(String[] args) {
int i;
Vector v1 = new Vector(100);
for (i = 1; i <= 5; i++){
v1.addElement(new Integer(1));
v1.addElement(new Integer(2));
}
System.out.println(v1.capacity() + "," + v1.size());
i = 0;
while ((i = v1.indexOf(new Integer(2),i)) != -1){
System.out.println(" " + i);
i++;
}
while (v1.removeElement(new Integer(1))){};
System.out.println();
System.out.println(v1.capacity() + "," + v1.size());
i = 0;
while ((i = v1.indexOf(new Integer(2),i)) != -1){
System.out.println(" " + i);
i++;
}
}
}
/********************************************************************************************/
import java.util.Date;
public class Now {
public static void main(String[] args) {
Date now = new Date();
long nowLong = now.getTime();
System.out.println("Value is " + nowLong);
}
}
/********************************************************************************************/
import java.text.DateFormat;
import java.util.Date;
public class StyleDate {
public static void main(String[] args) {
Date now = new Date();
DateFormat df = DateFormat.getDateInstance();
DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL);
String s = df.format(now);
String s1 = df1.format(now);
String s2 = df2.format(now);
String s3 = df3.format(now);
String s4 = df4.format(now);
System.out.println("(Default) Today is " + s);
System.out.println("(SHORT) Today is " + s1);
System.out.println("(MEDIUM) Today is " + s2);
System.out.println("(LONG) Today is " + s3);
System.out.println("(FULL) Today is " + s4);
}
}
/********************************************************************************************/
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class NextDay {
public static void main(String[] args) {
GregorianCalendar worldTour = new GregorianCalendar(2011, Calendar.OCTOBER,10);
worldTour.add(GregorianCalendar.DATE,3);
Date d = worldTour.getTime();
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
System.out.println("3days after todaay " + s);
}
}
/********************************************************************************************/
public class Comp {
public static void main(String[] args) {
Integer int1 = new Integer(1);
Integer int2 = new Integer(1);
Integer int3 = int1;
int array1[] = new int[2];
int array2[] = new int[2];
array2[0] = 2;
array1[1] = 2;
System.out.println("int1 == int2 is " + (int1 == int2));
System.out.println("int1 == int3 is " + (int1 == int3));
System.out.println("array1 == array2 is " + (array1 == array2));
System.out.println("arry2[0] == array2[1] is " + (array2[0] == array2[1]));
}
}
/********************************************************************************************/
public class Except {
class Div{
void d(int a,int b,int c){
int s = 0;
if(b != 0){
s = a/b;
if( c != 0){
s = s/c;
System.out.println("商为: " + s);
}else {
System.out.println("除数为0");
}
}else {
System.out.println("除数为0");
}
}
}
public static void main(String[] args) {
Except e = new Except();
Div d = e.new Div();
d.d(16,2,4);
d.d(18,3,0);
d.d(15,0,5);
}
}
/********************************************************************************************/
public class Except1 {
class Div{
void d(int a,int b,int c){
int s = 0;
s = a/b;
s = s/c;
System.out.println("商为: " + s);
}
}
public static void main(String[] args) {
Except1 e = new Except1();
Div div = e.new Div();
div.d(16,2,4);
div.d(18,3,0);
div.d(15,0,5);
}
}
/********************************************************************************************/
public class Except2 {
class Div{
void d(int a,int b,int c){
int s = 0;
try {
s = a/b;
s = s/c;
System.out.println("商为: " + s);
}catch (Exception e){
System.out.println("除数为0");
}
}
}
public static void main(String[] args) {
Except2 e = new Except2();
Div div = e.new Div();
div.d(16,2,4);
div.d(18,3,0);
div.d(15,0,5);
}
}
/********************************************************************************************/
public class Ex1 {
public static void main(String[] args) {
int x[] = {4,2,0};
try {
System.out.println("商1: " + x[0]/x[1]);
x[3] = 100;
System.out.println("商2: " + x[1]/x[2]);
}catch (ArithmeticException e){
System.out.println("一");
}catch (RuntimeException e){
System.out.println("二");
}catch (Exception e){
System.out.println("三");
}finally {
System.out.println("四");
}
System.out.println("五");
}
}
/********************************************************************************************/
public class Ex2 {
public static void main(String[] args) {
int x[] = {4,2,0};
try {
System.out.println("商1: " + x[0]/x[1]);
x[3] = 100;
System.out.println("商2: " + x[1]/x[2]);
}catch (NullPointerException e){
System.out.println("一");
}catch (ArithmeticException e){
System.out.println("二");
}finally {
System.out.println("四");
}
System.out.println("五");
}
}
/********************************************************************************************/
public class Ex3 {
public static void main(String[] args) {
int x[] = {4,2,0};
try {
System.out.println("商1: " + x[0]/x[1]);
x[3] = 100;
System.out.println("商2: " + x[1]/x[2]);
}catch (ArithmeticException e){
System.out.println("一");
}catch (RuntimeException e){
System.out.println("二");
throw e;//异常被捕获后又抛出
}catch (Exception e){
System.out.println("三");
}finally {
System.out.println("四");
}
System.out.println("五");
}
}
/********************************************************************************************/
public class Ex4 {
public static void main(String[] args) {
int x[] = {4,2,0};
try {
System.out.println("商1: " + x[0]/x[1]);
x[3] = 100;
System.out.println("商2: " + x[1]/x[2]);
}catch (ArithmeticException e){
System.out.println("一");
}catch (RuntimeException e){
System.out.println("二");
return;//碰到return,先去把finally执行完,然后退出。
}catch (Exception e){
System.out.println("三");
}finally {
System.out.println("四");
}
System.out.println("五");
}
}
/********************************************************************************************/
public class Ex5 {
class Div{
void d(int a,int b){
int s = 0;
s = a/b;
System.out.println("商为: " + s);
}
void meth(){
d(16,2);
d(15,0);//方法调用时的异常,方法d()中产生了除数为零的异常,
// 但是在d()中并没有捕获和处理,而是抛给了它的调用者meth(),
// meth()也没有处理,而是抛给了main,在main中处理了。
}
}
public static void main(String[] args) {
int x[] = {2,5,9};
try {
Ex5 ex5 = new Ex5();
Div div = ex5.new Div();
div.meth();
x[3] = 100;
}catch (ArithmeticException e){
System.out.println("1");
}catch (RuntimeException e){
System.out.println("2");
}catch (Exception e){
System.out.println("3");
}
}
}
/********************************************************************************************/
在这里插入代码片
/********************************************************************/
public class NumException extends Exception{
private String reason;
public NumException(){}
public NumException(String r){
reason = r;
}
public String getReason(){
return (reason);
}
}
/********************************************************************/
//这段代码挺好的
public class TestExc {
public class NumException extends Exception{
private String reason;
public NumException(){}
public NumException(String r){
reason = r;
}
public String getReason(){
return (reason);
}
}
class Student{
private String studentNo,name;
void setStudent(String stno,String nm) throws NumException{
if(stno.length() != 9){
throw new NumException("学号位数不对,应该是9位");
}
studentNo = stno;
name = nm;
}
void showInfo(){
System.out.println("学号:" + studentNo);
System.out.println("姓名:" + name);
}
}
public static void main(String[] args) {
TestExc testExc = new TestExc();
Student st = testExc.new Student();
try{
st.setStudent("15081410","张三");
}catch (NumException e){
System.out.println(e.getReason());
}
st.showInfo();
}
}
/********************************************************************/
在这里插入代码片
/********************************************************************/
public class TestExc {
public class NumException extends Exception{
private String reason;
public NumException(){}
public NumException(String r){
reason = r;
}
public String getReason(){
return (reason);
}
}
class Student{
private String studentNo,name;
void setStudent(String stno,String nm) throws NumException{
if(stno.length() != 9){
throw new NumException("学号位数不对,应该是9位");
}
studentNo = stno;
name = nm;
}
void showInfo(){
System.out.println("学号:" + studentNo);
System.out.println("姓名:" + name);
}
}
public static void main(String[] args) {
TestExc testExc = new TestExc();
Student st = testExc.new Student();
try{
st.setStudent("15081410","张三");
}catch (NumException e){
System.out.println(e.getReason());
}
st.showInfo();
}
}
/********************************************************************/
import java.io.IOException;
public class Io1 {
public static void main(String[] args) {
int ch;
System.out.println("enter a char: ");
try{
while ((ch = System.in.read()) != -1){
System.out.println("the char is " + (char)ch);
System.in.skip(2);//跳过Enter键值
}
}catch (IOException e){
System.out.println("the input is err");
}
}
}
/********************************************************************/
import java.io.IOException;
public class Io2 {
public static void main(String[] args) throws IOException {
byte b[] = new byte[255];
System.out.println("enter chars: ");
int len = System.in.read(b,0,255);
System.out.println("the char's length is " + len);
String s = new String(b,0,len - 2);
System.out.println("the chars is " + s);
System.out.println("the String's length is " + s.length());
}
}
/********************************************************************/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LineIn {
public static void main(String[] args) throws java.io.IOException{
String s;
InputStream in;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader ln = new BufferedReader(ir);
while ((s = ln.readLine()) != null){
System.out.println("Read " + s);
}
}
}
/********************************************************************/
import java.io.File;
public class Ftest1 {
public static void main(String[] args) {
File f1 = new File("F:\\dyp\\index.html");//路径中分隔符应该是\\
System.out.println("f1: " + f1.toString());
System.out.println("f1 is a directory: " + f1.isDirectory());
}
}
/********************************************************************/
import java.io.File;
public class Ftest2 {
public static void main(String[] args) {
String s = System.getProperty("file.separator");//获取本操作系统的路径中的分隔符
System.out.println("separator: " + s);
File f1 = new File("F:" + s + "dyp");
System.out.println("f1: " + f1.toString());
System.out.println("f1 is a directory: " + f1.isDirectory());
}
}
/********************************************************************/
import java.io.File;
public class Ftest3 {
public static void main(String[] args) {
File f1 = new File("r:\\temp1");
System.out.println("D:\\temp1:" + f1.exists());
if(!f1.exists()){
f1.mkdir();
}
System.out.println("made,r:\\temp1: " + f1.exists());
System.out.println("D:\\temp: is a directory: " + f1.isDirectory());
}
}
/********************************************************************/
//文件输入
import java.io.FileInputStream;
public class Fapp1 {
public static void main(String[] args) throws java.io.IOException{
int b;
FileInputStream fin = new FileInputStream("Fapp1.java");
while ((b = fin.read()) != -1){
System.out.println((char)b);
}
}
}
/********************************************************************/
//文件输出
import java.io.FileOutputStream;
public class Fapp2 {
public static void main(String[] args){
byte buffer[] = new byte[80];
try {
System.out.println("Enter: ");
int bytes = System.in.read(buffer);
FileOutputStream fout = new FileOutputStream("line.txt");
fout.write(buffer,0,bytes);
}catch (Exception e){
}
}
}
/********************************************************************/
//文件复制
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Fcopy {
public static void main(String[] args) throws java.io.IOException{
int b;
File file;
FileInputStream fin = new FileInputStream("star.png");
FileOutputStream fout = new FileOutputStream("star1.png");
System.out.println("文件复制!");
while ((b = fin.read()) != -1){
fout.write(b);
//System.out.print((char)b);
}
System.out.println("文件复制结束");
}
}
/********************************************************************/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Fapp3 {
public static void main(String[] args) throws java.io.IOException{
String s;
BufferedReader in;
File file;
FileInputStream fin = new FileInputStream("Fapp3.java");
in = new BufferedReader(new InputStreamReader(fin));
while ((s = in.readLine()) != null){
System.out.println("read: " + s);
}
}
}
/********************************************************************/
//用FileReader读取文本文件
import java.io.BufferedReader;
import java.io.FileReader;
public class Fapp4 {
public static void main(String[] args) throws java.io.IOException{
String s;
BufferedReader in;
FileReader fin = new FileReader("Fapp4.java");
in = new BufferedReader(fin);
while ((s = in.readLine()) != null){
System.out.println("Fileread: " + s);
}
}
}
/********************************************************************/
//用FileWriter完成文本文件写操作
import java.io.*;
public class Fapp5 {
public static void main(String[] args) {
String s;
try{
System.out.println("Enter: ");
InputStream in;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader ln = new BufferedReader(ir);
File file;
FileWriter f = new FileWriter("t1.txt");
while ((s = ln.readLine()) != null){
f.write(s + "\r\n");
}
ln.close();
f.close();
}catch (Exception e){
}
}
}
/********************************************************************/
import java.io.*;
//向文本文件中写入三条学生信息记录,每条记录包括学号、姓名和年龄,
//然后再从文件中把这三条记录读出。每条记录在文件中占一行。
public class Fapp55 {
public static void main(String[] args) {
String s;
int flag = 0,i;
try{
System.out.println("Enter: ");
InputStream in;
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader ln = new BufferedReader(ir);
File file;
FileWriter f = new FileWriter("st.txt");
while (flag < 3){
System.out.println("Enter 学号,姓名,年龄");
s = ln.readLine();
f.write(s + "\r\n");
flag++;
}
ln.close();
f.close();
FileReader fin = new FileReader("st.txt");
ln = new BufferedReader(fin);
i = 0;
while ((s = ln.readLine()) != null){
i++;
System.out.println("record" + i + ":" + s);
}
}catch (Exception e){
}
}
}
/********************************************************************/
import java.io.RandomAccessFile;
//随机文件读取
public class Fapp6 {
public static void main(String[] args) {
String s;
char ch;
RandomAccessFile f;
try{
f = new RandomAccessFile("test.dat", "rw");
//以读写模式对文件test.dat建立随机文件输入输出流
f.writeChars("java");
//向文件中写入一个字符串
f.writeChar(' ');
//以空格作为字符串结束
f.writeInt(48);
//向文件中写入整型数
System.out.println("Pointer: " + f.getFilePointer());
//获取当前文件指针的位置
f.seek(0);
//将文件指针位置设置为文件开始的位置
System.out.println("Pointer: " + f.getFilePointer());
System.out.println("String from the file: ");
ch = f.readChar();
while (ch != ' '){
System.out.println(ch);
ch = f.readChar();
}
//将文件中的字符串读出并输出到显示器,遇到空格结束.
System.out.println();
System.out.println("int from the file: " + f.readInt());
//读出并输出整型数
}catch (Exception e){
}
}
}
/********************************************************************/
//需要重点学习的一个例子
import java.io.IOException;
import java.io.RandomAccessFile;
//综合举例
//向随机文件中写入3个学生信息,每个学生记录包括学号、姓名和年龄。然后从文件中读出第3个学生的信息。
//学号长度固定为9个字符,姓名最多4个字符,可以少于4个字符。为了检索方便,要求每条记录长度相等。
public class Randrw {
public class Student{
String studentNo,name;
int age;
static final int stNo_length = 9;
//学号长度固定为9个字符
static final int name_length = 4;
//姓名长度固定为4个字符
static final int rec_length = (stNo_length + name_length)*2 +4;
//记录长度,字节数
Student(String sn,String nm,int a){
studentNo = sn;
name = nm;
age = a;
}
@Override
public String toString() {
return (studentNo + ";" + name + ";" + age + ";");
}
}
boolean writedata(Student st[], RandomAccessFile fout) throws IOException{
char ch;
for (int i=0; i<st.length; i++){
if((st[i].studentNo).length() != st[i].stNo_length){
return false;
}
else {
fout.writeChars(st[i].studentNo);
//向文件中写入学号,学号如果不足固定长度则本方法退出
}
for(int j=0; j < st[i].name_length; j++){
ch = ' ';
if(j<st[i].name.length()){
ch = st[i].name.charAt(j);
}
fout.writeChar(ch);
}
//向文件中写入姓名,姓名如果不足固定长度则补空格
fout.writeInt(st[i].age);
}
return true;
}
void readdata(int n,Student st[],RandomAccessFile f) throws IOException{
int size = Student.name_length;
StringBuilder b = new StringBuilder(size);
char ch[] = new char[size];
char ch1;
int i;
boolean more = true;
f.seek((n-1)*Student.rec_length);
//指针指到第3条记录起始处
i = 0;
while (i<Student.stNo_length){
ch1 = f.readChar();
System.out.println(ch1);
i++;
}
System.out.println();
i=0;
while (more && i<size){
ch1 = f.readChar();
i++;
if(ch1 == ' '){
more = false;
}
else {
b.append(ch1);
}
}
//读出姓名,因为姓名可能不足固定长度,只读出姓名中的有效字符
f.skipBytes(2 * (size-i));
//当姓名不足4个字符时,跳过剩余的字节,将指针指向本条记录的年龄值
System.out.println(b.toString() + " ");
System.out.println(f.readInt() + " ");
}
public static void main(String[] args) {
RandomAccessFile f;
Randrw r1 = new Randrw();
Student st[] = new Student[3];
st[0] = r1.new Student("150814101","张三",21);
st[1] = r1.new Student("150814103","李小四",20);
st[2] = r1.new Student("150814106","王老五",19);
try {
f = new RandomAccessFile("test.dat", "rw");
if(!r1.writedata(st,f)){
throw new Exception("WriteWrong");
}
r1.readdata(3,st,f);
}catch (Exception e){
e.printStackTrace();
}
}
}
/********************************************************************/
import java.io.Serializable;
public class StudentSer implements Serializable {
String studentNo,name;
int age;
StudentSer(String sn,String nm,int a){
studentNo = sn;
name = nm;
age = a;
}
@Override
public String toString() {
return (studentNo + ";" + name + ";" + age +";");
}
}
import java.io.*;
import java.util.stream.Stream;
//对象的输入输出
public class Settest {
public static void main(String[] args) throws Exception{
Settest st = new Settest();
FileOutputStream fout = new FileOutputStream("my.dat");
ObjectOutputStream bout = new ObjectOutputStream(fout);
StudentSer st1,st2,st3,st4;
st1 = new StudentSer("150814101","张三",21);
st2 = new StudentSer("150814103","李小四",20);
bout.writeObject(st1);
bout.writeObject(st2);
bout.close();
File file;
FileInputStream fin = new FileInputStream("my.dat");
ObjectInputStream bin = new ObjectInputStream(fin);
st3 = (StudentSer)bin.readObject();
System.out.println(st3.toString());
st4 = (StudentSer)bin.readObject();
System.out.println(st4.toString());
bin.close();
}
}
/********************************************************************/
public class Cmd1 {
public static void main(String[] args) {
int a,b;
System.out.println(args[0]);
System.out.println(args[1]);
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
System.out.println("a + b = " + (a + b));
}
}
/********************************************************************/
import java.util.Scanner;
public class ScannerLine {
public static void main(String[] args) {
String str;
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串:");
while (s.hasNext()){
str = s.nextLine();
System.out.print("str: " + str);
System.out.println();
}
s.close();
}
}
/********************************************************************/
import java.util.Scanner;
//扫描字符串,设定分隔符
public class ScannerStr {
public static void main(String[] args) {
String input = "1 bird 2 bird 3 red bird 4 blue bird";
Scanner s = new Scanner(input).useDelimiter("\\s*bird\\s*");
int x = s.nextInt() + s.nextInt();
System.out.println("x= " + x);
System.out.println(s.next());
System.out.println(s.next());
s.close();
}
}
/********************************************************************/
//扫描文件
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerFile {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("my.dat");
Scanner s = new Scanner(f);
while (s.hasNextLine()){
System.out.println("read: " + s.nextLine());
}
s.close();
}
}
/********************************************************************/
//java的图形用户界面只看一个例子,剩下的以后再看。
import javax.swing.*;
public class My {
public static void main(String[] args) {
JFrame f = new JFrame("hello");
f.setSize(200,200);
f.setVisible(true);
}
}
/********************************************************************/
//接下来多线程
//通过继承Thread类创建线程
public class Cret1 {
public class Tthread1 extends Thread{
@Override
public void run() {
System.out.println("Thread1 在运行");
}
}
public static void main(String[] args) {
Cret1 ct = new Cret1();
Tthread1 tr = ct.new Tthread1();
tr.start();
System.out.println("main在运行");
}
}
/********************************************************************/
//通过实现Runnable接口创建线程
public class Cret2 {
public class Tthread2 implements Runnable{
@Override
public void run() {
System.out.println("Thread2在运行");
}
}
public static void main(String[] args) {
Cret2 cr = new Cret2();
Tthread2 tr2 = cr.new Tthread2();
Thread tr1 = new Thread(tr2);
tr1.start();
System.out.println("main在运行");
}
}
/********************************************************************/
//龟兔赛跑
public class Thr1 {
public class Tortoise implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
}
}
}
public class Rabbit implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
}
}
}
public static void main(String[] args) {
Thr1 thr1 = new Thr1();
Tortoise tortoise = thr1.new Tortoise();
Rabbit rabbit = thr1.new Rabbit();
Thread t1 = new Thread(rabbit);
Thread t2 = new Thread(tortoise);
t2.start();
t1.start();
}
}
/********************************************************************/
//龟兔赛跑
//线程之间的数据交流
//内类的作用是可以直接访问外类的成员变量,把共享数据定义成外类的成员变量,
//线程定义成内类,就可以实现线程间的数据交流。
public class Thr1 {
int food = 20;
public void go(){
Tortoise r1 = new Tortoise();
Rabbit r2 = new Rabbit();
r1.run();
r2.run();
}
public class Tortoise implements Runnable{
int i,f = 0;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
if(food > 0){
food --;
f ++;
System.out.println("乌龟吃了第" + f + "个食物,还剩food=" + food);
}
}
}
}
public class Rabbit implements Runnable{
int i,f = 0;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
if(food > 0){
food --;
f ++;
System.out.println("兔子吃了第" + f + "个食物,还剩food=" + food);
}
}
}
}
public static void main(String[] args) {
Thr1 thr1 = new Thr1();
thr1.go();
}
}
/********************************************************************/
import java.util.Random;
//龟兔赛跑
//通过构造器传递参数
public class Thr2 {
public class food{
public int food = 10;
}//共同访问的数据
public void go(){
food f1 = new food();
Tortoise r1 = new Tortoise(f1);//将f1的引用传递给r1
Rabbit r2 = new Rabbit(f1);//将f1的引用传递给r2,有点c/c++的意思了
r1.run();
r2.run();
}
public class Tortoise implements Runnable{
int i;
food fd;
int f = 0;
public Tortoise(food fd){
this.fd = fd;//这里是传引用
}
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
if(fd.food > 0){
fd.food --;
f ++;
System.out.println("乌龟吃了第" + f + "个食物,还剩food=" + fd.food);
}
}
}
}
public class Rabbit implements Runnable{
int i;
food fd;
int f = 0;
public Rabbit(food fd){
this.fd = fd;//这里是传引用
}
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
if(fd.food > 0){
fd.food --;
f ++;
System.out.println("兔子吃了第" + f + "个食物,还剩food=" + fd.food);
}
}
}
}
public static void main(String[] args) {
Thr2 thr2 = new Thr2();
thr2.go();
}
}
//传引用的特点是一处变化,处处响应。
/********************************************************************/
//设置线程优先级
public class Thr {
public class Tortoise implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
}
}
}
public class Rabbit implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
}
}
public static void main(String[] args) {
Thr thr = new Thr();
Tortoise r1 = thr.new Tortoise();
Rabbit r2 = thr.new Rabbit();
Runnable target;
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t2.setPriority(10);
t1.start();
t2.start();
t1.setPriority(10);
}
}
/********************************************************************/
//休眠
public class Thr {
public class Tortoise implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
}
}
}
public class Rabbit implements Runnable{
int i;
@Override
public void run() {
try{
Thread.sleep(1);
}catch (InterruptedException e){ }
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
}
}
}
public static void main(String[] args) {
Thr thr = new Thr();
Tortoise r1 = thr.new Tortoise();
Rabbit r2 = thr.new Rabbit();
Runnable target;
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t2.setPriority(10);
t1.start();
t2.start();
t1.setPriority(10);
}
}
/********************************************************************/
public class Thr {
public class Tortoise implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("乌龟跑到了" + i + "米处");
}
}
}
public class Rabbit implements Runnable{
int i;
@Override
public void run() {
for(i=1;i<=10;i++){
System.out.println("兔子跑到了" + i + "米处");
if(i == 5){
Thread.yield();//使当前线程重新回到就绪状态
}
}
}
}
public static void main(String[] args) {
Thr thr = new Thr();
Tortoise r1 = thr.new Tortoise();
Rabbit r2 = thr.new Rabbit();
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t2.start();
t1.start();
}
}
/********************************************************************/
//等待其它线程一定时间
public class Jointest {
public class xx implements Runnable{
@Override
public void run() {
while (true){
System.out.println("aa");
}
}
}
public class yy implements Runnable{
@Override
public void run() {
while (true){
System.out.println("bb");
}
}
}
public static void main(String[] args) throws Exception{
Jointest jointest = new Jointest();
xx a = jointest.new xx();
yy b = jointest.new yy();
Runnable target;
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.setPriority(1);
t1.start();
try {
//t1.join(4);//主线程将等待t1线程4000毫秒
t1.join();//无参则一直等待t1线程跑完
}catch (Exception e){}
t2.start();
}
}
/********************************************************************/
//使用全局变量的引用来共享数据
public class Thr2 {
public class food{
public int food = 10;
int i;
String s;
public void show(){
System.out.println(s + "跑到了" + i + "米处");
if(food>0){
food--;
System.out.println(s + "吃了第" + i + "个食物,还剩food= " + food);
}
}
}
public class Tortoise extends Thread{
int i;
food fd;
public Tortoise(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
fd.i = i;
fd.s = "tortoise";
fd.show();;
}
}
}
public class Rabbit extends Thread{
int i;
food fd;
public Rabbit(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
fd.i = i;
fd.s = "rabbit";
fd.show();
}
}
}
public void go(){
food f1 = new food();
Tortoise r1 = new Tortoise(f1);
Rabbit r2 = new Rabbit(f1);
r1.start();
r2.start();
}
public static void main(String[] args) {
Thr2 thr2 = new Thr2();
thr2.go();
}
}
/********************************************************************/
//对共用对象加锁
public class Thr2 {
public class food{
public int food = 10;
int i;
String s;
public void show(){
System.out.println(s + "跑到了" + i + "米处");
if(food>0){
food--;
System.out.println(s + "吃了第" + i + "个食物,还剩food= " + food);
}
}
}//共同的访问对象
public class Tortoise extends Thread{
int i;
food fd;
public Tortoise(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
synchronized (fd){
fd.i = i;
fd.s = "tortoise";
fd.show();
}
}
}
}
public class Rabbit extends Thread{
int i;
food fd;
public Rabbit(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
synchronized (fd){
fd.i = i;
fd.s = "rabbit";
fd.show();
}
}
}
}
public void go(){
food f1 = new food();
Tortoise r1 = new Tortoise(f1);
Rabbit r2 = new Rabbit(f1);
r1.start();
r2.start();
}
public static void main(String[] args) {
Thr2 thr2 = new Thr2();
thr2.go();
}
}
//这个程序在乌龟和兔子线程中,对共用对象的访问代码加了锁。
//注意,对i和s的赋值都属于共用对象的访问访问,因此也要放到synchronized标记的大括号内。
//否则,对共用对象的访问依然不完整,结果还会混乱。为了使两个线程能出现交替运行的状态,
//让龟和兔子在每跑完1米后都休眠1000毫秒。
/********************************************************************/
//对共用方法加锁
public class Thr2 {
public class food{
public int food = 10;
int i;
String s;
public synchronized void show(int i1,String s1){
i = i1;
s = s1;
System.out.println(s + "跑到了" + i + "米处");
if(food>0){
food--;
System.out.println(s + "吃了第" + i + "个食物,还剩food= " + food);
}
}
}//共同的访问数据
public class Tortoise extends Thread{
int i;
food fd;
public Tortoise(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
fd.show(i,"tortoise");
}
}
}
public class Rabbit extends Thread{
int i;
food fd;
public Rabbit(food fd1){
fd = fd1;
}
@Override
public void run() {
for (i=1;i<11;i++){
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
fd.show(i,"rabbit");
}
}
}
public void go(){
food f1 = new food();
Tortoise r1 = new Tortoise(f1);
Rabbit r2 = new Rabbit(f1);
r1.start();
r2.start();
}
public static void main(String[] args) {
Thr2 thr2 = new Thr2();
thr2.go();
}
}
//这个程序首先把对共用对象操作的代码都放到了方法show()中,通过传参数的方式,
//在方法show()中为i和s赋值,这样就使得对共用对象的访问只要调用show()方法就能完成,
//也就是说show()方法就是线程中的共用代码,为了达到线程同步,就直接在方法show()定义时,
//把synchronized标记添加到其头部。
/********************************************************************/
public class Syntest1 {
public class synqueue{
private int front = 0,rear = 0;
final static int MaxSize = 6;
private char b[] = new char[MaxSize];
synchronized void enqueue(char c){
if((rear + 1) % MaxSize == front){
System.out.println("存储空间用完!");
System.exit(1);
}
rear = (rear + 1) % MaxSize;
b[rear] = c;
}
synchronized char outqueue(){
if(front == rear){
System.out.println("队列已空,无法消费!");
System.out.println(1);
}
front = (front + 1) % MaxSize;
return b[front];
}
}
public class producer implements Runnable{
synqueue sq;
producer(synqueue sq1){
sq = sq1;
}
@Override
public void run() {
char c;
for(int i=0;i<20;i++){
c = (char)(Math.random() * 26 + 'A');
sq.enqueue(c);
System.out.println("Producer" + c);
try {
Thread.sleep(100);
}catch (InterruptedException e){}
}
}
}
public class consumer implements Runnable{
synqueue sq;
consumer(synqueue sq1){
sq = sq1;
}
@Override
public void run() {
char c;
for (int i=0;i<20;i++){
c= sq.outqueue();
System.out.println("consumer" + c);
try {
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}
public static void main(String[] args) {
Syntest1 syntest1 = new Syntest1();
synqueue sq = syntest1.new synqueue();
producer p1 = syntest1.new producer(sq);
consumer c1 = syntest1.new consumer(sq);
Runnable target;
Thread t1 = new Thread(p1);
Thread t2 = new Thread(c1);
t1.start();
t2.start();
}
}
/********************************************************************/
public class Syntest2 {
public class synqueue{
private int front = 0,rear = 0;
final static int MaxSize = 6;
private char b[] = new char[MaxSize];
synchronized void enqueue(char c){
if((rear + 1) % MaxSize == front){
try {
this.wait();
//队列已满,暂停执行入队的线程,使正在执行enqueue()的线程进入队列的wait池
}catch (InterruptedException e){}
//System.out.println("存储空间用完!");
//System.exit(1);
}
this.notify();
rear = (rear + 1) % MaxSize;
b[rear] = c;
}
synchronized char outqueue(){
if(front == rear){
try {
this.wait();
//队列为空,暂停执行出队的线程
}catch (InterruptedException e){}
//System.out.println("队列已空,无法消费!");
//System.out.println(1);
}
this.notify();
//唤醒在此对象监视器上等待的单个线程
front = (front + 1) % MaxSize;
return b[front];
}
}
public class producer implements Runnable{
synqueue sq;
producer(synqueue sq1){
sq = sq1;
}
@Override
public void run() {
char c;
for(int i=0;i<20;i++){
c = (char)(Math.random() * 26 + 'A');
sq.enqueue(c);
System.out.println("Producer" + c);
try {
Thread.sleep(100);
}catch (InterruptedException e){}
}
}
}
public class consumer implements Runnable{
synqueue sq;
consumer(synqueue sq1){
sq = sq1;
}
@Override
public void run() {
char c;
for (int i=0;i<20;i++){
c= sq.outqueue();
System.out.println("consumer" + c);
try {
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}
public static void main(String[] args) {
Syntest2 syntest2 = new Syntest2();
synqueue sq = syntest2.new synqueue();
producer p1 = syntest2.new producer(sq);
consumer c1 = syntest2.new consumer(sq);
Runnable target;
Thread t1 = new Thread(p1);
Thread t2 = new Thread(c1);
t1.start();
t2.start();
}
}
/********************************************************************/
//死锁的产生
public class Locktest {
public class data{
int x,y;
}
public class xx implements Runnable{
data d1,d2;
xx(data dd1,data dd2){
d1 = dd1;
d2 = dd2;
}
@Override
public void run() {
synchronized (d1){
d1.x = 10;
d1.y = 10;
System.out.println(d1.x + " " + d1.y + "t1 locks d1");
try {
Thread.sleep(4000);
}catch (Exception e){}
synchronized (d2){
d2.x = 20;
d2.y = 20;
System.out.println(d2.x + " " + d2.y + "t1 locks d2");
try {
Thread.sleep(4000);
}catch (Exception e){}
}
}
}
}
public class yy implements Runnable{
data d1,d2;
yy(data dd1,data dd2){
d1 = dd1;
d2 = dd2;
}
@Override
public void run() {
synchronized (d2){
d2.x = 10;
d2.y = 10;
System.out.println(d2.x + " " + d2.y + "t2 locks d2");
try {
Thread.sleep(4000);
}catch (Exception e){}
synchronized (d1){
d1.x = 20;
d1.y = 20;
System.out.println(d1.x + " " + d1.y + "t2 locks d1");
try {
Thread.sleep(4000);
}catch (Exception e){}
}
}
}
}
public static void main(String[] args) {
Locktest lt = new Locktest();
data d1,d2;
d1 = lt.new data();
d2 = lt.new data();
xx a = lt.new xx(d1,d2);
yy b = lt.new yy(d1,d2);
Runnable target;
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}
/********************************************************************/
//避免死锁
public class Unlock {
public class data{
int x,y;
}
public class xx implements Runnable{
data d1,d2;
xx(data dd1,data dd2){
d1 = dd1;
d2 = dd2;
}
@Override
public void run() {
synchronized (d1){
d1.x = 10;
d1.y = 10;
System.out.println(d1.x + " " + d1.y + "t1 locks d1");
try {
Thread.sleep(4000);
}catch (Exception e){}
synchronized (d2){
d2.x = 20;
d2.y = 20;
System.out.println(d2.x + " " + d2.y + "t1 locks d2");
try {
Thread.sleep(4000);
}catch (Exception e){}
}
}
}
}
public class yy implements Runnable{
data d1,d2;
yy(data dd1,data dd2){
d1 = dd1;
d2 = dd2;
}
@Override
public void run() {
synchronized (d1){
d1.x = 10;
d1.y = 10;
System.out.println(d1.x + " " + d1.y + "t2 locks d1");
try {
Thread.sleep(4000);
}catch (Exception e){}
synchronized (d2){
d2.x = 20;
d2.y = 20;
System.out.println(d2.x + " " + d2.y + "t2 locks d2");
try {
Thread.sleep(4000);
}catch (Exception e){}
}
}
}
}
public static void main(String[] args) {
Unlock lt = new Unlock();
data d1,d2;
d1 = lt.new data();
d2 = lt.new data();
xx a = lt.new xx(d1,d2);
yy b = lt.new yy(d1,d2);
Runnable target;
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}
}
//在写程序时,避免死锁的办法是,多个线程对多个共享资源的加锁顺序保持一致。
/********************************************************************/
//Client/Server程序设计
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Net1 {
public static void main(String[] args) {
try {
InetAddress address1 = InetAddress.getByName("211.64.120.1");
System.out.println("211.64.120.1的域名" + address1.getHostName());
InetAddress address2 = InetAddress.getLocalHost();
System.out.println("本机的机器名:" + address2.getHostName());
System.out.println("本机的IP地址:" + address2.getHostAddress() );
}catch (UnknownHostException e){
System.out.println(e.toString());
}
}
}
/********************************************************************/
import java.net.MalformedURLException;
import java.net.URL;
public class Urltest {
public static void main(String[] args) {
try {
URL url = new URL("http://www.sdjtu.edu.cn/sdjtunet/xyxx.asp");
System.out.println("URL: " + url);
System.out.println("Protocal: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
}catch (MalformedURLException e){
System.out.println(e.toString());
}
}
}
/********************************************************************/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Msa {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(4321);
System.out.println("Server ok");
while (true){
Socket s = ss.accept();
//监听客户端请求,一旦监听到就生成Socket对象,并建立连接
InputStreamReader ins = new InputStreamReader(s.getInputStream());
BufferedReader in = new BufferedReader(ins);
//服务器端的输入流
String x = in.readLine();
System.out.println("Informtion from client: " + x);
//将客户端发来的信息输出到显示器
PrintStream out = new PrintStream(s.getOutputStream());
//服务器端的输出流
out.println("hello world");
in.close();
out.close();
s.close();
}
}catch (IOException e){}
}
}
import java.io.*;
import java.net.Socket;
public class Mca {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",4321);
//提供创建Socket对象向服务器的4321端口发出请求
PrintStream out = new PrintStream(s.getOutputStream());
//客户端的输出流
String c = "hello server";
out.println(c);
InputStreamReader ins = new InputStreamReader(s.getInputStream());
BufferedReader in = new BufferedReader(ins);
String x = in.readLine();
System.out.println("Information from server: " + x);
out.close();
in.close();
s.close();
}catch (IOException e){}
}
}
/********************************************************************/
import java.io.IOException;
import java.net.*;
public class Udps {
public static void main(String[] args) {
DatagramSocket ds = null;
DatagramPacket dp = null;
try {
ds = new DatagramSocket(3000);
//该套接字与端口号3000绑定
}catch (SocketException e){}
String str = "hello world";
try {
int len = str.getBytes().length;
System.out.println(str + len);
dp = new DatagramPacket(str.getBytes(),str.getBytes().length, InetAddress.getByName("localhost"),9000 );
}catch (UnknownHostException e){}
try {
ds.send(dp);
}catch (IOException e){}
ds.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Udprec {
public static void main(String[] args) {
DatagramSocket ds = null;
byte[] buf = new byte[1024];
DatagramPacket dp = null;
try {
ds = new DatagramSocket(9000);
}catch (SocketException e){}
try {
ds.receive(dp);
}catch (IOException e){}
String str = new String(dp.getData(), 0,dp.getLength()) + " from "
+ dp.getAddress().getHostAddress() + ": " + dp.getPort();
//从数据报包中解析出发来的数据、长度、发送方的IP地址及端口号
System.out.println(str + " length= " + dp.getLength());
ds.close();
}
}
/********************************************************************/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.rmi.UnexpectedException;
public class Udprec1 {
public static void main(String[] args) {
DatagramSocket ds = null;
byte[] buf = new byte[1024];
DatagramPacket dp = null,dp1 = null;
try {
ds = new DatagramSocket(9000);
}catch (SocketException e){}
//该套接字与端口9000绑定
dp = new DatagramPacket(buf,1024 );
//构造接收数据报包
try {
ds.receive(dp);
}catch (IOException e){}
String str = new String(dp.getData(),0, dp.getLength()) + " from " +
dp.getAddress().getHostAddress() + ": " + dp.getPort();
//从数据报包中解析出发来的数据、长度、发送方的IP地址及端口号
System.out.println(str);
String s = "i hava received!";
try {
dp1 = new DatagramPacket(s.getBytes(),s.getBytes().length, InetAddress.getByName("localhost"),3000 );
ds.send(dp1);
}catch (UnexpectedException e){}
catch (IOException e){}
ds.close();
}
}
/********************************************************************/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Webserver implements Runnable{
Socket s;
static int i;
public Webserver(Socket s1){
s = s1;
}
@Override
public void run() {
try {
PrintStream out = new PrintStream(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info = in.readLine();
System.out.println("now got" + info);
out.println("HTTP/1.0");
out.println("Content-Type: text/html");
i++;
String c = "<html><head></head><body><h1>hi this is" + i + "</h1></body></html>";
out.println();
out.println(c);
out.close();
s.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
}
}
import java.net.ServerSocket;
import java.net.Socket;
//java手写简单的Web服务器
public class Webs {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(80);
System.out.println("Web server ok");
while (true){
Socket s = ss.accept();
Webserver w = new Webserver(s);
Thread t = new Thread(w);
t.start();
}
}catch (Exception e){
System.out.println(e);
}
}
}
/********************************************************************/
import java.io.*;
import java.net.Socket;
public class Webserver1 implements Runnable{
Socket s;
static int i;
public Webserver1(Socket s1){
s = s1;
}
@Override
public void run() {
try {
PrintStream out = new PrintStream(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info = in.readLine();
System.out.println("now got" + info);
out.println("HTTP/1.0");
out.println("Content-Type: text/html");
out.println("");
//从用户的请求字符串中提取出用户请求的文件名及其路径信息
int sp1 = info.indexOf(' ');
int sp2 = info.indexOf(' ',sp1 + 1);
String fn = info.substring(sp1 + 2,sp2);
//当用户请求信息中未指定时,默认为index.html
if(fn.equals("")||fn.endsWith("/")){
fn = fn + "index.html";
}
System.out.println("sending file: " + fn + " to client");
InputStream fs = new FileInputStream(fn);
//建立文件输入流
byte buf[] = new byte[1024];
int n;
while ((n = fs.read(buf))>=0){
out.write(buf,0,n);
}
out.close();
s.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
}
}
import java.net.ServerSocket;
import java.net.Socket;
//java手写简单的Web服务器向客户端传递页面文件
public class Webs1 {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(80);
System.out.println("Web server ok");
while (true){
Socket s = ss.accept();
Webserver1 w = new Webserver1(s);
Thread t = new Thread(w);
t.start();
}
}catch (Exception e){
System.out.println(e);
}
}
}
/********************************************************************/
import java.io.*;
import java.net.Socket;
import java.net.URL;
public class Mspserver implements Runnable{
Socket s;
static int i;
public Mspserver(Socket s1){
s = s1;
}
@Override
public void run() {
try {
PrintStream out = new PrintStream(s.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info = in.readLine();
System.out.println("client is: " + s.getInetAddress());
System.out.println("now got " + info);
//解析目标站点
int sp1 = info.indexOf(' ');
int sp2 = info.indexOf(' ',sp1 + 1);
String targ = info.substring(sp1 + 1,sp2);
System.out.println("now connecting " + targ);
URL con = new URL(targ);
//建立目标站点的URL对象
InputStream gotoin = con.openStream();
//和目标站点建立输入流
int n;
byte buf[] = new byte[1024];
out.println("HTTP/1.0");
out.println("Content-type: text/html");
out.println("");
while ((n = gotoin.read(buf)) >= 0){
out.write(buf,0,n);
}
out.close();
s.close();
in.close();
}catch (Exception e){
System.out.println(e);
}
}
}
import java.net.ServerSocket;
import java.net.Socket;
//代理服务器程序与前面的Web服务器相比,只有一点区别 ,就是在解析了用户的请求后,
//Web服务器是与本地的文件建立文件输入流,而代理服务器可能是与另一台机器上的文件建立输入流,
//因此要先生成目标机器的URL对象,通过该对象建立文件输入流。
public class Msp {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8081);
System.out.println("proxy server ok");
while (true){
Socket s = ss.accept();
Mspserver p = new Mspserver(s);
Thread t = new Thread(p);
t.start();
}
}catch (Exception e){
System.out.println(e);
}
}
}
/********************************************************************/
//接下来的手写JDBC和手写Servlet以后另写博客练习。
/********************************************************************/
import java.rmi.Remote;
import java.rmi.RemoteException;
//java分布式编程
//被远程调用的方法应该定义在Remote的子接口中,并需要声明抛出java.rmi.RemoteException异常
public interface FacServ extends Remote {
public int fac(int n) throws RemoteException;
//fac()是需要被远程调用的方法
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class FacServImpl extends UnicastRemoteObject implements FacServ {
public FacServImpl() throws RemoteException{
super();
}
@Override
public int fac(int n) throws RemoteException {
System.out.println("A remote call!");
int p = 1, i;
for(i = 1; i <= n; i++){
p = p * i;
}
return (p);
}
}
/********************************************************************/
import java.rmi.Naming;
public class RmiServer {
public static void main(String[] args) {
try {
FacServImpl fs = new FacServImpl();
Naming.rebind("//127.0.0.1:8899/factorial",fs);
System.out.println("server bound");
}catch (Exception e){
System.out.println(e);
}
}
}
import java.rmi.Naming;
public class RmiClient {
public static void main(String[] args) {
try {
FacServ f = (FacServ) Naming.lookup("rmi://127.0.0.1/factorial");
int p = f.fac(5);
System.out.println(p);
}catch (Exception e){
System.out.println(e);
}
}
}
/********************************************************************/
java调试代码
最新推荐文章于 2024-03-06 11:52:30 发布