上题目:
python 代码:
from curses.ascii import isdigit
from operator import le
class Driver:
def __init__(self):
self.age = 0
self.principle = {"US":16,"CH":18}
self.country = "US"
def get_age(this):
age = input("What is your age?")
while age.isdigit() == False:
age = input("What is your age?")
this.age = age
def get_country(this):
country = input("Which country are you in?")
this.country = country
def get_moreprincipal(this):
countryname = input("PLease add the country name you wanna input")
drivingage = input("Please input the age at which is leggally to drive")
while drivingage.isdigit() == False:
print("The age has to be a numerical number")
drivingage = input("Please input the age at which is leggally to drive?")
this.principle[countryname] = int(drivingage)
def JudgeDrive(this):
try :
legalage = this.principle[this.country]
if int(this.age) < legalage:
print("You are not old enough to legally drive")
else:
print("You are old enough to legally drive")
except :
print("Sorry,we don't have the country's driving info")
lesson16 = Driver()
lesson16.get_age()
lesson16.get_country()
lesson16.get_moreprincipal()
lesson16.JudgeDrive()
效果图:
java 代码,
- 这里把scanner 作为一个field ,最后再close.
- 增加了一个函数GetMorePrincipal(),可以先输入国家及允许的年龄。
import java.util.HashMap;
import java.util.Scanner;
public class App {
private int age ;
private HashMap<String,Integer> principal = new HashMap<String,Integer>();
private String country;
private Scanner sc = new Scanner(System.in);
private static boolean isNumeric(String secondstring) {
return secondstring != null && secondstring.matches("\\d+(\\.\\d+)?");
}
void GetAgeCountry(){
System.out.println("What is your age?");
String age= this.sc.nextLine();
while (isNumeric(age) == false)
{
System.out.println("What is your age?");
age= this.sc.nextLine();
}
this.age = Integer.parseInt(age) ;
System.out.println("Which country are you in?");
this.country = this.sc.nextLine();
}
void GetMorePrincipal(){
System.out.println("PLease add the country name you wanna input");
String Countryname = this.sc.nextLine();
System.out.println("Please provide the age at which is leggaly right to drive");
String drivingage = this.sc.nextLine();
this.principal.put(Countryname,Integer.parseInt(drivingage));
}
void JudgeDrive(){
this.principal.put("US",16);
this.principal.put("CN",20);
int legalage = this.principal.get(this.country);
if (this.age > legalage)
{
System.out.println("You are old enough to legally drive at "+ this.age + " in " + this.country);
}
else{
System.out.println("You are not old enough to legally drive at "+ this.age + " in " + this.country);
}
}
public static void main(String[] args) throws Exception {
App lesson16 = new App();
lesson16.GetAgeCountry();
lesson16.GetMorePrincipal();
lesson16.JudgeDrive();
lesson16.sc.close();
}
}
效果图: