2017-02-09 15 views
-1

私は次のようにフォーマットされたCSVファイルを持っています。その後、私の出力では、この間違った出力は()

String newText = text.replaceAll("","0"); 

をやって、それは私が欲しいものである0では値の要素を交換しないですが、それはまた、前と値を持っている要素の後に0を付加しています。

010 
0 
030 
040 
030 
040 
0 
000 
020 
0 
040 
020 

ご迷惑をおかけして申し訳ありません。

EDIT:ここでは、クレアリゼーションのための私のコードの残りの部分です。

import java.lang.*; 

public class DataMatrix { 

    private double[][] dMatrix; 

    public DataMatrix(String text) { 

     String[] line = text.split("\n"); 
     // Creates an array for the CSV file 
     String[][] sMatrix = new String[line.length][]; 

     for(int i=0; i < line.length; i++) 
      sMatrix[i] = line[i].split(","); 

     /*for(int j=0; j < sMatrix.length; j++) { 
      for(int x=0; x <= line.length; x++) { 
       if(sMatrix[j][x] !=*/ 

     System.out.println("Original String: "); 

     for(int x=0; x < sMatrix.length; x++) { 
      for(int j=0; j <= line.length; j++) { 
       System.out.println(sMatrix[x][j]); 
      } 
     } 

     dMatrix = new double[sMatrix.length][]; 
     System.out.println("Converted to double: "); 

     for(int x=0; x < sMatrix.length; x++) { 
      dMatrix[x] = new double[sMatrix[x].length]; 
      for(int j=0; j <= sMatrix.length; j++) { 

       dMatrix[x][j] = Double.parseDouble(sMatrix[x][j]); 
       System.out.println(dMatrix[x][j]); 
      } 
     } 
    } 

    public void avgRowValue() { 

     double tempTotal = 0; 

     for(int x=0; x < dMatrix.length; x++) { 
      System.out.println("***********************************"); 
      System.out.println("The average for row "+(x+1)+" is: "); 

      for(int i=0; i < dMatrix[x].length;i++) { 
       tempTotal += dMatrix[x][i]; 
      double rowAvg = tempTotal/dMatrix[x].length; 
      System.out.println(rowAvg); 
      tempTotal = 0; 
      } 
     } 

    } 

    public void avgColValue() { 

     double tempTotal = 0; 

     for(int x=0; x < dMatrix[0].length; x++) { 
      System.out.println("**************************************"); 
      System.out.println("The average for column "+(x+1)+" is: "); 

      for(int i=0; i <= dMatrix.length-1; i++) 
       tempTotal += dMatrix[i][x]; 
      double colAvg = tempTotal/dMatrix.length; 
      System.out.println(colAvg); 
      tempTotal = 0; 
     } 
    } 

    public void overallAvgValue() { 

     double tempTotal = 0; 
     int count = 0; 

     for(int x=0; x < dMatrix.length; x++) { 
      for(int i=0; i <= dMatrix.length; i++) { 
       tempTotal += dMatrix[x][i]; 
       count++; 
      } 
     } 
     double overallAvg = tempTotal/count; 
     System.out.println("The overall average for the data matrix is: "+overallAvg); 
    } 

    public void maxValue() { 

     double maxValue = 0; 

     for(int x=0; x < dMatrix.length; x++) { 
      for(int i=0; i <= dMatrix.length; i++) { 
       if(dMatrix[x][i] >= maxValue) 
        maxValue = dMatrix[x][i]; 
      } 
     } 
     System.out.println("The max value for the data matrix is: "+maxValue); 
    } 

    public void minValue() { 

     double minValue = dMatrix[0][0]; 

     for(int x=0; x < dMatrix.length; x++) { 
      for(int i=0; i <= dMatrix.length; i++) { 
       if(dMatrix[x][i] <= minValue) 
        minValue = dMatrix[x][i]; 
      } 
     } 
     System.out.println("The min value for the data matrix is: "+minValue); 
    } 
} 

と私のメイン:私は、その後、そのファイルを読み、あなたがそれらが発生したとして空のセルを置き換えるために、このようなOpenCSVとしてライブラリを使用することをお勧め

import java.util.*; 

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

     Scanner input = new Scanner(System.in); 

      //Make sure the user passed the command line argument - and nothing else 
      if (args.length != 1){ 
       System.out.println("Assignment1 takes exactly one command-line argument."); 
        System.out.println("Usage: java Assignment1 some_file.csv"); 
       System.exit(0); 
      } 

      String csvFileName = args[0]; 

      //Instantiate my custom file reader 
     CSVReader fileReader = new CSVReader(); 

     //Read the file into a string 
     String text = fileReader.readFile(csvFileName); 
    String newText = text.replaceAll("", "0"); 
    //Create a new instance of DataMatrix that takes in String CSV file and converts to double array 
    DataMatrix matrix = new DataMatrix(newText); 

    boolean done = false; 
    while(done != true) { 
     System.out.println("**********************"); 
     System.out.println("CSV Reader Menu: "); 
     System.out.println("1. Display the average values of each individual row."); 
     System.out.println("2. Display the averages value of each individual column."); 
     System.out.println("3. Display the average of the entire data matrix."); 
     System.out.println("4. Display the maximum value of the entire data matrix."); 
     System.out.println("5. Display the minimum value of the entire data matrix."); 
     System.out.println("0. Exit."); 

     int choice = input.nextInt(); 
     switch(choice) { 
      case 1: matrix.avgRowValue(); 
       break; 
      case 2: matrix.avgColValue(); 
       break; 
      case 3: matrix.overallAvgValue(); 
       break; 
      case 4: matrix.maxValue(); 
       break; 
      case 5: matrix.minValue(); 
       break; 
      case 0: done = true; 
       break; 
      default: System.out.println("Invalid input."); 
       break; 
     } 
    }//end of menu loop 
    }//end of main 
}//end of class 
+0

