【问题标题】:Parsing a CSV string and using elements of the string for computation- homework解析 CSV 字符串并使用字符串的元素进行计算 - 作业
【发布时间】:2013-06-01 15:02:36
【问题描述】:

我对java很陌生,这是作业。任何方向将不胜感激。 任务是读取一个外部文本文件,然后解析该文件以生成一个新文件。 外部文件如下所示:

2             //number of lines in the file
3,+,4,*,2,-.   
5,*,2,T,1,+

我必须读取此文件并生成一个输出,该输出采用前面的 int 值并打印以下字符(跳过逗号)。所以输出看起来像这样:

+++****--
*****TT+

我尝试使用两种方法设置我的代码。第一个读取外部文件(作为参数传递),只要有下一行,就会调用第二个方法 processLine 来解析该行。这就是我迷路的地方。我不知道应该如何构造这个方法,所以它读取行并将标记值解释为整数或字符,然后根据这些值执行代码。 我只能使用我们在课堂上介绍的内容,所以没有外部库,只有基础知识。

public static void numToImageRep(File input, File output) //rcv file
    throws FileNotFoundException {  
        Scanner read = new Scanner(input);
        while(read.hasNextLine()){ //read file line by line
        String data = read.nextLine();
        processLine(data); //pass line for processing
        }
    }
public static void processLine(String text){  //incomplete, all falls apart here.
    Scanner process = new Scanner(text);
    while(process.hasNext()){
        if(process.hasNextInt()){
            int multi = process.nextInt();
            }
        if(process.hasNext()==','){



    }   
}

【问题讨论】:

    标签: string parsing csv fileoutputstream


    【解决方案1】:

    这个方法可以作为一个简单的例子来完成这项工作:

    public static String processLine(String text){
        String result = "";
        String[] splitted = text.split(",");
        int remaining = 0;
        for(int i=0;i<splitted.length;i+=2)
        {
            remaining = (Integer.parseInt(splitted[i]));
            while( remaining-- >0)
                result += splitted[i+1];
        }
            return result;
    }
    

    【讨论】:

    • 谢谢!我最终将您的解决方案合并为一个方法(无需像我最初想的那样调用单独的方法)。非常感谢。
    • 当然,很高兴我能帮上忙 :)
    猜你喜欢
    • 2013-06-12
    • 2017-08-28
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多