我使用","来解决.split()方法问题。作为界限。 Java的

时间:2015-11-29 19:41:11

标签: java

因此,对于我目前的学校项目,我们必须从包含元素周期表信息的文件中读取输入。基本上我必须分开每行的位,这些位在元素上有信息并将它们放入单独的字符串值中。

这里有一些代码我遇到了问题。

for(int i=0;inputStream.hasNextLine();i++)
    {
        String line = inputStream.nextLine();
        String[] info = line.split(",");

        name=info[0];
        atomicNumber=info[1];
        symbol=info[2];
        boilingPoint=info[3];
        meltingPoint=info[4];
        density=info[5];
        molecularWeight=info[6];


        elementInfo[i]= new Element(name,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);

它将所有东西都存放在适当的位置,除了密度和分子量的信息,我得到空值。我无法找到任何信息,为什么它不适用于最后两个字符串。

示例输出:

元素名称:actinium

原子序数:89

符号:Ac

沸点:3470

熔点:1324

密度:null

分子量:null

这里是元素对象的构造函数:

public Element(String name,String atomicNumber,String symbol, String boilingPoint, String meltingPoint, String density, String molecularWeight)
{
    this.name=name;
    this.atomicNumber=atomicNumber;
    this.symbol=symbol;
    this.boilingPoint=boilingPoint;
    this.meltingPoint=meltingPoint;
    this.density=density;
    this.molecularWeight=molecularWeight;
}

4 个答案:

答案 0 :(得分:0)

你可以尝试这个,

  

//表示信息不存在的文件,在这种情况下采用其默认值,即空

info[5] == null ? "empty" : info[5]; 
info[6] == null ? "empty" : info[6];

答案 1 :(得分:0)

您正在阅读的文件肯定包含7个元素,否则以下代码将导致错误

密度=信息[5]; molecularWeight =信息[6];

示例:

import java.util.*;


public class TestFinder {
    Map<String, Item> map = new HashMap<String, Item>();


    public void finder(List<String> targets, String startid){
        List<List<String>> path = new ArrayList<List<String>>();
        List<List<List<String>>> result = new ArrayList<List<List<String>>>();

        dfs(startid, targets, path, result);

        // print out result
        System.out.println(result.size());
        for(int i=0; i<result.size(); i++){
            for(int j=0; j<result.get(i).size(); j++){
                for(int k=0; k<result.get(i).get(j).size(); k++){
                    System.out.println(result.get(i).get(j).get(k) + " ");
                }

            }
            System.out.println();
        }
    }

    public void dfs(String id, List<String> targets, List<List<String>> path, List<List<List<String>>> pathList){
        if(targets.size() == 0){
            pathList.add(new ArrayList<List<String>>(path));
            return;
        }

        if(!map.containsKey(id)){
            System.out.println("This is doesn't exist!");
            return;
        }

        List<String> list = new ArrayList<String>();
        list.add(id); // add current item id to the head of list
        list.addAll(map.get(id).idList);

        int size = list.size();
        for(int i=0; i<size; i++){

            if(i==0){
                Item cur = map.get(list.get(i));
                List<String> l = new ArrayList<String>();
                l.add(cur.id);
                if(targets.contains(cur.str)){
                    l.add(cur.str);
                    targets.remove(cur.str);
                }
                path.add(l);
            }
            // else if i is greater than 0, set this id in idList as visited by removing it from idList
            else if(map.containsKey(list.get(i))){
                System.out.println("i is greater than 0");
                Item curTemp = map.get(list.get(i));
                List<String> idListTemp = curTemp.idList;
                idListTemp.remove(list.get(i));
                map.remove(id);
                map.put(curTemp.id, new Item(curTemp.id, idListTemp, curTemp.str));

                List<String> l = new ArrayList<String>();
                l.add(map.get(curTemp.id).id);
                if(targets.contains(map.get(curTemp.id).str)){
                    l.add(map.get(curTemp.id).str);
                    targets.remove(map.get(curTemp.id).str);
                }
                path.add(l);
                if(i<size-1){
                    dfs(list.get(i+1), targets, path, pathList);
                    path.remove(path.size()-1);
                }

            }

        } // end for







    }

    public void buildInput(){
        List<String> temp1 = new ArrayList<String>();
        temp1.add("Donald");
        temp1.add("Barbara");
        Item it1 = new Item("Thomas", temp1, "a");
        map.put("Thomas", it1);

        List<String> temp2 = new ArrayList<String>();
        temp2.add("Sarah");
        temp2.add("Lisa");
        Item it2 = new Item("Donald", temp2, "");
        map.put("Donald", it2);


        List<String> temp3 = new ArrayList<String>();
        Item it3 = new Item("Lisa", temp3, "c");
        map.put("Lisa", it3);


        List<String> temp4 = new ArrayList<String>();
        temp4.add("Lisa");
        temp4.add("Thomas");
        temp4.add("Barbara");
        Item it4 = new Item("Sarah", temp4, "d");
        map.put("Sarah", it4);

        List<String> temp5 = new ArrayList<String>();
        temp5.add("Sarah");
        Item it5 = new Item("Barbara", temp5, "e");
        map.put("Barbara", it5);
    }

    public static void main(String[] args) {
        TestFinder tf = new TestFinder();
        tf.buildInput();

        List<String> targets = new ArrayList<String>();
        targets.add("a");
        targets.add("c");
        targets.add("d");
        tf.finder(targets, "Donald");

    }    
}

class Item{
    String id;
    List<String> idList;
    String str;


    Item(String i, List<String> il, String s){
        id = i;
        idList = il;
        str = s;
    }

}

上述代码段的输出为5和[1,2,3,4,5] 在这里,我们不能使用info [5]或info [6],因为它会导致错误。

因此,您的数据是正确的,并且您正在捕获所有值。 我认为问题在于打印输出,但您没有在查询中提到要深入调查的代码。

希望它有所帮助。

答案 2 :(得分:0)

String.split()永远不会返回null(请参阅here),这意味着问题不在于split()方法,而在其他地方。 split()方法似乎至少返回7个数据块,这是因为执行此操作ArrayIndexOutOfBoundException时没有得到molecularWeight=info[6]

然后问题出在其他地方,您可以通过查看代码找到答案,并且必须有一些您缺少的东西,非常简单。

假设您有以下输入(2个元素):

actinium,89,Da,3470,1926,missing-x,missing-y
actinium,13,Gk,5480,1124,missing-z,missing-w

我使用了大部分代码,并开发了一个示例用例来从文件中读取上述两个元素,并将它们存储在一个列表中并打印回来。我使用List<Element>代替您的Element[]解决方案,并在Element类中覆盖toString()以使用Java 8的流来完美地打印元素,请参见下文并与您的解决方案进行比较:< / p>

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

public class ReadFromFileElements {
    public static void main(String... args) throws FileNotFoundException {
        // You can use list instead of Element[] array
        List<Element> elementInfo = new ArrayList<Element>(); 

        //file containing the input
        File file = new File("C:\\test_java\\elements.txt"); 

        //open input stream to the file
        Scanner input = new Scanner(file); 

        //as long as there is nextLine() keep looping
        while(input.hasNextLine()) {
            String line = input.nextLine();
            String[] chunk = line.split(",");

            Element e = new Element(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5],
                    chunk[6]);

            //add to the list of Element/s
            elementInfo.add(e); 
        }

        //close input stream
        input.close(); 

        //java 8 stream iterator through collection
        elementInfo.stream().forEach((temp) -> {
            //temp.toString() uses the overrided toString() of element class
            System.out.println(temp.toString()); 
        }); 
    }
}

