简体   繁体   English

如何让程序用Java创建自己的变量?

[英]How do I have a program create its own variables with Java?

I would like to start off by saying that if this is common knowledge, please forgive me and have patience. 我想首先说,如果这是常识,请原谅我并有耐心。 I am somewhat new to Java. 我对Java有些新意。 I am trying to write a program that will store many values of variables in a sort of buffer. 我正在尝试编写一个程序,它将在一种缓冲区中存储许多变量值。 I was wondering if there was a way to have the program "create" its own variables, and assign them to values. 我想知道是否有办法让程序“创建”自己的变量,并将它们分配给值。 Here is an Example of what I am trying to avoid: 以下是我要避免的示例:

package test;

import java.util.Scanner;

public class Main {
     public static void main(String args[]) {

        int inputCacheNumber = 0;
        //Text File:
        String userInputCache1 = null;
        String userInputCache2 = null;
        String userInputCache3 = null;
        String userInputCache4 = null;

        //Program
        while (true) {
            Scanner scan = new Scanner(System.in);
            System.out.println("User Input: ");
            String userInput;
            userInput = scan.nextLine();

            // This would be in the text file
            if (inputCacheNumber == 0) {
                userInputCache1 = userInput;
                inputCacheNumber++;
                System.out.println(userInputCache1);
            } else if (inputCacheNumber == 1) {
                userInputCache2 = userInput;
                inputCacheNumber++;
            } else if (inputCacheNumber == 2) {
                userInputCache3 = userInput;
                inputCacheNumber++;
            } else if (inputCacheNumber == 3) {
                userInputCache4 = userInput;
                inputCacheNumber++;
            }
            // And so on

        }

    }
}

So just to try to summarize, I would like to know if there is a way for a program to set an unlimited number of user input values to String values. 所以只是为了总结一下,我想知道程序是否有办法将无限数量的用户输入值设置为String值。 I am wondering if there is a way I can avoid predefining all the variables it may need. 我想知道是否有一种方法可以避免预定义它可能需要的所有变量。 Thanks for reading, and your patience and help! 感谢您的阅读,以及您的耐心和帮助! ~Rane 〜莱恩

You can use Array List data structure. 您可以使用Array List数据结构。

The ArrayList class extends AbstractList and implements the List interface. ArrayList类扩展了AbstractList并实现了List接口。 ArrayList supports dynamic arrays that can grow as needed. ArrayList支持可根据需要增长的动态数组。

For example: 例如:

List<String> userInputCache = new ArrayList<>();

and when you want to add each input into your array like 当你想将每个输入添加到你的数组中时

if (inputCacheNumber == 0) {
    userInputCache.add(userInput); // <----- here
    inputCacheNumber++;
}

If you want to traverse your array list you can do as follows: 如果要遍历数组列表,可以执行以下操作:

for (int i = 0; i < userInputCache.size(); i++) {
    System.out.println(" your user input is " + userInputCache.get(i));
} 

or you can use enhanced for loop 或者你可以使用enhanced for loop

for(String st : userInputCache) {
    System.out.println("Your user input is " + st);
}

Note: it is better to put your Scanner in your try catch block with resource so you will not be worried if it is close or not at the end. 注意:最好将您的Scanner放在try catch block with resource这样您就不会担心它是否在最后关闭。

For example: 例如:

try(Scanner input = new Scanner(System.in)) {
    /*
    **whatever code you have you put here**
    Good point for MadProgrammer:
    Just beware of it, that's all. A lot of people have multiple stages in their   
    programs which may require them to create a new Scanner AFTER the try-block
    */
 } catch(Exception e) {
 }

For more info on ArrayList 有关ArrayList的更多信息

http://www.tutorialspoint.com/java/java_arraylist_class.htm http://www.tutorialspoint.com/java/java_arraylist_class.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让程序创建自己的变量以匹配(无限)用户输入? - How do I have a program create its own variables to match (up to an infinite) amount of user inputs? 如何在Java中创建一个能够改变自己的源代码的程序,或者一个能够运行它的数学函数? - How can I create a program in Java that is able to alter its own source code, or a mathematical function that it is then to run? 在用Java程序创建文件之前,如何创建/修改文件的内容? - How do i create/modify the contents of a file before i create it in a Java program i have made? QueryDSL 如何创建带有自己连接的子查询? - QueryDSL how do I create a SubQuery with its own joins? 如何监视Java程序中变量的值? - How do I monitor the values of variables in a Java program? "Java 程序如何获得自己的进程 ID?" - How can a Java program get its own process ID? Java程序如何完全读取自己的控制台输出? - How can a Java program read its own console output fully? “标题”视图和按钮:如何在没有自己的Activity的“标题”中将监听器附加到按钮? - “Header” Views and buttons: how do I attach listeners to Buttons in a “header” that does not have its own Activity? 我可以在带有变量的特定 java 程序中运行 .java 类吗? - Can I run a .java class in a specific java program with its variables? 如何让一个类创建自己的Graphics实例 - How to have a class create its own instance of Graphics
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM