自动创建按时间顺序的变量名称

时间:2014-08-30 06:20:36

标签: java arrays variables

我正在编写一个将输入多项式的程序。需要为每个多项式输入创建一个新的ArrayList,我需要一种方法来命名每个列表而不事先知道多项式的数量。如果一个文件有2个多项式,我需要命名2个数组,但如果有更多的多项式,我需要命名更多的数组。无论如何,使用循环的迭代自动命名数组或变量。我无法弄清楚如何。变量名如:P1,P2,P3等随着多项式的数量的增加是我正在寻找的。每个多项式将逐行读取。我附上了我的代码,虽然它还远未完成。我想我需要将PolyCalc创建移动到while循环中,并为每行输入创建一个新的PolyCalc。我希望将此功能添加到main方法的while循环中。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


public class PolyProcessor {
    static int polyNum = 0;
public static void main(String[] args) throws FileNotFoundException{


    File polyfile = new File("polyinput.txt");
    Scanner read = new Scanner(polyfile);
    while (read.hasNextLine()){
        PolyCalc c = new PolyCalc();
        String j = read.nextLine();
        c.add(j.split(";"));
        polyNum++;}


    }
    }


class PolyCalc{
    static int polyCount = 0;

    static ArrayList polynomials = new ArrayList();

     static void add(String[] strings){
         for(int i = 0; i<strings.length;i++){
           polynomials.add(strings[i]);
           polyCount++;}
     }
     static Object get(int i){
         return polynomials.get(i);

     }
}

4 个答案:

答案 0 :(得分:1)

为什么不使用密钥是变量名的(哈希)映射?

Map polys = new HashMap();

int count=0;

For ...
    string key = String.format("p%02d",count++);
    polys.put(key, newPoly(...));

我必须查找String.format,但这样的话。

需要保留订单,因此只需选择足够长的零填充键即可进行排序。和/或使用保持插入顺序的linkedHashMap。

答案 1 :(得分:0)

首先,你不能使用变量来做到这一点。 Java不允许您动态声明变量。它不是那种编程语言......


如果必须将多项式存储在ArrayList中,则:

  • 让用户按编号(即列表中的位置)而不是按名称来引用多项式,或

  • 创建一个从名称映射到列表中的位置的哈希映射,或

  • 将多项式同时存储为ArrayList<String>HashMap<String, String>

实际上,我认为你可能误解了编程练习的要求。我怀疑您被要求将每个单项多项式表示为ArrayList(或其中包含ArrayList的自定义类)。将多项式表示为String并不允许您对其进行任何操作...无需先解析String并将其转换为其他形式。

答案 2 :(得分:0)

作为斯蒂芬的答案,你说arraylist是强制性的,你仍然可以使用ArrayList

ArrayList numbers = new ArrayList();


HashMap<String,ArrayList> myPolys = new HashMap<String,ArrayList>();

并使用HashMap

myPolys.put(what do you want to call them or your so "called" variables , numbers);

答案 3 :(得分:0)

由于你绝对需要使用ArrayList类来存储多项式,你可以使用它的add(int index,E Element)method,如下所示:

List polynomials= new ArrayList(); 
for(int k=0;k < counter;k++){
    polynomials.add(k, new Poly(...));
}

您不会P0P1,... {polynomials.get(0)polynomials.get(1),... 感谢gmhk中的this