如何使用Scanner类向数组列表添加值



我想问如何使用Scanner类向数组列表添加值而不声明任何变量。

List<Integer> cl = new ArrayList<>(); 
List<String> al = new ArrayList<>(); 

System.out.println("Enter the name of the account user");
String name = si.next();
System.out.println("Enter the amount you want to deposit in your account");
int amount= si.nextInt();
cl.add(amount);
al.add(name);

就像下面的代码一样,我想在数组列表中添加值,而不使用变量name和amount。

Scanner si = new Scanner(System.in);
List<Integer> cl = new ArrayList<>();
List<String> al = new ArrayList<>();
System.out.println("Enter the name of the account user");
al.add(si.nextLine());
System.out.println("Enter the amount you want to deposit in your account");
cl.add(si.nextInt());
si.nextLine();

nextLines适用于如果您想在此代码之后使用扫描器,现在扫描器中仍然不会有可能弄乱您的输入的新行字符。我还将next()替换为nextLine(),以防您想要输入包含空格的名称。(nextLine()返回所有东西,直到有一个n,它也删除n。)

最新更新