Java計算機二級(上機真題)

浮生了大白發表於2018-08-24
1.
import java.io.*;
public class Java_1 {
    public static void main(String[ ] args) throws IOException {
        InputStreamReader ir;
        BufferedReader in;
        int max, x;
        String data;

        max = 0;
        ir = new InputStreamReader(System.in);
        in = new BufferedReader(ir);
        System.out.println("請輸入5個正整數:");
        //*********Found**********
        for (int i = 1; i<= 5; i++) {
            data = in.readLine();
            //*********Found**********
            x = Integer.parseInt(data);
            if ( max < x )
                //*********Found**********
                max = x;
        }
        System.out.println("輸入的最大值是 "+ max);
    }
}
2.檔案的和遞迴呼叫
import java.io.File;

public class Java_2
{
   public static void main(String s[])
   {
      //Getting the Current Working Directory
      String curDir = System.getProperty("user.dir");
      System.out.println("當前的工作目錄是:"+curDir);
		
      //*********Found**********
      File ff=new File(curDir);
      String[] files=ff.list();
      for(int i=0; i<files.length; i++)
      {
         String ss=curDir+"\\"+files[i];
         traverse(0,ss);	
      }
   }
	
   /**
   * 遞迴地遍歷目錄樹
   * @param  level 目錄的層次
   * @param  s     當前目錄路徑名
   */
   public static void traverse(int level,String s)
   {
      File f=new File(s);
      for(int i=0; i<level; i++) System.out.print("   ");
      if(f.isFile()) 
      {
         System.out.println(f.getName());
      }
      else if(f.isDirectory())
      {
         //*********Found**********
         System.out.println("<"+f.getName()+">");
         String[] files=f.list();
         level++;
         //*********Found**********
         for(int i=0; i<files.length;i++)
         {
            String ss=s+"\\"+files[i];
            //*********Found**********
            traverse(level,ss);
         }
      }
      else
      {
         System.out.println("ERROR!");
      }
   }
}
3.swing構架與AWT事件處理機制

import java.awt.*;
import java.awt.event.*;
//*********Found**********
import javax.swing.*;

public class Java_3 {

    public static void main(String[ ] args) {
        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //*********Found**********
        frame.getContentPane().add(new Change());

        frame.pack();
        frame.setVisible(true);
    }
}

class Change extends JPanel {

    int count = 200;
    JLabel l1;
    JButton b1, b2;

    public Change( ) {
        setPreferredSize(new Dimension(280, 60));
        l1 = new JLabel("200");
        b1 = new JButton("增大");
        b2 = new JButton("減小");
        add(l1);
        //*********Found**********
        add(b1);
        //*********Found**********
        add(b2);
        b1.addActionListener( new BListener( ) );
        b2.addActionListener( new BListener( ) );
    }

    //*********Found**********
    private class  BListener implements ActionListener {

        //*********Found**********
        public void  actionPerformed (ActionEvent e) {
            if (e.getSource( ) == b1) {
                count++;
            } else {
                count--;
            }
            l1.setText("" + count);
        }
    }
}

二
1.考察JOptionPane類
import javax.swing.JOptionPane;  //匯入JOptionPane類

public class Java_1 {
   public static void main( String args[] )
   {
//*********Found********
      JOptionPane.showMessageDialog(
         null, "歡迎\n你\n參加\nJava\n考試!" );
      System.exit( 0 );  // 結束程式
   }
}
/* JOptionPane類的常用靜態方法如下:
   showInputDialog()
   showConfirmDialog()
   showMessageDialog()
   showOptionDialog()
*/

2.
import java.util.Random;

public class Java_2
{
   public static void main(String args[]){
      Random random = new Random();
      float x = random.nextFloat();//產生0.0與1.0之間的一個符點數
      int n = Math.round(20*x);  //構造20以內的一個整數
      long f = 1 ;  //儲存階乘的結果
      int k = 1 ;  //迴圈變數
   //*********Found********
      do{f = k * f;
         k++;
   //*********Found********
      }while(k <= n); 	
      System.out.println(n+"!= "+f);
   }
}

3.
//考察對話方塊綜合使用,首先繼承JFrame類以及實現ActionListener介面。處理GUI事件;浮點輸出格式;//showMessageDialog()顯示資訊
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

     //*********Found********
public class Java_3 extends JFrame implements ActionListener {
   private JTextField input1, input2, output;
   private int number1, number2;
   private double result;

   // 初始化
   public Java_3()
   {
     //*********Found********
      super( "示範異常" );

      Container c = getContentPane();
      c.setLayout( new GridLayout( 3, 2 ) );

      c.add( new JLabel( "輸入分子",
                         SwingConstants.RIGHT ) );
      input1 = new JTextField( 10 );
      c.add( input1 );

      c.add(
         new JLabel( "輸入分母和回車",
                     SwingConstants.RIGHT ) );
      input2 = new JTextField( 10 );
      c.add( input2 );
      input2.addActionListener( this );

      c.add( new JLabel( "計算結果", SwingConstants.RIGHT ) );
      output = new JTextField();
      c.add( output );

      setSize( 425, 100 );
      show();
   }

   //處理 GUI 事件
   public void actionPerformed( ActionEvent e )
   {
      DecimalFormat precision3 = new DecimalFormat( "0.000" );

      output.setText( "" ); // 空的JTextField輸出

     //*********Found********
      try {         
         number1 = Integer.parseInt( input1.getText() );
         number2 = Integer.parseInt( input2.getText() );

         result = quotient( number1, number2 );
     //*********Found********
         output.setText(precision3.format(result));
      }
      catch ( NumberFormatException nfe ) {
         JOptionPane.showMessageDialog( this,
            "你必須輸入兩個整數",
            "非法數字格式",
            JOptionPane.ERROR_MESSAGE );
      }
      catch ( Exception dbze ) {
     //*********Found********
         JOptionPane.showMessageDialog( this, 
            "除法異常",
            "除數為零",
            JOptionPane.ERROR_MESSAGE );
      }
   }

   // 定義求商的方法,如遇除數為零時,能丟擲異常。
     public double quotient( int numerator, int denominator )
      throws Exception
   {
      if ( denominator == 0 )
         throw new Exception();

      return ( double ) numerator / denominator;
   }

   public static void main( String args[] )
   {
      Java_3 app = new Java_3();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               e.getWindow().dispose();
               System.exit( 0 );
            }
         }
      );
   }
}
/* JOptionPane類的常用靜態方法如下:
   showInputDialog()
   showConfirmDialog()
   showMessageDialog()
   showOptionDialog()
*/

三
1.考察Applet使用
//*********Found********
import java.applet.*;
import java.awt.Graphics;

//*********Found********
public class Java_1 extends Applet {  
   public void paint( Graphics g )
   {
//*********Found********
      g.drawString( "歡迎你來參加Java 語言考試!", 25, 25 );
   }
}

2.考察Applet編寫
import java.awt.*;
import java.applet.*;

//*********Found********
public class Java_2 extends Applet
{
    TextArea outputArea;

    public void init()
    {
        setLayout(new BorderLayout());
        outputArea = new TextArea();
     //*********Found********
        add( outputArea );

      // 計算0至10的階乘
        for ( long i = 0; i <= 10; i++ )
            //*********Found********
            outputArea.append(i + "! = " + factorial(i)+ "\n" );
    }
   
   // 用遞迴定義階乘方法
    public long factorial( long number )
    {                  
        if ( number <= 1 )  // 基本情況
            return 1;
        else
            //*********Found********
            return number * factorial( number - 1 );
    }  
}

3.考察Swing與AWT中事件處理
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;

