繁体   English   中英

(Java) 有没有办法在方法中创建变量并每次更改变量的名称?

[英](Java) Is there a way to create a variable in a method and change the name of the variable each time?

我有一个 Word 类,用于存储名称、词性和定义:

public class Word{
    String name;
    String partOfSpeech;
    String definition;

    public Word(String s1, String s2, String s3){
        name = s1;
        partOfSpeech = s2;
        definition = s3;
    }
}

在另一个文件中,我有一个创建新 Word 的方法

public static void addWord(Scanner userInput) {
        System.out.print("Enter word:");
        String word = userInput.next();
        System.out.print("Enter the part of speech of " + word + ": ");
        String POS = userInput.next();
        System.out.print("Enter the definition of " + word + ": ");
        String definition = userInput.nextLine();
        Word *** = new Word(word, POS, definition);
    }

我想将每个新单词命名为实际单词本身,而不是每次调用该方法时都使用相同的名称。 我在网上搜索,但找不到任何答案。

在java中不可能

你为什么要这么做? 您可以简单地使用某种列表保存新创建的 Word 对象。 该列表将允许您迭代并获取所需的信息。

String name;
String partOfSpeech;
String definition;

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM