程式練習--01 - NTUCSIE的創作 - 巴哈姆特

創作內容

3 GP

程式練習--01

作者:Breguet│2013-04-26 11:55:18│巴幣:6│人氣:1161
---------------------------------------------------------------------------------------------------------------------
雖然不是什麼了不起的code 但希望能放上來 算是教學相長8
---------------------------------------------------------------------------------------------------------------------
攝氏轉華氏
---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[] args) {  
   
         Scanner input =new Scanner(System.in);  
   
        double celsius = input.nextDouble();  
        double fahrenheit = (9.0/5)*celsius+32;  
   
        System.out.println((int)fahrenheit);  
    }  
}  

---------------------------------------------------------------------------------------------------------------------
營業稅計算
營業稅 = 銷售金額 * 稅率, 應付總額 = 銷售金額 + 營業稅
---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[] args){  
        Scanner input=new Scanner(System.in);  
        double    money=input.nextDouble();  
        int       tax=input.nextInt();  
        double    saletax=money*(tax*0.01);  
        double    result=money+saletax;  
    System.out.println((int)(saletax*100)*0.01+" "+(int)(result*100)*0.01);  
    }  
}  

---------------------------------------------------------------------------------------------------------------------
BMI計算
import java.util.Scanner;  
public class Main {  
public static void main(String[]args){  
Scanner input=new Scanner(System.in);  
double tall=input.nextDouble();  
double heavy=input.nextDouble();  
double realtall=tall*0.01;  
double BMI=heavy/((realtall)*(realtall));  
System.out.println((int)(BMI));               
}  
}  
---------------------------------------------------------------------------------------------------------------------
Finding the Number of Days in a Month

Problem Description:
Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2000, the program should display 29.
---------------------------------------------------------------------------------------------------------------------

import java.util.Scanner;  
public class Main {  
public static void main(String[]args){  
    Scanner input = new Scanner(System.in);  
        int month=input.nextInt();  
        int year=input.nextInt();  
    if(month==1^month==3^month==5^month==7^month==8^month==10^month==12)  
        System.out.println("31");  
    if(month==4^month==6^month==9^month==11)  
        System.out.println("30");  
    if(month==2&&year%4==0&&year%100==0&&year%400==0)  
        System.out.println("29");  
    else if(month==2&&year%100==0&&year%400!=0)  
        System.out.println("28");  
}  
}  
---------------------------------------------------------------------------------------------------------------------
Scissor, Rock, Paper

Problem Description
Write a program that plays the popular scissor-rock-paper game. The numbers 0, 1, and 2 represent scissor, rock, and paper, respectively. Write a program to read two numbers where the first number represents the input from the user and the second number represents the input from the computer, respectively. Display the result.

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[] args){  
    Scanner input=new Scanner(System.in);  
        double a=input.nextDouble();  
        double b=input.nextDouble();  
        if(a==b)  
            System.out.println("Draw");  
        if(a==0&&b==2)  
            System.out.println("You win");  
        if(a==1&&b==0)  
            System.out.println("You win");  
        if(a==2&&b==1)  
            System.out.println("You win");  
        if(b==0&&a==2)  
            System.out.println("You lose");  
        if(b==1&&a==0)  
            System.out.println("You lose");  
        if(b==2&&b==1)  
            System.out.println("You lose");  
    }  
    }
---------------------------------------------------------------------------------------------------------------------
計算1到N之間屬於5或7的倍數(但非兩者同時)的總和
---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[]args){  
        Scanner input =new Scanner(System.in);  
        int a=input.nextInt();  
        int sum=0;  
        int x=0;  
          
    for(int n=1;n<=a;n++){  
        if(n%5==0&&n%7!=0)  
            sum+=n;  
        if(n%7==0&&n%5!=0)  
            sum+=n;  
    }System.out.println(sum);  
    }  
}
---------------------------------------------------------------------------------------------------------------------
位元計數器