public class Java_3
{
   public static void main(String[] args)
   {
      FontFrame frame = new FontFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

     //*********Found********
class FontFrame extends JFrame
{
   public FontFrame()
   {
      setTitle("沁園春.雪");
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      FontPanel panel = new FontPanel();
      Container contentPane = getContentPane();
     //*********Found********
      contentPane.add(panel);
   }
   public static final int DEFAULT_WIDTH = 300;
   public static final int DEFAULT_HEIGHT = 200;
}

     //*********Found********
class FontPanel extends JPanel
{
   public void paintComponent(Graphics g)
   {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      String message = "數風流人物,還看今朝!";
      Font f = new Font("隸書", Font.BOLD, 24);
      g2.setFont(f);
      FontRenderContext context = g2.getFontRenderContext();
      Rectangle2D bounds = f.getStringBounds(message, context);
      double x = (getWidth() - bounds.getWidth()) / 2;
      double y = (getHeight() - bounds.getHeight()) / 2;
      double ascent = -bounds.getY();
      double baseY = y + ascent;
      g2.setPaint(Color.RED);
     //*********Found********
      g2.drawString(message, (int)x, (int)(baseY));
   }
}

四.
1.
public class Java_1{
  public static void main(String[] args){
    //*********Found**********
    int[] scores = {90,80,75,67,53}; 
    int best = 0; 
    char grade; 

    // 找出這組成績中的最高分
    //*********Found**********
    for (int i=0;i <=4; i++){
      //*********Found**********
      if (scores[i] > best)
        best = scores[i];
    }
 
    //求各分數的等級並顯示
    for (int i=0; i<scores.length; i++){
      if (scores[i] >= best - 10)
        grade = 'A';
      //*********Found**********
      else if (scores[i] >= best - 20)
        grade = 'B';
      else if (scores[i] >= best - 30)
        grade = 'C';
      else if (scores[i] >= best - 40)
        grade = 'D';
      else
        grade = 'F';
      System.out.println("Student " + i + " score is " + scores[i] +
        " and grade is " + grade);
    }
  }
}

2.
public class Java_2 {
    public static void main(String[ ] args) {
        Point pt;
        //*********Found**********
        pt = new Point(2, 3);
        System.out.println(pt);
    }
}

class Point {

    //*********Found**********
    private int x;
    private int y;

    //*********Found**********
    public Point (int a, int b) {
        x = a;
        y = b;
    }

    int getX( ) {
        return x;
    }

    int getY( ) {
        return y;
    }

    void setX(int a) {
        x = a;
    }

    void setY(int b) {
        y = b;
    }

    //*********Found**********
    public String toString ( ) {
        return "( " + x + "," + y + " ) ";
    }
}

3.
import java.awt.*;
import java.awt.event.*;    
//*********Found**********
import javax.swing.*;
   
//*********Found**********
public class Java_3 extends JPanel{     
   
  private int counter = 0;    
   
  private JButton closeAllButton;    
   
  public Java_3() {    
    JButton newButton = new JButton("New");    
    //*********Found**********
    add(newButton);
    newButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent evt){
        CloseFrame f = new CloseFrame();    
        counter++;    
        f.setTitle("窗體 " + counter);    
        f.setSize(200, 150);    
        f.setLocation(30 * counter, 30 * counter);    
        //*********Found**********
        f.setVisible(true);    
        closeAllButton.addActionListener(f); 
      }  
    });
        
    closeAllButton = new JButton("Close all");    
    add(closeAllButton);    
  }      
   
  public static void main(String[ ] args) {    
    JFrame frame = new JFrame();    
    frame.setTitle("多窗體測試");    
    frame.setSize(300, 200);    
    frame.addWindowListener(new WindowAdapter() {    
      public void windowClosing(WindowEvent e) {    
        System.exit(0);    
      }    
    });    
   
    Container contentPane = frame.getContentPane();    
    contentPane.add(new Java_3());   
  
    frame.setVisible(true) ;    
  } 
} 
   
//*********Found**********
class CloseFrame extends JFrame implements ActionListener {    
  public void actionPerformed(ActionEvent evt) {     
    setVisible(false);    
  }    
}

1.矩陣運算
public class Java_1 {

    public static void main(String args[]) {
        int a[][] = {{2, 3, 4}, {4, 6, 5}};
        int b[][] = {{1, 5, 2, 8}, {5, 9, 10, -3}, {2, 7, -5, -18}};
        int c[][] = new int[2][4];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 4; j++) {
                //*********Found********
                c[i][j] = 0 ;
                //*********Found********
                for (int k = 0; k < 3; k++) 
                    //*********Found********
                    c[i][j] += a[i][k]*b[k][j];
                System.out.print(c[i][j] + "  ");
            }
            System.out.println();
        }
    }
}

 

相關文章