面向对象程序设计JAVA学习记录(8)

1.Use Collections to Represent Multiplicity

Objective

In this exercise you will replace the arrays code that you used to implement multiplicity in the relationships between bank and customer, and customer and their accounts.

Directions

This exercise is based on the exercise Create Your Own Exception.So copy all the previous Banking project files of that project, then make necessary modifications.

Modify the Bank Class

Modify the Bank class to use an ArrayList to implement the multiplicty on the customers association. Don't forget to import the necessary java.util classes.

  1. Modify the declaration for the customers attribute to be of type List and drop the numberOfCustomers attribute.

  2. Modify the Bank constructor to initialize the customers attribute to be a new ArrayList object.

  3. Modify the addCustomer method to use the add method.

  4. Modify the getCustomer method to use the get method.

  5. Modify the getNumOfCustomers method to use the size method.

Modify the Customer Class

Modify the Customer class to use an ArrayList to implement the multiplicty on the accounts association. Perform the same modifications as above.

Compile and Run the Main Program

You need to borrow the preset code of the Create Your Own Exception Project, make necessary modifications if needed. Compile and run the Main program and you should see the same output as before.

Optional: Modify the CustomerReport Class

Modify the CustomerReport class to use an ArrayList to implement the multiplicty on the accounts association. Perform the same modifications as above.

  1. In the Bank class, add a method called getCustomers that returns an Iterator on the customers list.

  2. In the Customer class, add a method called getAccounts that returns an Iterator on the accounts list.

  3. Modify the CustomerReport class to use a pair of nested while loops that iterate over the customer's iterator and the account's iterator; instead of using the nested forloops. You can also try to use the enhanced for loops.
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        Bank bank = Bank.getBank();
        Customer customer;
        int curCustomer = 0;
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        s.nextLine();
        while (t-- > 0) {
            String f = s.next();
            String l = s.next();
            s.nextLine();
            bank.addCustomer(f, l);
            customer = bank.getCustomer(curCustomer++);
            int numAccount = s.nextInt();
            s.nextLine();
            while (numAccount-- > 0) {
                String[] type = s.nextLine().split(" ");
                double balance;
                double interesOrProtect;
                if (type[0].trim().toUpperCase().equals("C")) {
                    balance = Double.parseDouble(type[1]);
                    if (type.length == 3) {
                        interesOrProtect = Double.parseDouble(type[2]);
                        customer.addAccount(new CheckingAccount(balance,
                                interesOrProtect));
                    } else {
                        customer.addAccount(new CheckingAccount(balance));
                    }
                } else if (type[0].trim().toUpperCase().equals("S")) {
                    balance = Double.parseDouble(type[1]);
                    interesOrProtect = Double.parseDouble(type[2]);
                    customer.addAccount(new SavingsAccount(balance,
                            interesOrProtect));
                }
            }
        }
        int nOPs = s.nextInt();
        s.nextLine();
        while (nOPs-- > 0) {
            String[] sOP = s.nextLine().split(" ");
            char op = sOP[0].charAt(0);
            int customerIndex = Integer.parseInt(sOP[1]);
            int accountIndex = Integer.parseInt(sOP[2]);
            double amount = Double.parseDouble(sOP[3]);
            switch (op) {
                case 'w':
                case 'W':
                    customer = bank.getCustomer(customerIndex);
                    try{
                        customer.getAccount(accountIndex).withdraw(amount);
                    }
                    catch (OverdraftException ode){
                        System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
                    }
                    break;
                case 'd':
                case 'D':
                    customer = bank.getCustomer(customerIndex);
                    customer.getAccount(accountIndex).deposit(amount);
                    break;
            }
        }
        CustomerReport cr = new CustomerReport();
        cr.generateReport();
    }
}
class Account {
    protected double balance;
    public Account(double init_balance) {
        this.balance = init_balance;
    }
    public String getBalance() {
        return String.format("%.1f",balance);
    }
    public boolean deposit(double amt) {
        balance = balance + amt;
        return true;
    }
    public void withdraw(double amt) throws OverdraftException {
        if (balance >= amt) {
            balance = balance - amt;
        } else {
            throw new OverdraftException("Insufficient funds", amt - balance);
        }
    }
}
class Bank{
    private static Bank bankInstance;
    private Bank(){};
    public static Bank getBank(){
        if(bankInstance==null){
            bankInstance = new Bank();
        }
      return bankInstance;
    }
    ArrayList<Customer> List=new ArrayList<>();
    public void addCustomer(String s, String l) {
        Customer customer = new Customer(s, l);
        this.List.add(customer);
    }
    public int getNumOfCustomers() {
        return List.size();
    }
    public Customer getCustomer(int index) {
        return List.get(index);
    }
}
class CheckingAccount extends Account {
    private Double protectedBy;
    public CheckingAccount(double balance) {
        super(balance);
        this.protectedBy = 0.0;
    }
    public CheckingAccount(double balance, Double protect) {
        super(balance);
        this.protectedBy = protect;
    }
    public void withdraw(double amt) throws OverdraftException {
        if (balance >= amt) {
            balance -= amt;
        } else {
            if (protectedBy > 0) {
                if (balance + protectedBy >= amt) {
                    protectedBy -= (amt - balance);
                    balance = 0.0;
                } else {
                    throw new OverdraftException("Insufficient funds", amt - balance - protectedBy);
                }
            } else {
                throw new OverdraftException("No overdraft protection", amt - balance);
            }
        }
    }
}
class Customer {
    private int acct;
    ArrayList<Account> list=new ArrayList<>();
    private String firstName;
    private String lastName;
    public Customer(String f, String l) {
        this.firstName = f;
        this.lastName = l;
        acct = 0;
    }
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void addAccount(Account n) {
        list.add(n);
        acct++;
    }
    public Account getAccount(int x) {
        return list.get(x);
    }
    public int getNumOfAccounts() {
        return acct;
    }
    public String toString() {
        return "["+firstName + " " +lastName +"]";
    }
}
 class OverdraftException extends Exception{
    private double deficit;
    public double getDeficit(){
        return this.deficit;
    }
    public OverdraftException(String message,double deficit){
        super(message);
        this.deficit=deficit;
    }
}
class SavingsAccount extends Account {
    private double interestRate;
    public SavingsAccount(double balance, double interest_rate) {
        super(balance);
        this.interestRate = interest_rate;
    }
}
 class CustomerReport {
    public void generateReport() {
        NumberFormat currency_format = NumberFormat.getCurrencyInstance();
        Bank bank =Bank.getBank();
                Customer customer;
        System.out.println("CUSTOMERS REPORT");
        System.out.println("================");
        for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
            customer = bank.getCustomer(cust_idx);
            System.out.println();
            System.out.println("Customer: "+"["
                    + customer.getFirstName() +" "
                    + customer.getLastName()+"]");
            for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
                Account account = customer.getAccount(acct_idx);
                String account_type = "";
                if ( account instanceof SavingsAccount ) {
                    account_type = "Savings Account";
                } else if ( account instanceof CheckingAccount ) {
                    account_type = "Checking Account";
                } else {
                    account_type = "Unknown Account Type";
                }
                System.out.println("    " + account_type + ": current balance is "
                        +"$"+ account.getBalance());
            }
        }
    }
}

 2.Sort Customers

