java语言程序设计基础篇第十二章编程练习题

1

package yongheng;
import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String str = cin.nextLine();
        str = str.replace(" ", "");
        int num1 = 1;
        int num2 = 1;
        try{
            num1 = Integer.parseInt(str.substring(0,1));
            num2 = Integer.parseInt(str.substring(2, 3));
        }
        catch(NumberFormatException e){
            System.out.println(e.toString());
        }
        char flag = str.charAt(1);
        int result = 0;
        switch(flag){
        case '+' : result = num1 + num2; break;
        case '-' : result = num1 - num2; break;
        case '*' : result = num1 * num2; break;
        case '/' : result = num1 / num2; break;
        }
        System.out.println(result);
    }

}


2

package yongheng;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int a = 0;
        int b = 0;
        boolean continueCin = true;
        do{
            try{
                System.out.println("Please input two number:");
                a = cin.nextInt();
                b = cin.nextInt();
                System.out.println("a + b = " + (a+b));
                continueCin = false;
            }
            catch(InputMismatchException ex){
                System.out.println("Try again.");
                //这个很重要,如果去掉就死循环了
                cin.nextLine();
            }
        }while(continueCin);
    }

}


3

package yongheng;
import java.util.*;

public class Calculator {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int[] integer = new int[100];
        for(int i = 0; i < 100; ++i)
            integer[i] = (int)(Math.random()*100);
        try{
            int index = cin.nextInt();
            System.out.println(integer[index]);
        }
        catch(ArrayIndexOutOfBoundsException ex){
            System.out.println("Out of Bounds");
        }
    }

}

4


public class Loan {
    private double annualInterestRate;
    private int numberOfYears;
    private double loanAmount;
    private java.util.Date loanDate;

    public Loan(){
        this(2.5,1,1000);
    }

    public Loan(double annualInterestRate, int numberOfYears, double loanAmount){
        if(annualInterestRate <= 0 || numberOfYears <= 0 || loanAmount <= 0)
            throw new IllegalArgumentException("you are wrong");
        this.annualInterestRate = annualInterestRate;
        this.numberOfYears = numberOfYears;
        this.loanAmount = loanAmount;
        loanDate = new java.util.Date();
    }

    public double getAnnualInterestRate(){
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate){
        if(annualInterestRate <= 0)
            throw new IllegalArgumentException("you are wrong");
        this.annualInterestRate = annualInterestRate;
    }

    public double getNumberOfYears(){
        return numberOfYears;
    }

    public void setNumberOfYears(int numberOfYears){
        if(numberOfYears <= 0)
            throw new IllegalArgumentException("you are wrong");
        this.numberOfYears = numberOfYears;
    }

    public double getLoanAmount(){
        return loanAmount;
    }

    public void setLoanAmount(double loanAmount){
        if(loanAmount <= 0)
            throw new IllegalArgumentException("you are wrong");
        this.loanAmount = loanAmount;
    }
    /*
     * 剩下的功能不抄了
     */
}


5

public class IllegalTriangleException extends Exception{
    private String message;
    public IllegalTriangleException(){
        message = "this is illegal";
    }

    public IllegalTriangleException(String argu){
        message = argu;
    }

    @Override
    public String toString(){
        return message;
    }
}

class Triangle extends SimpleGeometricObject{
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public Triangle(){
        super();
        side1 = side2 = side3 = 1.0;
    }

    //在这里修改的
    public Triangle(double side1, double side2, double side3)
            throws IllegalTriangleException{
        super();
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
        if(side1 + side2 <= side3 || side2 + side3 <= side1 || side1 + side3 <= side2)
            throw new IllegalTriangleException("ha ha,you are wrong");
    }

    public double getSide1(){
        return side1;
    }

    public double getSide2(){
        return side2;
    }

    public double getSide3(){
        return side3;
    }

    public double getArea(){
        double p = (side1 + side2+ side3) / 2;
        return Math.sqrt(p * (p-side1) * (p-side2) * (p-side3));
    }

    public double getPerimeter(){
        return side1 + side2 + side3;
    }

    @Override
    public String toString(){
        return "created on " + super.getDateCreated() + "\ncolor: " + super.getColor() + "\nfilled: " + super.isFilled()
                + "\nArea: " + this.getArea() + "\nPerimeter: " + this.getPerimeter();
    }
}
//测试
public class Main{

    public static void main(String[] args){
        try{
            Triangle tri = new Triangle(1,2,1);
        }
        catch(IllegalTriangleException ex){
            System.out.println(ex);
        }
    }
}

6 7 8 9 10
11

package yongheng;

import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class Main {

    public static void main(String args[]){
        ArrayList sstr = new ArrayList<>();
        File file = new File("./ff.txt");
        try(Scanner cin = new Scanner(file)){
            while(cin.hasNext()){
                //如果要替换的这个字符串刚好在换行的地方,这样就不行了
                sstr.add(cin.nextLine().replaceAll("you", "HK"));
            }
        }
        catch(FileNotFoundException ex){
            System.out.println(ex.toString());
        }

        try(PrintWriter output = new PrintWriter(file)){
            for(String str : sstr)
                output.print(str);
            System.out.println("success");
        }
        catch(FileNotFoundException ex){
            System.out.println(ex.toString());
        }
    }
}

12

package yongheng;

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class Main{

    public static void main(String[] args){
        File file = new File("Test.java");
        try(Scanner cin = new Scanner(file)){
            ArrayList ls = new ArrayList<>();
            while(cin.hasNext()){
                ls.add(new StringBuilder(cin.nextLine()));
            }
            int len = ls.size();
            for(int i = 1; i < len; ++i){
                int index = -1;
                if((index = ls.get(i).indexOf("{"))!= -1){
                    ls.get(i).replace(index,index+1," ");
                    ls.get(i-1).insert(ls.get(i-1).length(), "{");
                }
            }
            try(PrintWriter out = new PrintWriter(file)){
                for(StringBuilder str : ls){
                    out.println(str);
                }
            }
            catch(FileNotFoundException ex){
                System.out.println(ex.toString());
            }
        }
        catch(FileNotFoundException ex){
            System.out.println(ex.toString());
        }
    }
}

13

package yongheng;

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class Main{

    public static void main(String[] args){
        File file = new File("./text.txt");
        try(Scanner cin = new Scanner(file)){
            ArrayList ls = new ArrayList<>();
            int sumWord = 0;
            int charNum = 0;
            while(cin.hasNext()){
                String str = cin.nextLine();
                String[] snum = str.split("[\\s,:;?.]");
                sumWord += snum.length;
                charNum += str.length();
                ls.add(str);
            }
            int row = ls.size();
            System.out.println("word num: " + sumWord + "\nchar num: " + charNum + "\nrow: " + row);
        }
        catch(FileNotFoundException ex){
            System.out.println(ex.toString());
        }
    }
}

......
23

package yongheng;

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.net.URL;
import java.net.MalformedURLException;


public class Main{

    public static void main(String[] args){
        try{
            URL url = new URL("http://cs.armstrong.edu/liang/data/Scores.txt");
            Scanner cin = new Scanner(url.openStream());
            int cnt = 0;
            double temp = 0;
            double sum = 0;
            while(cin.hasNext()){
                ++cnt;
                sum += cin.nextDouble();
            }
            System.out.println("sum: " + sum + "\naverage:" + sum/cnt);
        }
        catch(MalformedURLException ex){
            System.out.println(ex.toString());
        }
        catch(IOException ex){
            System.out.println(ex.toString());
        }

    }
}

...
26

package yongheng;

import java.util.Scanner;
import java.io.File;


public class Main{

    public static void main(String[] args){
        Scanner cin = new Scanner(System.in);
        System.out.println("please input the name of the directory:");
        String dir = cin.next();
        File file = new File(dir);
        if(file.exists()){
            System.out.println("directory already exists");
        }
        else{
            file.mkdirs();
            System.out.println("directort created successfully");
        }
    }
}

......
33

package yongheng;

import java.util.Scanner;
import java.util.ArrayList;
import java.net.URL;


public class Main{

    public static void main(String[] args){
        String url = "http://www.cnblogs.com/guoyongheng/p/5782972.html";
        crawler(url);
    }

    public static void crawler(String startingurl){
        ArrayList listOfPendingURLs = new ArrayList<>();
        ArrayList listOfTraversedURLs = new ArrayList<>();

        listOfPendingURLs.add(startingurl);
        while(!listOfPendingURLs.isEmpty()/* && listOfTraversedURLs.size() <= 100*/){
            String urlString = listOfPendingURLs.remove(0);

            if(!listOfTraversedURLs.contains(urlString)){
                listOfTraversedURLs.add(urlString);

                for(String s : getSubURLs(urlString)){
                    if(!listOfTraversedURLs.contains(s))
                        listOfPendingURLs.add(s);
                }
            }
        }
    }

    public static ArrayList getSubURLs(String urlString){
        ArrayList list = new ArrayList<>();

        try{
            URL url = new URL(urlString);
            Scanner cin = new Scanner(url.openStream());
            int current = 0;
            while(cin.hasNext()){
                String line = cin.nextLine();

                if(line.indexOf("getf") >= 0){
                    System.out.println(urlString);
                    System.exit(0);
                }

                current = line.indexOf("http:",current);
                while(current >= 0){
                    int endIndex = line.indexOf("\"",current);
                    if(endIndex >= 0){
                        list.add(line.substring(current, endIndex));
                        current = line.indexOf("http:",endIndex);
                    }
                    else
                        current = -1;
                }
            }
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        return list;
    }
}

你可能感兴趣的:(Java学习)