《Core Java 卷I》1.
//标准设备输入import javax.swing.*;public class  InputTest
{
public static void main(String[] args) 
{
//get first input
String name = JOptionPane.showInputDialog("What is your name?"); //get second input
String tempinput = JOptionPane.showInputDialog("How old are you?"); int age = Integer.parseInt(tempinput); System.out.println("Hello,"+name+". Next year you will be " + (age + 1)); System.exit(0);
}
}2.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;/**
* A program for viewing images.
*/public class  ImageViewer
{
public static void main(String[] args) 
{
JFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
* A frame with a label to show an image.
*/class ImageViewerFrame extends JFrame
{
private JLabel label;
private JFileChooser chooser;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 400; public ImageViewerFrame()
{
setTitle("ImageVierwer");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); //use a label to display the images
label = new JLabel();
Container contentPane = getContentPane();
contentPane.add(label); //set up the file chooser
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(".")); //set up the menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar); JMenu menu = new JMenu("File");
menuBar.add(menu); JMenuItem openItem = new JMenuItem("Open");
menu.add(openItem); openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
//show file chooser dialog
int r = chooser.showOpenDialog(null); //if file selected,set it as icon of the label
if(r == JFileChooser.APPROVE_OPTION);
{
String name = chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
}
}
}
); JMenuItem exitItem = new JMenuItem("Close");
menu.add(exitItem);
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
System.exit(0);
}
}
);
menu = new JMenu("Tool");
menuBar.add(menu); JMenuItem fixItem = new JMenuItem("fix");
menu.add(fixItem);
}
}3.applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;public class  WelcomeApplet extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout()); JLabel label = new JLabel(getParameter("greeting"),SwingConstants.CENTER);
label.setFont(new Font("Serif", Font.BOLD, 18));
contentPane.add(label, BorderLayout.CENTER); JPanel panel = new JPanel(); JButton googleButton = new JButton("Google Site");
googleButton.addActionListener(makeURLActionListener("http://www.google.com"));
panel.add(googleButton); JButton mailButton = new JButton("Mail Me");
mailButton.addActionListener(makeURLActionListener("mailto:[email protected]"));
panel.add(mailButton); contentPane.add(panel, BorderLayout.SOUTH); } private ActionListener makeURLActionListener(final String u)
{
return new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
getAppletContext().showDocument(new URL(u));
}catch(MalformedURLException e)
{
e.printStackTrace();
}
}
};
}
}
<HTML>
<HEAD>
<TITLE> Welcome Applet </TITLE>
</HEAD><BODY><hr>
<p>
This applet is from the book
<a href = "http://www.csdn.net">
CSDN SITE
</a>
by
<em>
Google Site
</em>
and
<em>
Mail Me
</em>,published by Sun Microsystems Press.
</p><applet code = "WelcomeApplet.class" width="400" height="200">
<param name="greeting" value="Welcome to Core Java">
</applet><hr>
<p><a href = "WelcomeApplet.java">The source</a></p></BODY>
</HTML>

