1.//Fractor.java
public class Fractor{
int m,n;
public Fractor(int m1,int n1){
m=m1;
n=n1;
}
public void add(Fractor a){
int l=n*a.n;
m=n*a.m+m*a.n;
n=l;
}
public void sub(Fractor a){
n=n/a.n;
m=(m-n*a.m)/a.n;
int l=n*a.n;
m=m*a.n-n*a.m;
n=l;
}
String f(int k, int v) {
int i;
if(k>v){
int l;
l=k;
k=v;
v=l;
}
for(i=k;i>0;i--){
if(v%i==0&&k%i==0)
break;
}
return k+" 和 "+v+"最大公约数是:"+i;
}
public void display(){
System.out.println(m+"/"+n);
}
public static void main(String args[]) {
Fractor f1=new Fractor(3,9);
Fractor f2=new Fractor(4,9);
System.out.println(f1.f(3,9));
System.out.print("第一个分数是:");
f1.display();
System.out.print("第二个分数是:");
f2.display();
f1.add(f2);
System.out.print("两个分数相加结果是:");
f1.display();
f1.sub(f2);
System.out.print("两个分数相减结果是:");
f1.display();
}
}
2,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Jueduizhi extends JFrame{
private JLabel label1,label2;
private JTextField field1,field2;
private JButton button1,button2;
public Jueduizhi(){
super("求一个数的绝对值");
Container container=getContentPane();
container.setLayout(new FlowLayout());
label1=new JLabel("输入一个数");
field1=new JTextField(10);
container.add(label1);
container.add(field1);
label2=new JLabel("该数的绝对值是:");
field2=new JTextField(10);
container.add(label2);
container.add(field2);
button1=new JButton("求绝对值");
container.add(button1);
button2=new JButton("退出");
container.add(button2);
ActionEventHandler handler=new ActionEventHandler();
button1.addActionListener(handler);
button2.addActionListener(handler);
setSize(500,150);
setVisible(true);
}
public static void main(String args[])
{
Jueduizhi windiw=new Jueduizhi();
}
private class ActionEventHandler implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource()==button2)
System.exit(0);
else if(event.getSource()==button1){
String a=field1.getText();
int ai=Integer.parseInt(field1.getText());
if( ai>=0){
String result=String.valueOf(a);
field2.setText(result);}
else if(event.getSource()==button1){
if(ai<=0){
String result=String.valueOf(ai-ai-ai);
field2.setText(result);}
}
}
}
}
}
贴上去就对的不是很整齐了
自己看着修改吧