@azurefrogバギーコード... –

+0

の作品、'、出力がなければなりません: '0 0'ですが、あなたのコード出力は何もありません –

+0

混乱@azurefrogのために申し訳ありません!私がしようとしているのは、csvファイルを読み込んで、それを配列に入れることです(すでに行っています)。次に、csvファイルのスポットの1つに値がなく、0を割り当てる必要があるとき。 –

答えて

0

。それはより堅牢になります。

0

コンマに基づいて行を分割した後、textには単一の列の値が含まれていることを理解します。空の文字列を "0"に変更したい。

replaceAll()メソッドは、正規表現が必要です。空文字列は正規表現にとっては奇妙です。あなたがしたいのはtext.replaceAll("^$", "0")です。

+1

は、例として ',,'で動作しますか? –

+0

@Mohsen_Fatemi no、OPは ',,'をチェックする必要はありません。彼はすでにその行を別々の値に分割しています。カンマはもはや存在しません。 –

+0

@KlitosKyriacouあなたの返事をありがとう。私はあなたが述べたことを試して、私の出力で空の値を0に置き換えません。 –

3

text.replaceAll("", "0")とすると、文字列の長さがゼロの部分文字列がある場所をすべて探しています。これは、任意の2つの文字の間だけでなく、文字列の先頭と末尾にも、どの文字列でもあります。

"12345".replaceAll("", "_") // _1_2_3_4_5_ 

あなたはが本当にはこのために正規表現を使用する場合は、それぞれ、^$は、文字列の先頭と末尾あるreplaceAll("^$", "0")を、使用することができます。また、単なる文字列が空であるかどうかを確認します

String newText = text.isEmpty() ? "0" : text; 

例:

for (String s : "1,,23,4".split(",")) { 
    System.out.println(s.isEmpty() ? "0" : s); // prints 1, 0, 23, and 4 
    System.out.println(s.replaceAll("^$", "0"));// prints 1, 0, 23, and 4 
} 

あなたは元の文字列にそれらの0を挿入したい場合は、すなわちsplitを使用する前に、あなたが使用することができます文字列の開始、中文字列、および文字列終了の場合に異なる正規表現を使用する場合は、アサーションをlookahead and lookbehindとしてください。 「の文字列開始または,が先行する」ための(?<=^|,)、および「,または終わりの文字列が続く」の(?=,|$)

String nums = ",1,,23,4,"; 
System.out.println(nums.replaceAll("(?<=^|,)(?=,|$)", "0")); 
// output: 0,1,0,23,4,0 

それとも、に置換文字列でキャプチャグループとグループ参照を使用することができます,を交換用に運んでください。ここで、$10$2手段「は第一グループを、そして0、その後、第二グループ」:

System.out.println(nums.replaceAll("(^|,)(,|$)", "$10$2")); 
+0

あなたの答えをありがとう。 replaceAllオプションまたはtext.isEmptyオプションのいずれかを試したときに、文字列が空であるという数値書式例外エラーが発生しました。 –

+0

これは間違っています。入力が '123、、5'の場合、答えは '0102030 0 050' –

+1

@Mohsen_Fatemiどうなりますか?あなたは、コードの最初の行は私の答えではなく、OPの現在のコードが何をしているのかを説明することに気付いています。下の部分に提示されている2つの方法のどちらがその出力をどのように生成するのでしょうか? –

1

iはcsvファイルから読み込み中にこれを行うことを好む、そのコストは、CSVファイルを読み込んだ後にそれを行うよりもはるかに小さいので、私は作りますcsvreaderとLineという配列、CSVファイルから行ずつ読み出し、文字列の長さは、それがこのモードで書か0より大きい場合:それ以外の場合は0

CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); 
String [] Line; 
while ((Line = reader.readNext()) != null) { 
    for(int i = 0 ; i < Line.length ; i++) 
     if(Line[i].length>0) System.out.println(Line[i]); 
     else System.out.println("0"); 
} 

として書き込まれ、0thatstring0この方法、私は分割の方法を使用して","と各文字列をsplitingされ、それを提供していないよ、replace方法を行うと、それはバグだらけの例 `@azurefrog

+0

'split'の代わりに' CSVReader'を使うのに適しています。しかし、あなたは要件を誤解しているようです。 OPは123、、5を,0,050に変えたくありません。彼は123,0,5を望んでいる。 '!Line [i] .isEmpty()'なら 'Line [i]'だけを出力する必要があります。 –

+0

あなたは正しいです!私は今それを編集します、ありがとう –