Java-获取用户输入以访问数组,然后打印信息
我正在制作一个程序,要求用户输入一个汽车模型示例Honda,并访问Honda类。在用户输入模型后,他被要求选择一个本田模型示例“Civic”。当他输入“Civic”时,不同的年份会出现2000年、2013年等。。他选择了一年,而没有关于那辆车的信息 我已经有了第一部分,要求用户输入汽车模型并访问类。我不打算添加太多信息,这只是我正在做的一个项目Java-获取用户输入以访问数组,然后打印信息,java,Java,我正在制作一个程序,要求用户输入一个汽车模型示例Honda,并访问Honda类。在用户输入模型后,他被要求选择一个本田模型示例“Civic”。当他输入“Civic”时,不同的年份会出现2000年、2013年等。。他选择了一年,而没有关于那辆车的信息 我已经有了第一部分,要求用户输入汽车模型并访问类。我不打算添加太多信息,这只是我正在做的一个项目 import java.util.Scanner; public class carMain { public static void mai
import java.util.Scanner;
public class carMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Honda hondaMain = new Honda("civic");
System.out.println("Welcome to GoAuto. Search from thousands of cars. \n");
System.out.println("Please enter the brand of car you would like to search:");
String carBrand = input.nextLine();
if (carBrand.equalsIgnoreCase("Honda") == true) {
System.out.println("You are now in the Honda class");
//model type
String carBrand1 = input.nextLine();
}
}
}
我假设我需要创建一个数组来存储有关车型和年份的信息,但我不确定如何做到这一点
public class Honda {
String c;
Honda(String civi) {
c = civi;
}
void simplemsg() {
System.out.println("You are now in Honda Database");
}
}
首先,我认为您应该创建表示每个级别的类。例如
public class Make(){
//Add class properties
List<Models> models = new ArrayList();
public function Model get_model_by_name(String name) {
//int index = search for matching Model.name..
return this.models(index)
}
public class Model(){
//Add class properties
List<Years> years = new ArrayList();
public function Model get_year_by_name(String name) {
//int index = search for matching Year.name..
return this.models(index)
}
public class Year(){
//Add class properties
String info;
String info2;
}
public类Make(){
//添加类属性
列表模型=新的ArrayList();
公共函数模型按名称获取模型(字符串名称){
//int index=搜索匹配的Model.name。。
返回此。模型(索引)
}
公共类模型(){
//添加类属性
列表年份=新的ArrayList();
公共函数模型按名称获取年份(字符串名称){
//int index=搜索匹配的年份。名称。。
返回此。模型(索引)
}
公共课年(){
//添加类属性
字符串信息;
字符串信息2;
}
然后在main方法中,您可能希望像这样初始化值
//Initialize database
List<Make> database = new arrayList();
Make ford = new Make(<insert values for all properties>)
database.add(ford);
// Access ford..
System.out.println(ford.get_year_by_name(<whatever value user passed in>)
//初始化数据库
列表数据库=新的arrayList();
制造福特汽车
数据库.add(ford);
//进入福特。。
System.out.println(ford.get\u year\u by\u name()
显然,这是伪代码,您需要添加所需的任何构造函数和属性以及适当的getter和setter。理想情况是使用数据库查找或某种枚举文件。您不需要在equalsIgnoreCase之后放置==true
if(carBrand.equalsIgnoreCase("Honda")){
如果你想在一个数组中存储年份和汽车信息,请查看二维数组。正如其他答案所说,尽管你可以研究一些更内聚的编码方法是否可以将信息存储在某种数据库中?这将使你更容易访问数据并向用户显示数据我问这个问题由于范围问题的估计:这是家庭作业还是生产作业?因为数据结构非常大,我不会使用数组,因为它会变得不可维护。正如@LearningPhase刚刚指出的,对于任何真实的东西,数据库都是这个问题解决方案的一部分。脱离主题但
if(boolean==true)
是不必要的。如果(boolean),您只需编写if(boolean)
。这只是一个小项目。我想习惯使用类和访问信息。我不打算添加太多。奇怪的Java语法;)