上題目
python 版本
import re
class Rateforreturn:
rstr = ""
def GetInput(this):
this.rstr = input("What is the rate of return \n")
def isnumerical(this):
return this.rstr != "" and re.match("^\d+\.?\d*#34;, this.rstr) != None
def JudgeInput(this):
if this.isnumerical() == True:
if float(this.rstr) == 0:
print("Sorry. That's a not a valid input")
return 0
else:
years = 72 / float(this.rstr)
print("It will take {0} years to double your initial investment".format(years))
return 1
else:
print("Sorry, should be numerical numbers")
return 0
lesson29 = Rateforreturn()
lesson29.GetInput()
while lesson29.JudgeInput() == 0:
lesson29.GetInput()
運作效果圖
java 版本
import java.util.Scanner;
public class RateforReturn{
private String rstr = "";
private Scanner sc = new Scanner(System.in );
void GetInput(){
System.out.println("What is the rate of return ");
this.rstr = sc.nextLine();
}
static boolean isnumerical(String str1){
return str1.equals("") == false & & str1.matches("^\\d+\\.?\\d*#34;);
}
boolean JudgeInput2()
{
if (isnumerical(this.rstr) == true)
{
if (Float.parseFloat(this.rstr) == 0)
{
System.out.println("Sorry, That's not a valid input ");
return false;
}
else {
float years = 72 / Float.parseFloat(this.rstr);
System.out.println("It will take " + years + " years to double your initial investment");
return true;
}
}
else {
System.out.println("Sorry , should be numerical numbers");
return false;
}
}
public static void main(String[] args){
RateforReturn lesson29 = new RateforReturn();
lesson29.GetInput();
while (lesson29.JudgeInput2() == false)
{
lesson29.GetInput();
}
}
}
運作效果圖