上题目:
python 版本:
from curses.ascii import isdigit
from pandas import interval_range
import re
def Is_numerical(str1):
return re.match('^\d*.?\d*',str1) != None
def Get_input():
principalstr = input("Enter the principal: ")
while principalstr.isdigit() == False:
print("Please input the numerical info: ")
principalstr = input("Enter the principal: ")
intereststr = input("Enter the rate of interest: ")
while Is_numerical(intereststr) == False:
print("Please input the numerical info: ")
intereststr = input("Enter the rate of interest: ")
yearsstr = input("Enter the number of years: ")
while yearsstr.isdigit() == False:
print("Please input the numerical info: ")
yearsstr = input("Enter the number of years: ")
return float(principalstr),float(intereststr),float(yearsstr)
def CalculateSimpleIntrest(principal,interest,years): #如果是Java,里面必须宣称类型,python不用
amount = principal*(1+interest*years/100)
return amount
def Display(years,interest,amount):
print("After {0} years at {1}%, the investment will \n be worth ${2}".format(years,interest,amount))
principal,interest,years = Get_input()
amount = CalculateSimpleIntrest(principal,interest,years)
Display(years,interest,amount)
效果
java版本:
import java.util.Scanner;
public class CalSimInterest{
private float principal;
private float interest;
private float years;
private float amount;
public void Getinput(){
System.out.println("Enter the principal: ");
Scanner sc = new Scanner(System.in );
String principalstr = sc.next();
while (this.isNumeric(principalstr) == false)
{
System.out.println("Enter the principal: ");
principalstr = sc.next();
}
System.out.println("Enter the rate of interest: ");
String intereststr = sc.next();
System.out.println("Enter the number of years: ");
String yearsstr = sc.next();
this.principal = Float.parseFloat(principalstr);
this.interest = Float.parseFloat(intereststr);
this.years = Float.parseFloat(yearsstr);
sc.close();
}
float calculateSimpleInterest()
{
System.out.println(this.principal + " " + this.interest + " " + this.years);
float result = this.principal * (1 + this.interest * this.years / 100);
System.out.println(result);
this.amount = result;
return result;
}
public void display()
{
calculateSimpleInterest();
System.out.println(
"After " + this.years + " years at " + this.interest + "%, the investment will \n be worth #34; + this.amount);
}
private boolean isNumeric(String secondstring) {
return secondstring != null & & secondstring.matches("-?\\d+(\\.\\d+)?");
}
public static void main(String[] args)
{
CalSimInterest lesson12 = new CalSimInterest();
lesson12.Getinput();
lesson12.display();
}
}
效果: