如何在Java中将值添加到ArrayList
,然后将值打印到每个对象。
import java.util.ArrayList;
import java.util.Scanner;
public class exercise {
private ArrayList<String> files;
public void ArrayList() {
a = new ArrayList<>();
}
public void addObject() {
a.add("blue")
a.add("green")
a.add("yellow")
}
public void addValue(String Object) {
for (String filenames : a)
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
a.set(n)
}
}
我想尝试通过用户输入为“ blue”,“ green”和“ yellow”分配值,以便它可以是任何值
答案 0 :(得分:0)
编辑:
您想接受用户的输入,如果它是预定义的颜色(例如“蓝色”),然后将该颜色的预定义数字(例如3)添加到列表中?对吧?
如果是这种情况,则此代码从控制台获取用户的输入,检查该输入是否为预定义的颜色,然后将匹配的数字存储在ArrayList
中。
当用户输入“ 停止”时,程序仅打印列表中的数字,然后终止。
import java.util.ArrayList;
public class Exercise {
private static ArrayList<Integer> list = new ArrayList<Integer>(); // You can initialize your ArrayList here as well
public static void main(String[] args) {
String userInput = null;
int number = 0;
do{
// Read inputs as long as user did not entered 'stop'
userInput = readUserInput();
number = createNumberFromColor(userInput);
// add the number to the list if it's not 0
if (number!=0) {
list.add(number);
}
}while (!userInput.equals("stop"));
// If you want afterwards you can print the list elements
System.out.println("The list contains:");
for (int i=0; i<list.size(); i++) {
System.out.print(""+list.get(i)+" ");
}
System.out.println();
}
private static String readUserInput(){
// This is an easier way to read the user input from the console
// than using the Scanner class, which needs to be closed etc...
return System.console().readLine();
}
private static int createNumberFromColor(String input){
switch (input) {
// Add your own cases here, for example case "red": return 1, etc...
case "blue":
return 5;
case "yellow":
return 3;
// If the input was not a known color then return 0
default:
return 0;
}
}
}