我对java很新,发现很难习惯这些术语,我已经搜索了互联网,但我尝试的一切都不起作用,因为我不知道如何在我的代码中正确实现它......我可以简单地让控制台显示我输入到数组列表中的内容吗?感谢
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Account {
List<String> name = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> createOption = new ArrayList<>();
List<String> sortCode = new ArrayList<>();
List<Integer> deposit = new ArrayList<>();
List<Double> accountNumber = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
public void accountCreation() {
String name = "", address = "", createOption = "", sortCode = "", deposit = "";
double accountNumber = 0;
boolean valid = false;
while (!valid) {
System.out.println("What account would you like to create?");
System.out.println("Current or savings?");
createOption = keyboard.nextLine();
if (createOption.equalsIgnoreCase("current") || createOption.equalsIgnoreCase("savings")) {
valid = true;
} else {
System.out.println("Please enter checking or savings");
}
}
System.out.print("Please enter your name:");
name = keyboard.nextLine();
System.out.print("Please enter your address");
address = keyboard.nextLine();
System.out.print("Please enter an initial deposit");
deposit = keyboard.nextLine();
System.out.print("Please enter an sort code ");
sortCode = keyboard.nextLine();
System.out.print("Please enter an account number");
accountNumber = Double.parseDouble(keyboard.nextLine());
valid = false;
System.out.println();
}
}
答案 0 :(得分:0)
你做错了。您必须使用add()
将项目添加到ArrayList
。
例如:
name.add(keyboard.nextLine());
为了显示ArrayList
中的项目,您可以按如下方式使用循环:
for(String n : name) {
System.out.println("Name: " + n);
}
您必须为您计划中的所有其他ArrayLists
更正此内容。
答案 1 :(得分:0)
我更改了您的完整名称,因为您的代码无法打印任何内容,因为主方法丢失了:
public class Account {
public static void main(final String[] args) {
new Account().accountCreation();
}
List<String> names = new ArrayList<String>();
public void accountCreation() {
final Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your name:");
names.add(keyboard.nextLine());
for (final String name : names) {
System.out.println("Name: " + name);
}
}
}
你可以用类似的方式完成剩下的工作。 (只有当你想要有很多条目时,ArrayList才有意义;如果你需要,你应该循环。)....