Objective

This exercise is based on the previous exercise of Use Collections to Represent Multiplicity. you will sort the list of bank customers by their names. This will require you to have the Customer class implement the Comparable interface.

Directions

Start by copying all the previous project files into your working directory.

  1. Add the sortCustomers method to the Bank class.

  2. Modify the Customer class to implement the Comparable interface. You will need to specify the compareTo method. Make this method compare the two customers in a lexigraphical order with the last name taking precedence over the first name. For example, "Joe Smith" should come before "Samuel Smith".

  3. Modify the CustomerReport class to call the sortCustomers method before generating the report.

  4. Compile and run the Main program. You should see the expected result accordingly
    import java.text.NumberFormat;
    import java.util.*;
    import java.util.List;
    public class Main {
        public static void main(String[] args) {
            Bank bank = Bank.getBank();
            Customer customer;
            int curCustomer = 0;
            Scanner s = new Scanner(System.in);
            int t = s.nextInt();
            s.nextLine();
            while (t-- > 0) {
                String f = s.next();
                String l = s.next();
                s.nextLine();
                bank.addCustomer(f, l);
                customer = bank.getCustomer(curCustomer++);
                int numAccount = s.nextInt();
                s.nextLine();
                while (numAccount-- > 0) {
                    String[] type = s.nextLine().split(" ");
                    double balance;
                    double interesOrProtect;
                    if (type[0].trim().toUpperCase().equals("C")) {
                        balance = Double.parseDouble(type[1]);
                        if (type.length == 3) {
                            interesOrProtect = Double.parseDouble(type[2]);
                            customer.addAccount(new CheckingAccount(balance,
                                    interesOrProtect));
                        } else {
                            customer.addAccount(new CheckingAccount(balance));
                        }
                    } else if (type[0].trim().toUpperCase().equals("S")) {
                        balance = Double.parseDouble(type[1]);
                        interesOrProtect = Double.parseDouble(type[2]);
                        customer.addAccount(new SavingsAccount(balance,
                                interesOrProtect));
                    }
                }
            }
            int nOPs = s.nextInt();
            s.nextLine();
            while (nOPs-- > 0) {
                String[] sOP = s.nextLine().split(" ");
                char op = sOP[0].charAt(0);
                int customerIndex = Integer.parseInt(sOP[1]);
                int accountIndex = Integer.parseInt(sOP[2]);
                double amount = Double.parseDouble(sOP[3]);
                switch (op) {
                    case 'w':
                    case 'W':
                        customer = bank.getCustomer(customerIndex);
                        try{
                            customer.getAccount(accountIndex).withdraw(amount);
                        }
                        catch (OverdraftException ode){
                            System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
                        }
                        break;
                    case 'd':
                    case 'D':
                        customer = bank.getCustomer(customerIndex);
                        customer.getAccount(accountIndex).deposit(amount);
                        break;
                }
            }
            CustomerReport cr = new CustomerReport();
            cr.generateReport();
        }
    }
    class Account {
        protected double balance;
        public Account(double init_balance) {
            this.balance = init_balance;
        }
        public String getBalance() {
            return String.format("%.1f",balance);
        }
        public boolean deposit(double amt) {
            balance = balance + amt;
            return true;
        }
        public void withdraw(double amt) throws OverdraftException {
            if (balance >= amt) {
                balance = balance - amt;
            } else {
                throw new OverdraftException("Insufficient funds", amt - balance);
            }
        }
    }
     class Bank{
        private static Bank bankInstance;
        private Bank(){};
        public List<Customer> sortCustomer(){
            Collections.sort(this.list);
            return this.list;
        }
        public static Bank getBank(){
            if(bankInstance==null){
                bankInstance = new Bank();
            }
          return bankInstance;
        }
        ArrayList<Customer> list=new ArrayList<>();
        public void addCustomer(String s, String l) {
            Customer customer = new Customer(s, l);
            this.list.add(customer);
        }
        public int getNumOfCustomers() {
            return list.size();
        }
        public Customer getCustomer(int index) {
            return list.get(index);
        }
    }
    class CheckingAccount extends Account {
        private Double protectedBy;
        public CheckingAccount(double balance) {
            super(balance);
            this.protectedBy = 0.0;
        }
        public CheckingAccount(double balance, Double protect) {
            super(balance);
            this.protectedBy = protect;
        }
        public void withdraw(double amt) throws OverdraftException {
            if (balance >= amt) {
                balance -= amt;
            } else {
                if (protectedBy > 0) {
                    if (balance + protectedBy >= amt) {
                        protectedBy -= (amt - balance);
                        balance = 0.0;
                    } else {
                        throw new OverdraftException("Insufficient funds", amt - balance - protectedBy);
                    }
                } else {
                    throw new OverdraftException("No overdraft protection", amt - balance);
                }
            }
        }
    }
    class Customer implements Comparable<Customer> {
        private int acct;
        ArrayList<Account> list=new ArrayList<>();
        private String firstName;
        private String lastName;
        public Customer(String f, String l) {
            this.firstName = f;
            this.lastName = l;
            acct = 0;
        }
        @Override
        public int compareTo(Customer o) {
            if(this.lastName.equals(o.getLastName())){
                return this.firstName.compareTo(o.getFirstName());
            }
            else{
                return this.lastName.compareTo(o.getLastName());
            }
        }
        public String getFirstName() {
            return firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void addAccount(Account n) {
            list.add(n);
            acct++;
        }
        public Account getAccount(int x) {
            return list.get(x);
        }
        public int getNumOfAccounts() {
            return acct;
        }
        public String toString() {
            return "["+firstName + " " +lastName +"]";
        }
    }
    class OverdraftException extends Exception{
        private double deficit;
        public double getDeficit(){
            return this.deficit;
        }
        public OverdraftException(String message,double deficit){
            super(message);
            this.deficit=deficit;
        }
    }
    class SavingsAccount extends Account {
        private double interestRate;
        public SavingsAccount(double balance, double interest_rate) {
            super(balance);
            this.interestRate = interest_rate;
        }
    }
     class CustomerReport {
        public void generateReport() {
            NumberFormat currency_format = NumberFormat.getCurrencyInstance();
            Bank bank =Bank.getBank();
                    Customer customer;
            System.out.println("CUSTOMERS REPORT");
            System.out.println("================");
            bank.sortCustomer();
            for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
                customer = bank.getCustomer(cust_idx);
                System.out.println();
                System.out.println("Customer: "+"["
                        + customer.getFirstName() +" "
                        + customer.getLastName()+"]");
                for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
                    Account account = customer.getAccount(acct_idx);
                    String account_type = "";
                    if ( account instanceof SavingsAccount ) {
                        account_type = "Savings Account";
                    } else if ( account instanceof CheckingAccount ) {
                        account_type = "Checking Account";
                    } else {
                        account_type = "Unknown Account Type";
                    }
                    System.out.println("    " + account_type + ": current balance is "
                            + "$"+account.getBalance());
                }
            }
        }
    }
    

    3.Sort Customers(alternate)

Objective

In this exercise you will sort the list of bank customers as you have done in the previous exercise. But this time you are required to sort the customers in various way: by their names, balance of their checking accounts or saving accounts. You need to create comparing classes implementing the Comparator interface and apply the comparation using the class instance.

Directions

Copy the previous Banking project files. Of course, the Customer class does not need to implment the Comparable interface this time.

  1. Add the sortCustomers method to the Bank class. This time, you need to pass a Comparator object as a parameter to the method so that it will sort the customers according to the comparator(). Hint, you may need to use the Collections.sort method to sort the list. Refer to JDK API documents please. Do not forget to pass the Type parameter when using the generics.

  2. Create your own NameCompSavingComp and CheckingComp classes that implement the Comparator interface. You will need to specify the compare method. Make this method compare the two customers in a lexigraphical order with the last name taking precedence over the first name for the NameComp class. For example, "Joe Smith" should come before "Samuel Smith".

    Do the similar thing with the SavingComp and CheckingComp classes as NameComp class.

  3. Modify the CustomerReport class to call the sortCustomers method before generating the report.

  4. Write your own Main program, sort the customers by Name, Savings and Ckecking, and generate report accordingly.
    import java.text.NumberFormat;
    import java.util.*;
    public class Main {
    	public static void main(String[] args) {
    		Bank bank = Bank.getBank();
    		Customer customer;
    		int curCustomer = 0;
    		Scanner s = new Scanner(System.in);
    		int t = s.nextInt();
    		s.nextLine();
    		while (t-- > 0) {
    			String f = s.next();
    			String l = s.next();
    			s.nextLine();
    			bank.addCustomer(f, l);
    			customer = bank.getCustomer(curCustomer++);
    			int numAccount = s.nextInt();
    			s.nextLine();
    			while (numAccount-- > 0) {
    				String[] type = s.nextLine().split(" ");
    				double balance;
    				double interesOrProtect;
    				if (type[0].trim().toUpperCase().equals("C")) {
    					balance = Double.parseDouble(type[1]);
    					if (type.length == 3) {
    						interesOrProtect = Double.parseDouble(type[2]);
    						customer.addAccount(new CheckingAccount(balance,
    								interesOrProtect));
    					} else {
    						customer.addAccount(new CheckingAccount(balance));
    					}
    				} else if (type[0].trim().toUpperCase().equals("S")) {
    					balance = Double.parseDouble(type[1]);
    					interesOrProtect = Double.parseDouble(type[2]);
    					customer.addAccount(new SavingsAccount(balance,
    							interesOrProtect));
    				}
    			}
    		}
    		int nOPs = s.nextInt();
    		s.nextLine();
    		while (nOPs-- > 0) {
    			String[] sOP = s.nextLine().split(" ");
    			char op = sOP[0].charAt(0);
    			int customerIndex = Integer.parseInt(sOP[1]);
    			int accountIndex = Integer.parseInt(sOP[2]);
    			double amount = Double.parseDouble(sOP[3]);
    			switch (op) {
    			case 'w':
    			case 'W':
    				customer = bank.getCustomer(customerIndex);
    				try{
    					customer.getAccount(accountIndex).withdraw(amount);
    				}
    				catch (OverdraftException ode){
    					System.out.println( customer + " withdraw " + amount + ", " + ode.getMessage() + ": " + ode.getDeficit());
    				}
    				break;
    			case 'd':
    			case 'D':
    				customer = bank.getCustomer(customerIndex);
    				customer.getAccount(accountIndex).deposit(amount);
    				break;
    			}
    		}
    		CustomerReport cr = new CustomerReport();
    		cr.generateReport();
    	}
    }
    class OverdraftException extends Exception{
    	private Double deficit;
    	public Double getDeficit(){
    		return deficit;
    	}
    	
    	public OverdraftException(String message , Double defici){
    		super(message);
    		deficit=defici;
    	}
    }
    class Account{
    	protected  double balance;
    	public  Double getBalance(){
    		return balance;
    	}
    	public boolean deposit( Double amt){
    		balance = balance + amt;
    		return true;
    	}
    	public void withdraw( Double amt ) throws  OverdraftException{
    		if (balance - amt >=0) balance =balance - amt;
    		else {
    			throw new OverdraftException("Insufficient funds", amt - balance) ;
    		}	
    	}
    	public  Account(Double init_balance ){
    		balance = init_balance;
    	}
    }
    class SavingsAccount extends Account{
    	private double interestRate ;
    	public SavingsAccount ( Double balance , Double interest_rate){
    		super(balance);
    		interest_rate = interestRate;
    	}
    }
    class CheckingAccount extends Account{
    	private Double overdraftProtection;
    	public CheckingAccount( Double balance ){
    		super(balance);
    	}
    	public CheckingAccount(Double balance, Double protect){
    		super(balance);
    		this.overdraftProtection =protect;
    	}
    	public double getOverdraftProtection() {
            		return overdraftProtection;
        	}
    	public void setOverdraftProtection(double overdraftProtection) {
    		this.overdraftProtection = overdraftProtection;
    	}
    	public void withdraw(Double amt)throws OverdraftException{
    		if (amt <= balance){
    			balance -= amt;
    		}else{  if (overdraftProtection ==null) {
    			throw new OverdraftException("No overdraft protection", amt - balance) ;
    		           }else if (balance+overdraftProtection <= amt){
    				if(amt - balance - overdraftProtection!=0)
    				{throw new OverdraftException("Insufficient funds", amt - balance - overdraftProtection) ;}
    				else {balance = 0.0; }
                		           }else {
    				overdraftProtection -= (amt -balance) ;
    				balance = 0.0;
    		           }
    		         
    		}
    	}	
    }
    class Customer {
    	private  String firstName;
    	private  String lastName;
    	private  SavingsAccount  savingsAccount;
    	private CheckingAccount checkingAccount;
    	private List<Account> accounts;
    	public Customer(String f, String l ){
    		firstName =f;
    		lastName  = l;
    		accounts = new ArrayList<Account>();
    	}
    	public String toString(){
    		return "["+firstName+" "+lastName+"]" ;
    	}
    	
    	public String getFirstName() {
    		return firstName;
    	}
    	public String getLastName() {
    		return lastName;
    	}
    	public  void addAccount( Account acct){
    		accounts.add(acct);
    		
    	}
    	public int getNumOfAccounts(){
    		return accounts.size();
    	}
    	public Account getAccount(int index) {
    		return accounts.get(index);
    	}
    	
    }
    class CustomerReport {
    	Bank bank = Bank.getBank() ;
    	Customer customer ;
    	 public void generateReport(){
    		String[] str={"User Name","Savings Account Balance","Checking Account Balance"};
    		for(String a: str ){
    			bank.sortCustomers(a);
    		NumberFormat currency_format = NumberFormat.getCurrencyInstance() ;
    		 System.out.println("CUSTOMERS REPORT according to "+a+":");
    		System.out.println("=============================================");
    		
    		for (int cust_idx = 0 ; cust_idx < bank.getNumOfCustomers() ; cust_idx++){
    			customer = bank.getCustomer(cust_idx) ;
    			 System.out.println();
    			 System.out.println("Customer: [" + customer.getFirstName() + " " + customer.getLastName()+"]");
    			for (int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++){
    				Account account = customer.getAccount(acct_idx) ;
    				String account_type = "" ;
    				if (account instanceof SavingsAccount){
    					account_type = "Savings Account" ;
                   				}
    				if (account instanceof CheckingAccount){
    					account_type = "Checking Account" ;
                    			}
                    			System.out.println("    "+account_type + ": current balance is $" + account.getBalance());
                			}
           		 }
    		}
        	}
    }
    class Bank {
    	private List<Customer> customers;
    	private static Bank bank= new Bank();
    	public static Bank getBank(){
            		return bank ;
        	}
      	public Bank() {
    		customers = new ArrayList<Customer>();
    	}
       	public void addCustomer(String f,String l) {
    		Customer aa = new Customer(f,l);
    		customers.add(aa);
       	}
    	public int getNumOfCustomers() {
    		return customers.size();
    	}
    	public Customer getCustomer(int index) {
    		return customers.get(index);
    	}
    	public void sortCustomers( String message){
    		  if(message.equals("User Name")){
                			Collections.sort(customers,new NameComp());
          		 }
    		else if(message.equals("Savings Account Balance")){
                			Collections.sort(customers,new SavingComp());
            		}
            		else{
               			Collections.sort(customers,new CheckingComp());
            		}
    	}
    }
    class NameComp implements Comparator<Customer>{
    	@Override
    	public int compare(Customer o1,Customer o2){
    		int result = 0;
            		result = o1.getLastName().compareTo(o2.getLastName());
            		if(result == 0){
                			result = o1.getFirstName().compareTo(o2.getFirstName());
           		 }
           		 return result;
    	}
    }
    class SavingComp implements Comparator<Customer>{
    	@Override
    	 public int compare(Customer o1, Customer o2) {
            		double x = -1;
            		double y = -1;
            		for(int i=0; i<o1.getNumOfAccounts();i++){
                			if(o1.getAccount(i) instanceof SavingsAccount){
                    			x = o1.getAccount(i).balance;
               			}
            		}
            		for(int i=0;i<o2.getNumOfAccounts();i++){
               	 		if(o2.getAccount(i) instanceof SavingsAccount){
                    			y = o2.getAccount(i).balance;
                			}
            		}
            		if(x < y) return -1;
           		else if(x > y) return 1;
            		else  return 0;
        	}
    }
    class CheckingComp implements Comparator<Customer>{
    	public int compare(Customer o1, Customer o2) {
            		double x = -1;
            		double y = -1;
            		for(int i=0; i<o1.getNumOfAccounts();i++){
                			if(o1.getAccount(i) instanceof CheckingAccount){
                    			x = o1.getAccount(i).balance;
               			}
            		}
            		for(int i=0;i<o2.getNumOfAccounts();i++){
               	 		if(o2.getAccount(i) instanceof CheckingAccount){
                    			y = o2.getAccount(i).balance;
                			}
            		}
            		if(x < y) return -1;
           		else if(x > y) return 1;
            		else  return 0;
        	}
    }

    4.The Collatz Sequence

成绩: 5 / 折扣: 0.8

The famous Collatz sequence is generated by a method decribed as follows. Given a positive integer N, if it is odd, then replace it with 3*N+1. For even number N, use N/2 instead. You can get a sequence of number by this method. It is conjectured that the algorithm above will terminate at 1 for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)

Input

The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there is an integers N.

Output

For each number N, output the sequence generated in a line, using coma as its separator.

Sample Input

2
22
33

Sample Output

22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1
33,100,50,25,76,38,19,58,29,88,44,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1

	
import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++){
            int a = s.nextInt();
            while(a != 1){
                System.out.print(a + ",");
                if(a % 2 == 0) a = a/2;
                else a = a*3 + 1;
            }
            System.out.println("1");
        }
        s.close();
    }
}

5.Collatz Sequence Again

As you have seen in the previous practice, the Collatz sequence is generated by a method decribed as follows. Given a positive integer N, if it is odd, then replace it with 3*N+1. For even number N, use N/2 instead. You can get a sequence of number by this method. It is conjectured that the algorithm above will terminate at 1 for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)

Input

The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there are two integers i and j.

Output

For each pair of input integers i and j you should output ij, and the maximum sequence length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).

Sample Input

4
1 10
100 200
201 210
900 1000 

Sample Output

1 10 20
100 200 125
201 210 89
900 1000 174 