輸入一整數 n ,計算以二進制表示的 n 有幾個位元為 1 。

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;   
public class Main {  
    public static void main(String[]args){  
        Scanner input = new Scanner(System.in);  
        int EnterNumber = input.nextInt();  
        int count=0;  
        int multiple=EnterNumber;  
        while(true){  
            multiple=multiple/2;  
            if(multiple%2==1)  
                count++;  
            if(multiple/2==0)  
                break;  
               continue;  
        }  
          
        if(EnterNumber%2==0)  
            System.out.println(count);  
        else if(EnterNumber%2!=0)  
            System.out.println((count+1));        
    }  
}
---------------------------------------------------------------------------------------------------------------------
爬樓梯

問題描述
小明有個習慣,爬樓梯有時會一階一階爬,也會一次爬二階,隨意交替。當他遇到樓梯有 N 階時他可以有幾種不同的爬法來爬完 N 階 (附註: 如果樓梯有4階,則先爬一階,再爬一階,再爬兩階,這和先爬兩階,再爬一階,再爬一階,算是兩種不同爬法。)

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
public static void main (String[]args){  
    Scanner input= new Scanner(System.in);  
    long n = input.nextLong();  
    long number1=0,number2=1,number3;  
    for(int i=0;i<n;i++){  
        number3=number2;  
        number2+=number1;  
        number1=number3;         
    }  
    System.out.println(number2);     
}  
}  

---------------------------------------------------------------------------------------------------------------------
Sorting three numbers

Problem Description
Write the following method that accepts three numbers and print them (one number each line) in decreasing order:

public static void displaySortedNumbers(double num1, double num2, double num3)

Write a main program that reads in three numbers and invoke the method to print those numbers (one number each line) in decreasing order.
---------------------------------------------------------------------------------------------------------------------

import java.util.Scanner;  
public class Main {  
       public static void main (String[]args){  
           Scanner input= new Scanner(System.in);  
           double num1=input.nextDouble();  
           double num2=input.nextDouble();  
           double num3=input.nextDouble();  
           displaySortedNumbers(num1, num2, num3);  
       }  
       public static void displaySortedNumbers(double num1, double num2, double num3){  
           double highnum=0;  
           double midnum=0;  
           double lownum=0;  
           if(num1>num2&&num2>num3){  
               highnum=num1;  
               midnum =num2;  
               lownum =num3;  
           }  
           else if(num1>num3&&num3>num2){  
               highnum=num1;  
               midnum =num3;  
               lownum =num2;  
           }     
           else if(num2>num1 &&num1>num3){  
               highnum=num2;  
               midnum =num1;  
               lownum =num3;  
           }   
           else if(num2>num3 &&num3>num1){  
               highnum=num2;  
               midnum =num3;  
               lownum =num1;  
           }     
           else if(num3>num1 &&num1>num2){  
               highnum=num3;  
               midnum =num1;  
               lownum =num2;  
           }  
           else if(num3>num2 &&num2>num1){  
               highnum=num3;  
               midnum =num2;  
               lownum =num1;  
           }     
           System.out.println(highnum);  
           System.out.println(midnum);  
           System.out.println(lownum);  
       }      
}  
---------------------------------------------------------------------------------------------------------------------

Testing if a number is prime

Problem Description
Write an isPrime(int number) method for testing whether a number is prime (You can reuse the one in the textbook). Write a main program to read in an integer and invoke the isPrime method to check whether the number is prime, and print "is prime" or "not prime" accordingly.

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[]args){  
    Scanner input=new Scanner(System.in);  
    int num=input.nextInt();  
    isPrime(num);  
    }  
    public static void isPrime(int num){  
        for(int n=2;n<=num;n++){  
        if(num%n==0&&n!=num){  
        System.out.println("not prime");   
        break;  
        }  
        if(num%n!=0&&n<num){  
        continue;  
        }  
        if(num%n==0&&n==num){  
        System.out.println("is prime");  
        break;  
        }  
        }  
    }  
}
---------------------------------------------------------------------------------------------------------------------
Game: Blackjack

