java - java中如何给对象赋值
问题描述
如何ArrayList
在 java 中添加一个值,然后将值打印到每个对象。
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" 所以它可以是任何值
解决方案
编辑:
你想接受用户的输入,如果它是预定义的颜色,比如“蓝色”,那么为该颜色添加一个预定义的数字,比如 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;
}
}
}
推荐阅读
- javascript - 如何在不改变圆内半径的情况下改变笔画宽度
- design-patterns - 在以下场景中使用哪种设计模式?
- json - 如何在 json 中转换这种类型的数学?
- c - 将 synproxy 移植到用户空间
- apache - 为子目录 url 预渲染 htaccess
- mongodb - 如何使用 $dateFromString 转换数组中的日期?
- javascript - 如何在 ES6 中将 json 对象数组绑定到 javascript 类数组
- php - 用php中的信息更新图像
- pivot - 1) Informatica Power Center 的标准化转换问题
- python - 从 execute_async_script() 获取结果