class Element {
    String name;
    String atomicNumber;
    String symbol;
    String boilingPoint;
    String meltingPoint;
    String density;
    String molecularWeight;

    public Element(String name, String atomicNumber, String symbol, String boilingPoint, String meltingPoint,
            String density, String molecularWeight) {
        this.name = name;
        this.atomicNumber = atomicNumber;
        this.symbol = symbol;
        this.boilingPoint = boilingPoint;
        this.meltingPoint = meltingPoint;
        this.density = density;
        this.molecularWeight = molecularWeight;
    }

    public String toString() {
        StringBuilder builder  = new StringBuilder(); 
        builder.append("\n Element name: " + this.name); 
        builder.append("\n Atomic no: " + this.atomicNumber); 
        builder.append("\n Symobl : " + this.symbol); 
        builder.append("\n Boiling point : " + this.boilingPoint); 
        builder.append("\n Melting point : " + this.meltingPoint); 
        builder.append("\n Density : " + this.density); 
        builder.append("\n Molecular weight: " + this.molecularWeight); 

        return builder.toString();

    }
}

对文件中的上述两行运行上面的代码,我得到以下输入:

Element name: actinium
 Atomic no: 89
 Symobl : Da
 Boiling point : 3470
 Melting point : 1926
 Density : missing-x
 Molecular weight: missing-y

 Element name: actinium
 Atomic no: 13
 Symobl : Gk
 Boiling point : 5480
 Melting point : 1124
 Density : missing-z
 Molecular weight: missing-w

答案 3 :(得分:0)

使用此

       public static void readFileData(String filename) throws FileNotFoundException{
        ArrayList<Element> list = new arrayList<>();
        String split = ","; //split with comma

                Scanner in = new Scanner(new File(filename));

                String wordIn;
                Element elem = new Element();

                while (in.hasNextLine()) {
                    wordIn = in.nextLine();
                    String splitter[] = wordIn.split(split);

                    String name = splitter[0];
                    int atomicNumber = Integer.parseInt(splitter[1]);
                    String symbol = splitter[2];
                    String boilingPoint = splitter[3];
                    String meltingPoint = splitter[4];
                    String density = splitter[5];
                    String molecularWeight = splitter[6]

                    elem.setName(name);
                    elem.setAtomicNumber(atomicNumber);
                    elem.setSymbol(symbol);
                    elem.setBoilingPoint(boilingPoint);
                    elem.setMeltingPoint(meltingPoint);
                    elem.setDensity(density);
                    elem.setMolecularWeight(molecularWeight);
                    list.add(elem);
    }
                  for(Element el : list){
                     sout(el.toString()) // if you have a to string method
                  }
}

     public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        String file = sc.next();
        readFileData(file);
     }

确保您的Element课程中有这些设定者。太过String的方法会很方便,但不是必需的。如果变量在int类中键入Element,则可以执行Integer.parseInt()Double.parseDouble将字符串转换为整数或浮点数等.sout是{{1}的缩写}输入sout + tab,你得到了完整的东西。