Problem Description
Write an isBlackJack(int c1, int c2) method that accepts two integers as two cards from a deck of 52 cards, and returns true if the two cards sum to 21 (Blackjack). The 52 cards are numbered from 0 to 51. Card numbers 0 to 12 represent Ace, Two, ..., to King of Spades. Card numbers 13 to 25, 26 to 38, 39 to 51 represent 13 Hearts, 13 Diamonds, and 13 Clubs, respectively. Note that an Ace counts as 11 and Jacks, Queens, Kings count as 10. Write a main method that reads in two integers as two cards, invoke the above method, and output "true" if the two cards form a Blackjak, and "false" otherwise.

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;      
public class Main {      
    public static void main(String[]args){      
    Scanner input=new Scanner(System.in);      
    int c1=input.nextInt();      
    int c2=input.nextInt();      
    isBlackjack(c1,c2);      
    }      
    public static void isBlackjack(int c1,int c2){      
    c1=c1%13;      
    c2=c2%13;      
    if(c1==0)      
        c1=11;      
    else if(c1==9||c1==10||c1==11||c1==12)      
        c1=10;      
    if(c2==0)      
        c2=11;      
    else if(c2==9||c2==10||c2==11||c2==12)      
        c2=10;      
    int num=c1+c2;      
    if(num==21)      
        System.out.println("true");      
    else      
        System.out.println("false");      
    }      
}

---------------------------------------------------------------------------------------------------------------------
Counting occurrence of numbers

roblem Description
Write a program that reads a list of integers between 1 and 100. Assume the input ends with 0. Count the occurrences of each number, and report how many numbers that occur at least two times.

Input Format
The input consists of a list of integers that ends with 0. An integer may appear multiple times.

Output Format
The number of integers that occur at least twice.
---------------------------------------------------------------------------------------------------------------------
import java.util.Arrays;  
import java.util.Scanner;  
public class Main {  
    public static void main(String args[]){  
        Scanner input= new Scanner(System.in);  
        short checkNum[]=new short[100];  
        short anotherNum[]=new short[101];  
        short mid=0;  
        short count=0;  
        for(short i=0;i<100;i++)  
            checkNum[i]=(short)(i+1);  
        for(short i=0;true;i++){  
            short n=input.nextShort();  
            if(n==0)  
                break;  
            mid=(short) Arrays.binarySearch(checkNum,n);  
            anotherNum[mid]++;  
        }  
        for(int i=0;i<100;i++){  
            if(anotherNum[i]>1){  
                count++;  
            }  
        }  
        System.out.println(count);    
    }  
}  
---------------------------------------------------------------------------------------------------------------------
Locating the largest element

Problem Description

Write the following method that returns the location of the largest element in a two-dimensional array: public static int[] locateLargest(double[][] a). The return value is a one-dimensional array that contains two elements, which indicate the row and column indices of the largest element in the two-dimensional array. Write a main method that reads in the size of the array and the contents of the array, invokes the locateLargest() method, and displays the location of the largest element.

Input Format

The first line of the input contains two integers indicating the number of rows and columns. Each remaining line contains data of each row.

Output Format

Output two integers representing the location of the largest element. Note that the first element of the array is assumed at location (0,0)

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String[]args){  
        Scanner input =new Scanner(System.in);  
        int enterNum1=input.nextInt();  
        int enterNum2=input.nextInt();  
        double [][] list =new double [enterNum1][enterNum2];  
        for(int row=0;row<list.length;row++){  
            for(int column=0;column<list[row].length;column++){  
                list[row][column]=input.nextDouble();  
            }  
        }  
          
        locateLargest(list);  
          
    }  
    public static int[] locateLargest(double[][] a){  
        double max=0;  
        double LargestRow,LargestColumn;  
        int finalNUM []=new int[2];  
        for(int row=0;row<a.length;row++){  
            for(int column=0;column<a[row].length;column++){  
                if(a[row][column] >max){  
                    max=a[row][column];  
                    finalNUM [0]=row;  
                    finalNUM [1]=column;  
                }  
            }  
              
        }  
        System.out.println(finalNUM[0]+" "+finalNUM[1]);  
        return finalNUM;  
    }  
}  
---------------------------------------------------------------------------------------------------------------------
好數問題