解决方案 »

  1.   

    /**
    * author: YinLei
    * java.lang.String 主要的API注解,例子
    * Version: 1.0
    */
    public class StringTest
    {
    public static void main(String[] args) 
    {
    String oldString = "JustForTest";
    String otherString = "";
    String newString = "";
    /*
      Methord: char charAt(int index)
      Description:  返回指定位置的字符
    */
    System.out.println("1.char charAt(int index)");
            System.out.println(oldString.charAt(2) + "\n");
    /*
      Methord: int compareTo(String orther)
      Description: 如果字符串依照字典顺序在other串的前面,返回负值;
    如果字符串依照字典顺序在other串的后面,返回正值;
    如果两者相等,返回0。
     */
    System.out.println("2.int compareTo(String orther)");
    otherString = "JustForTes";
    System.out.println(oldString.compareTo(otherString) + "\n");
    /*
      Methord: boolean endsWith(String suffix)
      Description: 如果字符串是以suffix结尾,返回true
    */
    System.out.println("3.boolean endsWith(String suffix)");
    /*
      Methord: boolean equals(String other)
      Description: 如果与字符串是以other相等,返回true
    */
    System.out.println("4.boolean equals(Object other)\n");
    /*
      Methord: boolean equalsIgnoreCase(String other)
      Description: 如果与字符串是以other相等(不区分大小写),返回true
    */
    System.out.println("5.boolean equalsIgnoreCase(String other)\n"); /*
      Methord: int indexOf(String str)
                    int indexOf(String str,int fromIndex)
      Description: 返回从0或索引fromIndex开始的与str相互匹配的第一个字符串的开始位置
    */
    System.out.println("6.int indexOf(String str,int fromIndex)\n"); /*
      Methord: int lastIndexOf(String str)
                    int lastIndexOf(String str,int fromIndex)
      Description: 返回从0或索引fromIndex开始的与str相互匹配的最后一个字符串的开始位置
    */
    System.out.println("7.int lastIndexOf(String str,int fromIndex)\n"); /*
      Methord: int length()
      Description: 返回字符串长度
    */
    System.out.println("8.int length()\n"); /*
      Methord: String replace(char oldChar,char newChar)
      Description: 返回用字符newChar替换oldChar字符后得到的新的字符串
    */
    System.out.println("9.String replace(char oldChar,char newChar)\n"); /*
      Methord: boolean startsWith(String prefix)
      Description: 如果字符串是以suffix开始,返回true
    */
    System.out.println("10.startsWith(String prefix)\n"); /*
      Methord: String subString(int beginIndex)
    String subString(int beginIndex,int endIndex)
      Description: 返回原串从beginIndex开始到endIndex为止(不包括endIndex)的新字符串
    */
    System.out.println("11.String subString(int beginIndex,int endIndex)\n"); /*
      Methord: String toLowerCase()
    String toUpperCase()
      Description: 转换大小写,返回得到的新串
    */
    System.out.println("12.String toLowerCase()/toUpperCase()\n"); /*
      Methord: String trim()
      Description: 把原串中所有的开始和结尾空格去掉,返回得到的新串
    */
    System.out.println("13.String trim()\n");
    }
    }
      

  2.   

    /**
    * author: YinLei
    * java.math.BigInteger 主要的API注解,例子
    * java.math.BigDecimal 与此类似
    * Version: 1.1
    */import javax.swing.*;
    import java.math.*;public class BigIntegerTest
    {
    public static void main(String[] args) 
    { /*
      Methord: BigInteger add(BigInteger other)
    BigInteger subtract(BigInteger other)
    BigInteger multiply(BigInteger other)
    BigInteger divide(BigInteger other)
    BigInteger mod(BigInteger other)
      Description:  返回此大整数和大整数other的和,差,积,商及余数.
    */
    /*
      Methord: int compareTo(BigInteger other)
      Description:  如果此大整数等于other,则返回0;
    如果小于other,则返回负数;
    否则返回正数.
    */
    /*
      Methord: static BigInteger valueOf(long x)
      Description:  返回值等于x的大整数.
    */
    String input = JOptionPane.showInputDialog("How many numbers do you need to draw?");
    int k = Integer.parseInt(input); input = JOptionPane.showInputDialog("What is the hightest number you can draw?");
    int n = Integer.parseInt(input); /*
    computer binomial coefficient
    n * ( n - 1 ) * ( n - 2 ) * ...... * ( n - k -1 )
    -------------------------------------------------
    1 * 2 * 3 * ...... * k
    */ BigInteger lotteryOdds = BigInteger.valueOf(1); for(int i = 1; i <= k; i++)
    {
    lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n -i + 1)).divide(BigInteger.valueOf(i));
    } System.out.println("Your odds are 1 in " + lotteryOdds); System.exit(0);
    }
    }
      

  3.   

    /**
    * author: YinLei
    * java.text.NumberFormat 主要的API注解,例子
    * Version: 1.1
    */import java.text.NumberFormat;
    import java.util.Locale;public class NumberFormatTest
    {
    public static void main(String[] args) 
    {
    double v1 = 10000.0/3.0;
    NumberFormat formatter = NumberFormat.getNumberInstance();
    String r1 = ""; double v2 = 10000.0/6.3;
    NumberFormat formatter2 = NumberFormat.getNumberInstance(); /*
      Methord: String format(double number)
      Description:  返回包含格式化数字的字符串
    */
    System.out.println("0.String format(double number)"); /*
      Methord: static NumberFormat getCurrencyInstance()
      Description:  返回一个NumberFormat对象,以按照当前地区的规则把货币转换成字符串
    */
    System.out.println("1.getCurrencyInstance()");
    formatter = NumberFormat.getCurrencyInstance(Locale.CHINA);
    r1 = formatter.format(v1);
    System.out.println(r1); /*
      Methord: static NumberFormat getNumberInstance()
      Description:  返回一个NumberFormat对象,以按照当前地区的规则格式化数字
    */
    System.out.println("2.getNumberInstance()");
    formatter = NumberFormat.getNumberInstance(Locale.CHINA);
    r1 = formatter.format(v1);
    System.out.println(r1); /*
      Methord: static NumberFormat getCurrencyInstance()
      Description:  返回一个NumberFormat对象,把百分数转化成字符串
    */
    System.out.println("3.getPercentInstance()");
    formatter = NumberFormat.getPercentInstance(Locale.CHINA);
    r1 = formatter.format(v1);
    System.out.println(r1); /*
      Methord: void setMaximumFractionDigits(int digits)
      Description:  为格式化对象设定小数点后面显示的最多位数,显示的最后一位是四舍五入的
    */
    System.out.println("4.void setMaximumFractionDigits(int digits)");
    /*
      Methord: void setMaximumIntegerDigits(int digits)
      Description:  为格式化对象设定小数点前面显示的最多位数,如果指定位数太少,数字会被简单地截掉
    */
    System.out.println("5.void setMaximumIntegerDigits(int digits)");
    formatter2 = NumberFormat.getNumberInstance(Locale.CHINA);
    formatter2.setMaximumFractionDigits(4);
    formatter2.setMaximumIntegerDigits(6);
    r1 = formatter2.format(v2);
    System.out.println(r1);
    /*
      Methord: void setMinimumFractionDigits(int digits)
      Description:  为格式化对象设定小数点后面显示的最少位数,不够在后面补0
    */
    System.out.println("6.void setMinimumFractionDigits(int digits)");
    /*
      Methord: void setMinimumFractionDigits(int digits)
      Description:  为格式化对象设定小数点前面显示的最多位数,不够在前面补0
    */
    System.out.println("7.void setMinimumFractionDigits(int digits)");
    v1 = 10.0/8;
    formatter = NumberFormat.getNumberInstance(Locale.CHINA);
    formatter.setMinimumFractionDigits(3);
    formatter.setMinimumIntegerDigits(3);
    r1 = formatter2.format(v1);
    System.out.println(r1); }
    }
      

  4.   

    /**
    * author: YinLei
    * java.util.Arrays 主要的API注解,例子
    * Version: 1.2
    */import java.util.*;public class ArraysTest
    {
    public static void main(String[] args) 
    {
    /*
      Methord: static void sort(Xxx[] a)
      Description:  类型为int,long,short,char,byte,boolean,float或double的数组使用优化的快速排序
    */
    System.out.println("1.static void sort(Xxx[] a)");
    int[] testArray = {199,1,8,68,27}; Arrays.sort(testArray);
    for(int i = 0; i < testArray.length; i++)
    System.out.print(testArray[i]+" ");
    System.out.println("\n*****************************************************");
    /*
      Methord: static int binarySearch(Xxx[] a, Xxx v)
      Description:  a----类型为int,long,short,char,byte,boolean,float或double的已排序数组
    v----与a元素类型相同的值
    利用二分搜索算法查找v值。
    如果找到返回其下标;否则返回负值r;-r-1为要保持有序数组时应该插入v的位置
    */
    System.out.println("2.static int binarySearch(Xxx[] a, Xxx v)");
    int index = Arrays.binarySearch(testArray,7);
    System.out.print(index);
    System.out.println("\n*****************************************************");
    /*
      Methord: static boolean equals(Xxx[] a, Object other)
      Description:  a--------类型为int,long,short,char,byte,boolean,float或double的已排序数组
    other----一个对象
    如果other是与a类型和长度均相同的数组,而且对应下标所指向的元素都相等,返回true
    */
    System.out.println("3.static boolean equals(Xxx[] a, Object other)");
    int[] otherArray = {1,8,27,68,199};
    boolean result = Arrays.equals(testArray,otherArray);
    System.out.print(result);
    System.out.println("\n*****************************************************"); /*
      Methord: static void fill(Xxx[] a, Xxx v)
      Description:  a----类型为int,long,short,char,byte,boolean,float或double的已排序数组
    v----与a元素类型相同的值
    把数组所有元素的值都赋为v
    */
    System.out.println("4.static void fill(Xxx[] a, Xxx v)");
    Arrays.fill(testArray,9);
    for(int i = 0; i < testArray.length; i++)
    System.out.print(testArray[i]+" ");
    System.out.println("\n*****************************************************"); }
    }
      

  5.   

    import java.util.*;public class CalendarTest
    {
    public static void main(String[] args) 
    {
    //construct d as current date
    GregorianCalendar d = new GregorianCalendar(); int today = d.get(Calendar.DAY_OF_MONTH);
    int month = d.get(Calendar.MONTH);        //set d to start date of the month
    d.set(Calendar.DAY_OF_MONTH, 1); int weekday = d.get(Calendar.DAY_OF_WEEK); System.out.println("a::::"+weekday+" "+Calendar.SATURDAY+" "+month+" "+Calendar.MONTH+"   "+today);
    //print heading
    System.out.println("Sun Mon Tue Wed Thu Fri Sat"); for(int i = Calendar.SUNDAY; i < weekday; i++)
    System.out.print("    "); do
    {
    //print day
    int day = d.get(Calendar.DAY_OF_MONTH);
    if(day < 10)  System.out.print(" ");
    System.out.print(day); // current day with *
    if(day == today)
    System.out.print("* ");
    else
    System.out.print("  ");
    //start a new line after every Saturday
    if(day % 7 == (7 - weekday + 1))
    System.out.println(); //advance d to the next_day
    d.add(Calendar.DAY_OF_MONTH, 1);
    //weekday = d.get(Calendar.DAY_OF_MONTH);
    }
    while(d.get(Calendar.MONTH) == month);
    //the loop exit wher d is day 1 of the next month //print final end of line if necessary
    if(weekday != Calendar.SUNDAY)
    System.out.println(); }
    }
      

  6.   

    //将二维数组作为两个一维数组操作public class LotteryArry
    {
    public static void main(String[] args) 
    {
    final int NMAX = 10;

    //allocate triangular array
    int[][] odds = new int[NMAX + 1][];
    for(int n = 0; n <= NMAX; n++)
    odds[n] = new int[n + 1]; //fill triangular array
    for(int n = 0; n < odds.length; n++)
    for(int k = 0; k < odds[n].length; k++)
    {
    int lotterOdds = 1;
    for(int i = 1; i <= k; i++)
    lotterOdds = lotterOdds * (n -i + 1) / i; odds[n][k] = lotterOdds;
    } //print triangular array
    for(int n = 0; n < odds.length; n++)
    {
    for(int k = 0; k < odds[n].length; k++)
    {
    String output = "    " + odds[n][k];
    output = output.substring(output.length() - 4);
    System.out.print(output);
    }
    System.out.println();
    }
    }
    }
      

  7.   

    import java.util.*;public class EmployeeTest
    {
    public static void main(String[] args) 
    {
    Employee yinlei = new Employee();
    Date d = yinlei.getHireDay();
    System.out.println(d.toString()); //double oneYearsInMilliSecond = 1 * 365.0 * 24 * 60 * 60 * 1000;
    long oneYearsInMilliSecond2 = (long)1 * 365 * 24 * 60 * 60 * 1000;//注意一定要用 (long)强行转化 d.setTime( d.getTime() + oneYearsInMilliSecond2 );
    Date t = yinlei.getHireDay();
    System.out.println(t.toString());
    }
    }
    class Employee
    {
    private Date hireDay; public Employee()
    {
    GregorianCalendar calendar = new GregorianCalendar(2006,3,28);
    hireDay = calendar.getTime(); } public Date getHireDay()
    {
    return (Date)hireDay.clone();//如果不用clone()方法,d和hireDay.hireDay指向了同一个对象,
                                  //对的d应用的更改方法会改变这个员工对象的私有状态
    }
    }