public class Add{
public static void main(String[] args){
double x = Double.valueOf(args[0]).doubleValue(), //将字符串化为数值
y = Double.valueOf(args[1]).doubleValue();
System.out.println("x+y=" + (x+y));
}
}
public class PrintNumber{
public static void main(String args[]){
int n = 1678;
System.out.print(n/1000 + " ");
System.out.print(n/100%10 + " ");
System.out.print(n/10%10 + " ");
System.out.print(n%10 + " ");
}
}
public class AverageNumberLetters{
public static void main(String args[]){
String s = "Java is an object oriented programming language";
String[] t = s.split(" ");
double sum = 0,num = 0;
System.out.println(s);
for(int i = 0; i < t.length; i++){
sum += t[i].length();
num ++;
}
System.out.println("平均字母数:" + sum/num);
}
}
public class CompoundInterest{
public static void main(String args[]){
double rate = 0.065/12; //月利率
double principal = 10000,sum = principal,t = 0;
double[] interest = new double[11]; //每年利息
for(int i = 1; i <= 10; i++){
for(int j = 1; j <= 12; j++){
sum = sum*(1 + rate);
}
interest[i] = sum - principal;
System.out.println("第 " + i + " 年的利息:" + interest[i] + " 和结余:" + sum);
principal = sum;
for(int k = 1; k <= i; k++){
t += interest[k];
}
System.out.println("到该年为止的平均利息:" + t/i);
t = 0;
}
}
}
public class Array{
public static void main(String args[]){
double[][] s = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
double[] sum1 = new double[4]; //每行
double[] sum2 = new double[4]; //每列
double sum3 = 0;//主对角线
double sum4 = 0;//副对角线
double max = s[0][0];
for(int i = 0; i < 4; i++){
sum1[i] = 0;
sum2[i] = 0;
for(int j = 0; j < 4; j++){
sum1[i] += s[i][j];
sum2[i] += s[j][i];
if(s[i][j] > max)max = s[i][j]; //最大值
if(i == j)sum3 += s[i][j];
if(i+j == 4-1)sum4 += s[i][j];
}
}
for(int k = 0; k < 4; k++)
System.out.println("第 " + (k+1) + " 行:" + sum1[k]);
for(int k = 0; k < 4; k++)
System.out.println("第 " + (k+1) + " 列:" + sum2[k]);
System.out.println("主,副对角线的和与最大值分别是:" + "("+ (sum3+sum4)+ "," + max +")");
}
}
public class Address{
private String name;
private String email;
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void display(){
System.out.println(this.name + "’s Address:" + this.email);
}
}
//这个题目我就随便设置了几个值对应三种访问控制符,类名也随便起的,无所谓了
class Test{
Test(){
}
Test(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName(){ //返回私有成员变量
return name;
}
private String name;
public int age;
protected String sex;
}
public class Test18{
public static void main(String[] args){
Test test = new Test("zgh",18,"male");
//System.out.println(test.name); //name是私有的,这样访问会报错
System.out.println(test.getName());//私有成员变量的访问要借助于方法
System.out.println(test.age);
System.out.println(test.sex);
}
}
//这个题目借助于构造器就ok了
public class CalculateInstances{
static int num;
CalculateInstances(){
num++;
}
}
测试上述代码的正确性:
public class CalculateInstances{
static int num;
CalculateInstances(){
num++;
}
public static void main(String[] args){
System.out.println(CalculateInstances.num);
CalculateInstances a = new CalculateInstances();
System.out.println(CalculateInstances.num);
CalculateInstances b = new CalculateInstances();
System.out.println(CalculateInstances.num);
CalculateInstances c= new CalculateInstances();
System.out.println(CalculateInstances.num);
CalculateInstances d= new CalculateInstances();
System.out.println(CalculateInstances.num);
}
}
public class Student{
private String name;
private float GPA;
public Student(){
}
public Student(String name){
this.name = name;
}
public Student(String name,float GPA){
this.name = name;
this.GPA = GPA;
}
}
(第4章15题如此:假如我们要编写一个地址簿的程序,设计一个能存储姓名、E-mail地址,并能显示一个地址的Address类)
class Address{
private String name;
private String email;
public void setName(String name){
this.name = name;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void display(){
System.out.println(this.name + "’s Address:" + this.email);
}
}
public class AddressSon extends Address{
private String Email; //另外一个成员变量来存储电话号码
public void setEmail(String email) {
Email = email;
}
public String getEmail() {
return Email;
}
}
第一个解: 首先说一下,下面我写的代码已经超出题目要求了(我将设计的List类,增删对象时,可以动态的改变数组的长度)
public class List<E> { //泛型
//描述事物
//属性:
private static final int DEFAULT_CAPACITY = 10;
private Object[] elementData;//给ArrayBox一个初始数组
private int size = 0;//记录ArrayBox中有效数据的个数,给一个初始值
//构造方法:
public List(){
elementData = new Object[DEFAULT_CAPACITY];
}
public List(int capacity){
elementData = new Object[capacity];
}
//方法:
//1.需要设计一个方法,用来添加元素
// 提供什么条件(参数) 返回一个结果(返回值)--告知用户一个结果,是否存储成功 boolean
//
//存储元素的时候方法给位置存放
//如果位置满了,方法要解决这个问题
//添加元素
public boolean add(E element){//E是创建box对象时,规定的类型
//首先要确保自己的属性数组的内部容量够不够用
// 调用一个方法,来确定内部容量够用否
this.ensureCapacity(size+1);
//我想把element存入elementData数组中
elementData[size++] = element;
return true;
}
//访问控制修饰符是private的,是不希望用户看到的方法
private void ensureCapacity(int minCapacity){ //来确定内部容量够用否
//minCapacity即用户所需最小空间
if(minCapacity > elementData.length){
//如果内部容量不够用,调用一个扩容的方法
this.grow(minCapacity);
}
}
private void grow(int minCapacity){ //给内部空间扩容
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity>>1);//即oldCapacty*1.5
if(newCapacity < minCapacity){
newCapacity = minCapacity;
}
//既然要把空间扩容,要把旧数组的内容放到新的更大空间的数组中
//调用一个类,复制数组内容
elementData = this.copyOf(elementData,newCapacity);
}
private Object[] copyOf(Object[] oldArray,int newCapacity){ //把就数组的内容复制到新的数组中
Object[] newArray = new Object[newCapacity];
for(int i = 0; i < elementData.length; i++){
newArray[i] = oldArray[i];
}
return newArray;
}
//2.需要设计一个方法,删除元素
public E remove(int index){
//检测index是否合法
this.rangeCheck(index);
//将要删除的元素保存下来,返回给用户
E oldValue = (E)elementData[index];
//删除元素
for(int i = index;i < size-1; i++){
elementData[i] = elementData[i+1];
}
elementData[--size] = null;//末尾元素清空
return oldValue;
}
private void rangeCheck(int index){ //检验index是否合法
if(index < 0 || index > this.size){
System.out.println("导入索引有问题!!!");
}
}
}
第二个解: 这个思路我用到了链表的数据结构
class Node<E> { //定义双向链表的数据结构
private Node prev;//上一个Node对象
private E item; //当前的数据
private Node next;//下一个Node对象
public Node(Node prev,E element,Node next){
this.item = element;
this.next = next;
this.prev = prev;
}
public E getItem() {
return item;
}
public Node getNext() {
return next;
}
public Node getPrev() {
return prev;
}
public void setItem(E item) {
this.item = item;
}
public void setNext(Node next) {
this.next = next;
}
public void setPrev(Node prev) {
this.prev = prev;
}
}
public class List<E>{ //泛型
//先定义头节点和尾节点的属性
private Node first;
private Node last;
private int size = 0;//记录有效元素的个数
//1.增加元素的方法
public boolean add(E element) {
//将element元素存入一个新的node里,挂在链表的尾端
// 调用linkLast方法
this.linkLast(element);
//告知添加成功
return true;
}
private void linkLast(E element){ //将element元素存入一个新的node里,挂在链表的尾端
//获取链表的尾节点
Node l = last;
//创建一个新的Node对象,将新数据包装起来
Node newNode = new Node(l,element,null);
//再将新节点设置为尾节点
last = newNode;
if(l == null){
first = newNode;
}
else{
l.setNext(newNode);
}
//有效元素增加一个
size++;
}
//2.删除元素的方法
public void remove(int index) {
//检测index是否合法
this.rangeCheck(index);
//找到index位置的那个Node
//调用node方法
Node targetNode = this.node(index);
//删除当前元素的目标节点
//调用
this.unLink(targetNode);
//有效元素减少一个
size--;
//返回被删元素
return oldValue;
}
private Node node(int index){ //找寻index对应位置的那个Node对象,将对象中的数据据取出来
Node targetNode;//用来存储当前目标元素的对象
if(index < (index>>1)){
targetNode = first;
for(int i = 0; i < index; i++){
targetNode = targetNode.getNext();
}
}
else{
targetNode = last;
for(int i = size-1; i > index; i--){
targetNode = targetNode.getPrev();
}
}
return targetNode;
}
private void unLink(Node targetNode){
if(targetNode.getPrev() == null){
first = targetNode.getNext();
}else{
targetNode.getPrev().setNext(targetNode.getNext());
}
if(targetNode.getNext() == null){
last = targetNode.getNext();
}else{
targetNode.getNext().setPrev(targetNode.getPrev());
}
targetNode.setNext(null);
targetNode.setPrev(null);
}
private void rangeCheck(int index){ //检验index是否合法
if(index < 0 || index > this.size){
System.out.println("导入索引有问题!!!");
}
}
}
public interface OneToN{
public int disp();
}
public class Pro implements OneToN{
private int n;
public Pro(){}
public Pro(int n){
this.n = n;
}
public void setN(int n){
this.n = n;
}
public int getN(){
return this.n;
}
public int disp(){
int mul = 1;
for(int i = 1; i <= n; i++){
mul *= n;
}
return mul;
}
}
public class Sum implements OneToN{
private int n;
public Sum(){}
public Sum(int n){
this.n = n;
}
public void setN(int n){
this.n = n;
}
public int getN(){
return this.n;
}
public int disp(){
int sum = 0;
for(int i = 1; i <= n; i++){
sum += n;
}
return sum;
}
}
public class Demo{
public static void main(String[] args){
Sum sum = new Sum(10);
Pro pro = new Pro(10);
System.out.println(sum.disp());
System.out.println(pro.disp());
}
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Demo extends Frame implements ActionListener {
private TextField input = new TextField();
private Label output = new Label();
private Button add = new Button("add");
private class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent we){
System.exit(0);
}
}
public Demo(){
super("10");
setup();
add.addActionListener(this);
addWindowListener(new WindowCloser());
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == add){
output.setText(input.getText());
}
}
private void setup(){
Panel top = new Panel();
top.setLayout(new BorderLayout());
top.add("West",add);
top.add("Center",input);
setLayout(new BorderLayout());
add("North",top);
add("Center",output);
}
public static void main(String[] args){
Demo demo = new Demo();
}
}
//
//
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Demo extends Applet implements MouseMotionListener{
private int xstart = -1,
ystart = -1;
private int xend,yend;
private TextField showPosition;
public void init(){
showPosition = new TextField(20);
add(showPosition);
addMouseMotionListener(this);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
xstart = e.getX();
ystart = e.getY();
}
});
}
public void paint(Graphics g){
if(xstart != 1 && ystart != 1){
g.drawRect(xstart,ystart,xend-xstart,yend-ystart);
showPosition.setText("x:" + xend + ",y:" + yend);
}
}
public void mouseDragged(MouseEvent me){
xend = me.getX();
yend = me.getY();
repaint();
}
public void mouseMoved(MouseEvent e) { }
}
在cmd中输入appletviewer Demo.java
,运行即可。
(本人的jdk版本,貌似应该或许是把appletviewer给淘汰了,所以呢,没结果)
这个题目,真他娘的让我屁屁疼,说的啥啊,就不能说的详细点,无语至极。不管了,就瞎几把按照自己的理解写一个了:
搞一个用户界面,要使用Canvas组件,然后在瞎几把搞几个按钮之类的组件上去,点不同的按钮,画布区出现不同的字符串
package canvas;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CanvasTest extends Frame implements ActionListener {
private Button b1 = new Button("zgh");
private Button b2 = new Button("666");
private Button b3 = new Button("cao~~");
private DrawCanvas dc = new DrawCanvas();
public CanvasTest(){
super("12");
init();
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setSize(400,400);
setVisible(true);
}
public void init(){
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout());
buttons.add(b1);
buttons.add(b2);
buttons.add(b3);
setLayout(new BorderLayout());
add("North",buttons);
add("Center",dc);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == b1)
dc.b1();
else if(e.getSource() == b3)
dc.b2();
else
dc.b3();
dc.repaint();
}
public static void main(String[] args) {
CanvasTest ct = new CanvasTest();
}
}
class DrawCanvas extends Canvas{
private String temp = "我是谁?我在哪?";
public void paint(Graphics g){
g.drawString(temp,50,50);
}
public void b1(){
temp = "张国豪";
}
public void b2(){
temp = "张国豪666";
}
public void b3(){
temp = "这个题目真的无语!";
}
}
package additive_computer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Computer extends Frame implements ActionListener {
private Button add = new Button("add");
private Button clean = new Button("clean");
private TextField tf = new TextField(30);
private Label result = new Label();
private double sum = 0;
public Computer(){
super("13");
setup();
add.addActionListener(this);
clean.addActionListener(this);
setSize(400,100);
setVisible(true);
}
public void setup(){
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout());
buttons.add(clean);
buttons.add(add);
buttons.add(tf);
setLayout(new BorderLayout());
add("North",buttons);
add("Center",result);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == add){
sum += new Double(tf.getText());
tf.setText("");
result.setText("结果:" + sum);
}else if(e.getSource() == clean){
sum = 0;
tf.setText("");
result.setText("");
}
}
public static void main(String[] args) {
Computer computer = new Computer();
}
}
package text_editor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextEditor extends Frame implements ActionListener {
private Button copy = new Button("copy");
private Button paste = new Button("paste");
private Button cutting = new Button("cutting");
private TextField ef = new TextField(30);
private TextField show = new TextField(30);
private String temp = null;
public TextEditor(){
super("15");
setup();
copy.addActionListener(this);
paste.addActionListener(this);
cutting.addActionListener(this);
setVisible(true);
setSize(400,100);
}
public void setup(){
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout());
buttons.add(copy);
buttons.add(paste);
buttons.add(cutting);
setLayout(new BorderLayout());
add("North",buttons);
add("Center",ef);
add("South",show);
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == copy){
temp = ef.getText();
}else if(event.getSource() == paste){
show.setText(temp);
}else if(event.getSource() == cutting){
temp = ef.getText();
ef.setText("");
show.setText(temp);
}
}
public static void main(String[] args) {
TextEditor te = new TextEditor();
}
}
package io;
import java.io.*;
public class Homework11 {
public static void main(String[] args) {
File file = new File("E://test.txt");
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(file,true);
dos = new DataOutputStream(fos);
dos.writeInt(6);
dos.writeInt(8);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
dis = new DataInputStream(fis);
double value1 = dis.readDouble();
double value2 = dis.readDouble();
System.out.println(value1 + " " + value2);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
写进去没问题,但是读出来会抛出异常java.io.EOFException
因为int是4个字节,double是8个字节
写两个int
以double来读取时,一次就把两个int读完了,再读一次double,没东西可读,所以抛出异常
这个题目初看,感觉有那么点叫我们写GUI的意思,但是Java的GUI就是一坨不可描述之物,用起来麻烦的要死,而且早就被市场淘汰的技术,真心不想再写了GUI了,我就只把功能实现即可
package io;
import java.io.*;
public class Homework12 {
//创建一个新文件
private void createFile(String path){
File file = new File(path);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取已经存在的文件
private void readFile(File file){
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String value = br.readLine();
while(value != null){
System.out.println(value);
value = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fr != null){
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//修改文本,就是写进去新的内容,把原来的文本覆盖掉
public void modifiy(File file){
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write("我真帅");
bw.newLine();
bw.write("德玛西亚,亚索万岁");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Homework12 h12 = new Homework12();
h12.createFile("E://test.txt");
h12.modifiy(new File("E://test.txt"));
h12.readFile(new File("E://test.txt"));
}
}
package io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Homework15 {
public static void main(String[] args) {
File file = new File("E://prime.dat");
FileWriter fw = null;
try{
fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 2; i <= 200; i++){
boolean isFlag = true;//true素数
for(int j = 2; j <= Math.sqrt(i); j++){
if(i % j == 0){
isFlag = false;
break;
}
}
if(isFlag){
bw.write("" + i); //拼接成串,为了在文件中不乱码
bw.flush();
bw.newLine();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
随便给文件写点什么进去就行了
读文件的线程:
写文件的线程(加一个安全锁):
测试:
其中一次运行结果:
package eight;
import java.awt.*;
import java.util.Date;
public class Clock extends Label implements Runnable{
public Thread clocker = null;
public Clock(){
setText(new Date().toString());
}
public void start(){
if(clocker == null){
clocker = new Thread(this);
clocker.start();
}
}
@Override
public void run() {
Thread currentThread = Thread.currentThread();
if(clocker == currentThread){
setText(new Date().toString());
try{
clocker.sleep(1000);
}catch(InterruptedException ie){
ie.getStackTrace();
}
}
}
public void stop(){
clocker = null;
}
public static void main(String[] args) {
Clock c = new Clock();
c.start();
}
}
逐帧移动呦(下面这个代码纯属搞笑,莫要当真)
package eight;
import javax.swing.*;
import java.awt.*;
public class TickerTape extends JFrame{
private JPanel panel = null;
private JLabel label = null;
private int X;
public TickerTape(int X){
super("八.8");
this.X = X;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setBounds(400,280,560,340);
panel = new JPanel();
add(panel);
panel.setLayout(null);
label = new JLabel("zgh666");
panel.add(label);
label.setBounds(X,160,60,40);
label.setFont(new Font("黑体",Font.BOLD,34));
}
public static void main(String s[]) {
Clock c = new Clock();
int X = 400;
new TickerTape(X);
while(true){
new TickerTape(X);
X-=20;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
做尼玛的applet,拒绝做这玩意
随便把逻辑写一下:
运行后:
开始测试:
首先运行服务端:
然后运行客户端:
再看服务端:
然后在客户端输入数据:
如果对你有帮助,请来一个手有赞香