題目說明: 如果某一個四位數,恰好其中只有兩個數字相同,則稱為「好數」,例如: 1223, 3464, 9001 就算好數。但若有三個或四個數相同,或是多於一組的數字相同,如 1333, 5535, 2244 都不算是好數。請寫一個程式,讀入一個四位數整數,並判斷該整數是否為好數。若是好數則印出Yes,若不是則印出No。
輸入說明: 一個四位數整數

輸出說明: 若是好數則印出Yes,若不是則印出No

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String args[]){  
        Scanner input=new Scanner(System.in);  
        int Num=input.nextInt();  
        int a=Num/1000;  
        int b=(Num%1000)/100;  
        int c=(Num%100)/10;  
        int d=Num%10;  
          
        if(a==b&&a!=c&&a!=d&&c!=d)  
            System.out.println("Yes");  
        else if(a==c&&a!=b&&a!=d&&b!=d)  
            System.out.println("Yes");  
        else if(a==d&&a!=c&&a!=b&&c!=b)  
            System.out.println("Yes");  
        else if(b==c&&b!=a&&b!=d&&a!=d)  
            System.out.println("Yes");  
        else if(b==d&&b!=c&&b!=a&&a!=c)  
            System.out.println("Yes");  
        else if(c==d&&c!=a&&c!=b&&a!=b)  
            System.out.println("Yes");  
        else  
            System.out.println("No");  
    }  
}  

---------------------------------------------------------------------------------------------------------------------
Occurrences of Each Digit in a String

Problem Description
Write a method that counts the occurrences of each digit in a string using the following header:

   public static int[ ]  count(String s)

The method counts how many times a digit appears in the string. The return value is an array of ten elements, each of which holds the count for a digit. For example, after executing int [ ] counts = count("12203AB3"), counts[0] is 1, counts[1] is 1, counts[2] is 2, and counts[3] is 2.

Write a main method that reads a string, calls the count() method, and displays the number of occurrences of each digit in the string.

Input Format
A string

Output Format
Ten integers representing the number of occurrences of digit 0, 1, ..., 9.
---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;   
public class Main {   
  public static void main(String args[]){   
        Scanner input=new Scanner(System.in);   
      String str=input.next();   
       int count []=new int [10];   
     for(int i=0;i<str.length();i++){   
            if(str.charAt(i)=='0')   
             count[0]++;   
            if(str.charAt(i)=='1')   
             count[1]++;   
            if(str.charAt(i)=='2')   
             count[2]++;   
            if(str.charAt(i)=='3')   
             count[3]++;   
            if(str.charAt(i)=='4')   
             count[4]++;   
            if(str.charAt(i)=='5')   
             count[5]++;   
            if(str.charAt(i)=='6')   
             count[6]++;   
            if(str.charAt(i)=='7')   
             count[7]++;   
            if(str.charAt(i)=='8')   
             count[8]++;   
            if(str.charAt(i)=='9')   
             count[9]++;   
        }   
          System.out.println(count[0]+" "+count[1]+" "+count[2]+" "+count[3]+" "+count[4]+" "+count[5]+" "+count[6]+" "+count[7]+" "+count[8]+" "+count[9]);   
}   
}  
---------------------------------------------------------------------------------------------------------------------
Displaying the prime factors
Problem Description
Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. For example, if the integer is 120, the smallest factors are displayed as 5 3 2 2 2. In your program, use the StackOfIntegers class in Listing 10.8 of the textbook (page 383) to store the factors first (e.g., 2 2 2 3 5) and retrieve and display them in the desirable order.

