该程序跟踪已从陈列室出售的汽车。 系统应该允许他
- 添加新车
- 根据车牌号获取特定汽车的详细信息
- 获取所有汽车的详细信息
汽车细节包括底盘 编号、制造商、型号、发动机容量和注册年份。国民身份证 买家的号码也与汽车的详细信息一起存储。所有这些 详细信息保存在单个字符串中,其中每个组件由“!”分隔。 系统应允许根据车牌号对汽车进行索引 (这是一个字符串)。 例如,如果出售的汽车包含以下详细信息:
注册号:1910JN2011 底盘号:23432-423 品牌: 宝马 型号:X5 发动机排量 : 3000 cc 注册年份:2011 买家编号:S012345678910
映射中的键值对将是: “1910JN2011”-> 23432-423!宝马!X5!3000!2011!S012345678910”
这是我已经解决的问题:
public class dsa_qu2c {
//Function display(String G) takes as input the string and displays the attributes
public static void display(String G){
String Details[]= G.split("!");
//split() allows splitting of a string based "!" and returns an array of strings
System.out.println("Chassis Number:\t"+Details[0]);
System.out.println("Make:\t"+Details[1]);
System.out.println("Model:\t"+Details[2]);
System.out.println("Engine Capacity:\t"+Details[3]);
System.out.println("Year of Registration:\t"+Details[4]);
System.out.println("Buyer NIC:\t"+Details[5]);
}
public static int menu(){
Scanner sc= new Scanner(System.in);
int choice;
System.out.println("1:Add a car.");
System.out.println("2:Display car based on registration number");
System.out.println("3:Display all details of car");
choice=sc.nextInt();
sc.nextLine();
return choice;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String S= ""; //Compiled string to be stored as value in the hashmap
String R= ""; //Registration number to be stored as key in the hashmap
Scanner sc= new Scanner(System.in);
int choice;
HashMap<String, String> HMap= new HashMap<String, String>();
while(true){
choice= menu();
switch(choice)
{
case 1 : {
System.out.println("Enter registration number");
R= sc.nextLine();
System.out.println("Enter compiled string");
S= sc.nextLine();
HMap.put(R,S);
break;
}
case 2: {
System.out.println("Enter registration number");
R= sc.nextLine();
String value= HMap.get(R);
display(value);
break;
}
case 3: {
for(Map.Entry entry: HMap.entrySet()){
display((String)entry.getValue());
break;
}
}
case 4: {
System.exit(0);
}
default: {
break;
}
}
}
}
}
只有系统必须检索所有汽车数据的情况 3 无法正常工作,因为当我选择该选项时没有显示任何内容。
最佳答案
在情况 3 中,将 break 放在 for 循环之后。当您使用 switch case 时,删除中断实际上并不能成为良好的编码实践
关于java - HashMap:通过解密函数中的加密字符串来获取HashMap中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42489917/