首页 > 解决方案 > 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" 所以它可以是任何值

标签: javaarraylistjava.util.scanner

解决方案


编辑:

你想接受用户的输入,如果它是预定义的颜色,比如“蓝色”,那么为该颜色添加一个预定义的数字,比如 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;
        }
    }
}

推荐阅读