Input Format
an integer

Output Format
Print all its smallest factors in decreasing order.

---------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
import java.util.Arrays;  
public class Main{  
    public static void main(String[] args){  
        Scanner input = new Scanner(System.in);  
        int integer = input.nextInt();  
        StackOfIntegers stack = new StackOfIntegers();  
        int temp = integer;   
            for(int i = 2 ; i < temp / 2 && integer > 1; i++){  
                while(integer % i == 0){  
                    stack.push(i);  
                    integer /= i;  
                }  
            }  
            while(stack.getSize() > 1)  
                System.out.print(stack.pop() + " ");  
            System.out.println(stack.pop());  
        }  
    }  
class StackOfIntegers {  
    private int[] elements;  
    private int size;  
    public static final int DEFAULT_CAPACITY = 16;  
    public StackOfIntegers() {  
        this(DEFAULT_CAPACITY);  
    }  
    public StackOfIntegers(int capacity) {  
        elements = new int[capacity];  
    }  
    public void push(int value) {  
        if(size >= elements.length) {  
            int[] temp = new int[elements.length * 2];  
            System.arraycopy(elements,0,temp,0,elements.length);  
            elements = temp;  
        }  
        elements[size++] = value;  
    }  
    public int pop() {  
        return elements[--size];  
    }  
    public int peek() {  
        return elements[size - 1];  
    }  
    public boolean empty() {  
        return size == 0;  
    }  
    public int getSize() {  
        return size;  
    }  
}
-----------------------------------------------------------------------------------------------------------------
Creating four fans
-----------------------------------------------------------------------------------------------------------------
import javax.swing.*;
import java.awt.*;

public class fans extends JFrame{
public static void main(String args[]){
fans fansArc =new fans();
fansArc.setLocationRelativeTo(null);
fansArc.setSize(300,300);
fansArc.setTitle("Excercise15_9");
fansArc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fansArc.setVisible(true);
}
fans(){
setLayout(new GridLayout(2,2,1,1));
for(int i=0;i<4;i++){
add(new drawFans());
}
}
}
class drawFans extends JPanel{
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
int x=getWidth()*9/10;
int y=getHeight()*9/10;
//x & y Arcs
int x1=x*7/8;
int y1=y*7/8;
//Center
int xCenter=x/2;
int yCenter=y/2;
g.drawOval(0,0,x,y);
g.setColor(Color.RED);
g.fillArc(xCenter-x1/2,yCenter-y1/2,x1,y1,10,30);
g.fillArc(xCenter-x1/2,yCenter-y1/2,x1,y1,100,30);
g.fillArc(xCenter-x1/2,yCenter-y1/2,x1,y1,190,30);
g.fillArc(xCenter-x1/2,yCenter-y1/2,x1,y1,280,30);
}
}
-----------------------------------------------------------------------------------------------------------------
Display a bar chart


import javax.swing.*;
import java.awt.*;