这个问题每一组数据都硬算的话会超时,所以可做一个数组记录前面几组数据已经算出来的结果,需要就去调用

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        long n = s.nextInt();
        int[] record = new int[1000000];
        record[1] = 1;
        for(int i = 0; i < n; i++){
            long a = s.nextLong();
            long b = s.nextLong();
            int count = 0;
            for(long j = Math.min(a,b); j < Math.max(a,b); j++){
                long m = j;
                int count2 = 0;
                while(m > j || record[(int)m] == 0){
                    if(m % 2 == 0) m = m/2;
                    else m = m*3 + 1;
                    count2++;
                }
                count2 += record[(int)m];
                record[(int)j] = count2;
                if(count2 > count) count = count2;
            }
            System.out.println(a + " " + b + " " + count);
        }
        s.close();
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java面向对象程序设计第三版耿祥义第一章主要介绍了Java的基础知识和面向对象的概念。 1. Java语言的特点 Java语言是一种面向对象的编程语言,具有以下特点: - 简单易学:Java语言的语法类似C++,但是去掉了C++中比较难理解的特性,使得Java更加容易学习和使用。 - 面向对象Java语言是一种纯面向对象的编程语言,所有的程序都是由对象组成的。 - 平台无关性:Java语言可以在不同的操作系统和硬件平台上运行,只需要安装相应的Java虚拟机即可。 - 安全性:Java语言的安全性非常高,可以在不信任的环境下运行程序,避免了一些安全漏洞。 - 高性能:Java语言的运行速度比较快,且可以通过各种优化技术来提高性能。 2. 面向对象的概念 面向对象是一种软件设计的思想,其核心是将问题看作是由对象组成的。对象是指具有一定属性和行为的实体,属性是对象的特征,行为是对象的动作。 在面向对象的设计中,需要考虑以下几个方面: - 类的设计:类是创建对象的模板,需要定义类的属性和方法。 - 对象的创建:创建对象时,需要使用new关键字来调用类的构造方法。 - 对象的访问:访问对象的属性和方法时,需要使用点号操作符来进行访问。 - 继承和多态:继承是指一个类可以继承另一个类的属性和方法,多态是指同一种行为可以用不同的方式实现。 3. Java的基础知识 Java语言的基础知识包括数据类型、运算符、流程控制语句等。 - 数据类型:Java语言的数据类型包括基本数据类型和引用数据类型。基本数据类型包括整型、浮点型、字符型和布尔型,引用数据类型包括类、接口、数组等。 - 运算符:Java语言的运算符包括算术运算符、关系运算符、逻辑运算符、位运算符等。 - 流程控制语句:Java语言的流程控制语句包括if语句、switch语句、for循环、while循环、do-while循环等。 4. Java程序的基本结构 Java程序的基本结构包括类的定义、方法的定义和语句块的定义。 - 类的定义:类是Java程序的基本组成单元,需要使用class关键字来定义类。 - 方法的定义:方法是类中的一个函数,用于实现特定的功能,需要使用方法名、参数列表和返回值类型来定义方法。 - 语句块的定义:语句块是一组语句的集合,需要使用大括号来定义语句块。 总的来说,Java面向对象程序设计第三版耿祥义第一章介绍了Java语言的基础知识和面向对象的概念,为后续的学习打下了基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦叮当

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值