我希望用户能够输入多个作业,然后输入每个作业的名称。现在我有点用 if else 语句来强迫它
System.out.println("How many jobs have you had?");
int numberjobs = scanner.nextInt();
if (numberjobs == 3) {
System.out.println("What was your first job?");
scanner.nextLine();
company1 = scanner.nextLine();
System.out.println("What was your second job?");
company2 = scanner.nextLine();
System.out.println("What was your third job?");
company3 = scanner.nextLine();
} else if (numberjobs == 2) {
System.out.println("What was your first job?");
scanner.nextLine();
company1 = scanner.nextLine();
System.out.println("What was your second job?");
company2 = scanner.nextLine();
} else if (numberjobs == 1) {
System.out.println("What was your first job?");
scanner.nextLine();
company1 = scanner.nextLine();
}
有没有办法更容易地制作循环?我可以对输入的作业数进行无上限的循环吗?
创建一个公司的集合,然后使用循环填充它:
List<String> companies = new ArrayList<>();
System.out.println("How many jobs have you had?");
int numberjobs = scanner.nextInt();
for (int i=0; i < numberjobs; ++i) {
System.out.println("Enter job " + i + " please:");
String company = scanner.nextLine();
companies.add(company);
}
我们也可以在这里使用数组,但如果程序中的逻辑稍后需要添加更多作业,List
会更灵活。
是的,您可以使用循环:
System.out.println("How many jobs have you had?");
int numberjobs = scanner.nextInt();
String companies[] = new String[numberjobs];
for(int i=0; i<numberjobs; i++) {
System.out.println("What was your job #" + (i+1) + "?");
company[i] = scanner.nextLine();
}