public class Bar_Chart extends JFrame{
public static void main(String args[]){
Bar_Chart chart=new Bar_Chart();
chart.setLocationRelativeTo(null);
chart.setSize(300,300);
chart.setTitle("Excercise15_9");
chart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chart.setVisible(true);
}
Bar_Chart(){
add(new drawBarChart());
}
}
class drawBarChart extends JPanel{
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setLayout(new GridLayout(1,4,2,2));
int x=getWidth();
int y=getHeight();
int x1=x/30;
int y1=y/30;
int width=(x-6*x1)/4;
int height=(y-3*y1)/4;
g.setColor(Color.black);
g.drawLine(x1/2, (y1*2+height*2)+2*height,x-x1,(y1*2+height*2)+2*height);
//20% project
g.setColor(Color.red);
g.fillRect(x1, y1*2+height*2, width, 2*height);
g.setColor(Color.black);
g.drawString("Project--20%", x1, y1*2+height*2-y1);
//10% quizzes
g.setColor(Color.blue);
g.fillRect(2*x1+width,y1*2+height*3 , width, height);
g.setColor(Color.black);
g.drawString("Quizzes--10%", x1+x1+width, y1*2+height*3-y1);
//30% midterms1
g.setColor(Color.green);
g.fillRect(3*x1+2*width,y1*2+height , width, 3*height);
g.setColor(Color.black);
g.drawString("Midterms--30%", x1+2*x1+2*width, y1*2+height-y1);
//40% final
g.setColor(Color.orange);
g.fillRect(4*x1+3*width,y1*2 , width, 4*height);
g.setColor(Color.black);
g.drawString("Final -40%", x1+3*x1+3*width, y1*2-y1);
}
}
-----------------------------------------------------------------------------------------------------------------
Array index out of bound exception

Problem Description
Write a program that first creates an integer array a[50], and set a[i] = i+3, i=0 to 49. The program next prompts the user to enter an index k, then calls a method readValue(int k) that would return the value of a[k]. The main program displays the value a[k]. If the index is out of bounds, the method readValue(int k) would throw an IndexOutOfBoundsException. The main program should catch the exception and display the message "out of bounds".

Input Format
an integer k

Output Format
value of a[k], or "out of bounds"
-----------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
public class outOfBound {
public static void main(String args[]){
Scanner input =new Scanner(System.in);
int check []=new int[50];
for(int i=0;i<50;i++){
check[i]=i+3;
}
int num =input.nextInt();
if(num<50){
System.out.println(check[num]);
}
else
System.out.println("out of bounds");
}
}
-----------------------------------------------------------------------------------------------------------------
Invalid triangle exception

Problem Description
In a triangle, the sum of any two sides must be greater than the third side. Define a Triangle class that contains three data fields (type double): side1, side2, and side3 that represent the three sides. Create a custom InvalidTriangleException class that extends Exception. The constructor of the Triangle class should throw an InvalidTriangleException if the three sides violates the rule.
Write a program that prompts the user to enter three floating-point numbers that represents the three sides of a triangle, then tries to create the triangle object. If the triangle is valid, display "valid"; If the triangle violates the rule, the main program should catch the exception and display "invalid".

Input Format
three floating-point numbers representing the three sides of a triangle

Output Format
valid or invalid
-----------------------------------------------------------------------------------------------------------------
import java.util.Scanner;  
public class Main {  
    public static void main(String args[]){  
        Scanner input=new Scanner(System.in);  
        double side1=input.nextDouble();  
        double side2=input.nextDouble();  
        double side3=input.nextDouble();  
        try{  
            Triangle triangle=new Triangle(side1,side2,side3);  
        }  
        catch(Exception ex){  
            System.out.println("invalid");  
        }  
    }  
}  
class Triangle{  
    private double side1;  
    private double side2;  
    private double side3;  
    public Triangle(double side1, double side2, double side3) throws Exception {  
        this.side1=side1;  
        this.side2=side2;  
        this.side3=side3;  
        if((side1+side2)>side3&&(side1+side3)>side2&&(side2+side3)>side1)  
            System.out.println("valid");  
        else  
            throw new Exception();  
    }  
}  
-----------------------------------------------------------------------------------------------------------------
The ComparableCircle class

Problem Description

Define a class named ComparableCircle that extends the SimpleCircle class (see Listing 8.2 of the textbook) and implements Comparable. Implement the compareTo method to compare the circles on the basis of area. Write a test program that reads in radiuses of two circles, creates two ComparableCircle objects, and uses the comparedTo() method to find out whether circle 1 or circle 2 is larger.

Input Format

Two floating point numbers representing the radiuses of two circles.

Output Format

Print out which circle is larger.

----------------------------------------------------------------------------------------------------------------
import java.util.*;  
public class Main {  
    public static void main(String args[]){  
        Scanner input =new Scanner(System.in);  
        double circleR1=input.nextDouble();  
        double circleR2=input.nextDouble();  
        ComparableCircle circle1=new ComparableCircle(circleR1);  
        ComparableCircle circle2=new ComparableCircle(circleR2);  
        if(circle1.compareTo(circle2)==1)  
            System.out.println("Circle 1 is larger.");  
        if(circle1.compareTo(circle2)==-1)  
            System.out.println("Circle 2 is larger.");  
    }  
}  
class SimpleCircle{  
    public double radius;  
    SimpleCircle(){}  
    SimpleCircle(double radius){  
        this.radius=radius;  
    }  
    double getArea(){  
        return radius*radius*Math.PI;  
    }  
    double getPerimeter(){  
        return 2*radius*Math.PI;  
    }  
    double setRadius(double radius){  
        this.radius=radius;  
        return radius;  
    }  
}  
class ComparableCircle extends SimpleCircle implements  Comparable<ComparableCircle>{  
    ;  
    ComparableCircle(){  
    }  
    ComparableCircle(double circleR1){  
        super(circleR1);  
    }  
    @Override  
    public int compareTo(ComparableCircle o) {  
        if(getArea()>o.getArea())  
            return 1;  
        if(getArea()<o.getArea())  
            return -1;  
        else  
            return 0;  
    }  
}  
----------------------------------------------------------------------------------------------------------------
Handle event of mouse click

Problem Description
Write a program that displays a frame with two buttons as shown below. Assume the initial value of sum is 0. When the "+1" or "+2" button is clicked, you should add 1 or 2 to the sum, respectively. Also after each click, you should display the current value of sum by printing "The current sum is n." where n represents the current sum. For example, if "+1" is clicked, print "The current sum is 1". If "+2" is clicked next, print "The current sum is 3". If "+2" is clicked again, print "The current sum is 5", and so on. (Note: To do this assignment, you can start by modifying the code of Listing 16.1 of the textbook. Add a static variable such as static int sum in the HandleEvent class to store the value of sum.)
----------------------------------------------------------------------------------------------------------------

import java.awt.event.*;
import javax.swing.*;
public class EventOfMouseClick extends JFrame{
public static int sum=0;
EventOfMouseClick(){
JButton addOne=new JButton("+1");
JButton addTwo=new JButton("+2");
JPanel justPanel=new JPanel();
add(justPanel);
justPanel.add(addOne);
justPanel.add(addTwo);
addOneClass listen1=new addOneClass();
addTwoClass listen2=new addTwoClass();
addOne.addActionListener(listen1);
addTwo.addActionListener(listen2);
}
public static void main(String args[]){
JFrame Jf=new EventOfMouseClick();
Jf.setTitle("Handle event of mouse click");
Jf.setSize(300,250);
Jf.setLocationRelativeTo(null);
Jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Jf.setVisible(true);
}
}
class addOneClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
EventOfMouseClick.sum+=1;
System.out.println("The current sum is :"+ EventOfMouseClick.sum);
}
}
class addTwoClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
EventOfMouseClick.sum+=2;
System.out.println("The current sum is :"+ EventOfMouseClick.sum);
}
}

引用網址:https://home.gamer.com.tw/TrackBack.php?sn=1987431
All rights reserved. 版權所有,保留一切權利

相關創作

留言共 0 篇留言

我要留言提醒:您尚未登入,請先登入再留言

3喜歡★NTUCSIE 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:大家新年快樂呀呀呀呀呀呀... 後一篇:程式練習--Animat...

追蹤私訊切換新版閱覽

作品資料夾

ilove487奇幻小說連載中
《克蘇魯的黎明》0671.第一王國伐盧希亞看更多我要大聲說昨天13:07


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】