2017-11-10 26 views
1

私は、.txtファイルの内容を読み込んで、そのファイルの内容を検証し、適切な形式のテーブルに出力するプログラムを作成しています。ここに私の問題があります...私のプログラムは現在ファイルを読み込んでコンテンツを出力していますが、私はそのファイルコンテンツの検証を実装しようとしています。txtファイルの内容を確認する

.txtの内容::

firstname lastname 
Gameone : 120 : 1428 
Gametwo : 20 : 10 
Gamethree : 90 : 800 
Gamefour : 190 : 2001 
Gamefive : 25 : 80 
Gamesix : 55 : 862 

txtファイルは、この形式のデータが含まれています。私は今、私のプログラムがファイルを読み込む方法を説明します

{gamename}: {gamescore}:私が使用.txtファイルを読み取るために

を{minutesplayed}

データから欠落している場合、私は、ユーザーに通知する必要が検証することによって明確にするため

//~~~~a-line-split~~~~// 
    String[] aline; 

    aline = a.split(":"); 

    for (int i=0; i<aline.length; i++) 
    { 
     aline[i] = aline[i].trim(); 
     //System.out.println(aline[i]); 
    } 

:次に、以下に示すようにIは対Gから各文字にループのためにこれを使用してデータを分割する

ライン1は、例えばラインを持っていた場合:

gameone:{行方不明}:現在1428

私はこの単純な持っている場合、各ラインの声明:

  if (bline.length < 3) 
      { 
       System.out.println("There is an error in row one!"); 
      } 

しかし、私は、各行のどこにデータがないのかを正確に知るためにはプログラムが必要です。線に沿って

 System.out.println("There is an error in row one!"); 

しかし、その代わりに何か:だけではなく、一般的な応答

 System.out.println("There is data missing, row: 1 column: 2"); 

あなたがこれを持っていればここまで読むために時間を割いていただきありがとうございます。どんなアドバイスも非常に高く評価されます。これが正しいフォーマットでないか、好きでないものがある場合は、コメントを介して私に知らせてください。

ありがとうございました。 Robert。要求されたよう

フルコード:

package readfile; 

    import java.io.*; 
    import java.util.*; 

    public class readfile 
    { 

    public static void main(String[] args) 

    { 
    Scanner scan = new Scanner (System.in); 
    String FileN = " "; 
    String a = " "; 
    String b = " "; 
    String c = " "; 
    String d = " "; 
    String e = " "; 
    String f = " "; 
    String g = " "; 

    boolean fileExists = false; 
    File newFile = null; 
    while(!fileExists) 
    { 
     System.out.println("Enter the name of the file you want to open: "); 
     FileN = scan.nextLine(); 
     newFile = new File(FileN); 
     fileExists = newFile.exists(); 
     if (!fileExists) 

     { 
     System.out.println(FileN + " not found..."); 
     } 

    } 
    try { 
     Scanner scan2; 
     scan = new Scanner(newFile); 
    } 
    catch(FileNotFoundException fnfe) { 
     System.out.println("sorry but the file doesn't seem to exist"); 
    } 


    //++++++++++++++=FILE READ=++++++++++++++++++++ 
    System.out.println("*FILE HAS BEEN LOCATED*"); 
    System.out.println("*File contains: \n"); 
    while(scan.hasNext()) 
    { 
     a = scan.nextLine(); 
     b = scan.nextLine(); 
     c = scan.nextLine(); 
     d = scan.nextLine(); 
     e = scan.nextLine(); 
     f = scan.nextLine(); 
     g = scan.nextLine(); 
    } 

     //+++++++++++++++ARRAYS FOR THE LINES+++++++++++++++++++ 

    //~~~~A-LINE~~~~// 
    String[] aline; 

    aline = a.split(":"); 

    for (int i=0; i<aline.length; i++) 
    { 
     aline[i] = aline[i].trim(); 
     //System.out.println(aline[i]); 
    } 

    //~~~~B-LINE~~~~// 

    String[] bline; 
    bline = b.split(":"); 

    for (int i=0; i<bline.length; i++) 
    { 
     bline[i] = bline[i].trim(); 
     //System.out.println(bline[i]); 
    } 

    //~~~~C-LINE~~~~// 

    String[] cline; 
    cline = c.split(":"); 

    for (int i=0; i<cline.length; i++) 
    { 
     cline[i] = cline[i].trim(); 
     //System.out.println(cline[i]); 
    } 

    //~~~~D-LINE~~~~// 

    String[] dline; 
    dline = d.split(":"); 

    for (int i=0; i<dline.length; i++) 
    { 
     dline[i] = dline[i].trim(); 
     //System.out.println(dline[i]); 
    } 

    //~~~~e-LINE~~~~// 

    String[] eline; 
    eline = e.split(":"); 

    for (int i=0; i<eline.length; i++) 
    { 
     eline[i] = eline[i].trim(); 
     //System.out.println(eline[i]); 
    } 

    //~~~~f-LINE~~~~// 

    String[] fline; 
    fline = f.split(":"); 

    for (int i=0; i<fline.length; i++) 
    { 
     fline[i] = fline[i].trim(); 
     //System.out.println(fline[i]); 
    } 

    //~~~~g-LINE~~~~// 

    String[] gline; 
    gline = g.split(":"); 

    for (int i=0; i<gline.length; i++) 
    { 
     gline[i] = gline[i].trim(); 
     //System.out.println(gline[i]); 
    } 

    String user  = aline [0]; 
    //~~~~~~~~~GAME NAMES~~~~~~~~~~~~~// 

    //GTA 
    String gameone = bline [0]; 

    //MINECRAFT 
    String gametwo = cline [0]; 

    //ASSASSIN'S CREED IV 
    String gamethree = dline [0]; 

    //PAYDAY2 
    String gamefour = eline [0]; 

    //WOLFENSTEIN 
    String gamefive = fline [0]; 

    //FARCRY 4 
    String gamesix = gline [0]; 




    //~~~~~~~~~~Achievement Score~~~~~~~~~~~~// 


    //GTA SCORE 
    String scoreone  = bline [1]; 

    //MINECRAFT SCORE 
    String scoretwo  = cline [1]; 

    //ASSASSIN'S CREED IV SCORE 
    String scorethree = dline [1]; 

    //PAYDAY2 SCORE 
    String scorefour = eline [1]; 

    //WOLFENSTEIN SCORE 
    String scorefive = fline [1]; 

    //FARCRY 4 SCORE 
    String scoresix  = gline [1]; 

//+++++++++++++++++++++TOTAL~~CALC++++++++++++++++++++++// 
    double totalcount = 79.566; // change to the amount played. 
    int totalhours = (int)totalcount; 
    int totalmin = (int)(totalcount*60)%60; 
    int totalsec = (int)(totalcount*(60*60))%60; 
    System.out.println("TOTAL TIME PLAYED:"); 
    System.out.println(String.format("%s(hours) %s(minutes) %s(seconds)", 
    totalhours, totalmin, totalsec));  

    //~~~~~~~~~~Minutes Played~~~~~~~~~~~~// 

    //GTA min 
    String minone  = bline [2]; 

    //MINECRAFT min 
    String mintwo  = cline [2]; 

    //ASSASSIN'S CREED IV min 
    String minthree = dline [2]; 

    //PAYDAY2 min 
    String minfour = eline [2]; 

    //WOLFENSTEIN min 
    String minfive = fline [2]; 

    //FARCRY 4 min 
    String minsix  = gline [2]; 

    //~~~~~~~~~GAMES TEST~~~~~~~~~~~~//  

      System.out.println("\nUSER: "+user); 
      System.out.println("\nDATA: "); 
      System.out.println("1: "+gameone+"  | score: "+scoreone+" 
      | minutes played: "+minone); 
      System.out.println("2: "+gametwo+"  | score: "+scoretwo+" 
      | minutes played: "+mintwo); 
      System.out.println("3: "+gamethree+"  | score: "+scorethree+"  
      | minutes played: "+minthree); 
      System.out.println("4: "+gamefour+"   | score: 
      "+scorefour+" | minutes played: "+minfour); 
      System.out.println("5: "+gamefive+"  | score: "+scorefive+" 
      | minutes played: "+minfive); 
      System.out.println("6: "+gamesix+"  | score: "+scoresix+" 
      | minutes played: "+minsix); 

      if (bline.length < 3) 
      { 
       int column = 0; 
       for(int i = 0; i<bline.length; i++){ 
        column = i; 
        if(bline[i] == null || bline[i].trim() == ""){ 
         System.out.println("There is an error in row two 
        column "+(i+1)); 
        } 
       } 
      } 



} 


} 

答えて

1
if (bline.length < 3) 
{ 
    int column = 0; 
    for(int i = 0; i<bline.length; i++){ 
     column = i; 
     if(bline[i] == null || bline[i].trim() == ""){ 
      System.out.println("There is an error in row two column "+(i+1)); 
     } 
    } 
} 

これをテストしていないが、それは

EDIT動作するはずです:意志ので、あなたの完全なコードbline[2], cline[2]...を見てみると

をし、それらの値が最初の場所でファイルにない場合、その呼び出しを行う前にチェック情報は、それが、

はまた、テストされていない空の文字列をすべき返します不足している場合は、最初のあなたがチェック

public static String getAtIndex(String[] array, int indexToCkeck){ 
    if(indexToCkeck >=array.length){ 
     return ""; 
    } 
    else{ 
     return array[indexToCkeck]; 
    } 
} 

ので、代わりのように、このようにbline[2], cline[2] ...使用readfile.getAtIndex(bline, 2)をやってを行うための静的メソッドを作成することができます

+0

これは、今、私がArrayIndexOutOfBoundsExceptionを受け取った.txtファイル内のブリン配列からデータを削除したときには、どうもありがとうございます。どうすれば解決できますか? – rxbert

+0

ArrayIndexOutOfBoundsException何時ですか? –

+0

if文ではなく、ファイルが読み込まれる場所: – rxbert

1

supercsvまたはany otherのような十分にテストされたライブラリを使用してください。これにより、テキスト形式が複雑になるとすぐに数時間を節約できます。また、データの各単一列を検証するために使用される適切な組み込みデータ型のセットを提供します。また、データをPOJOに直接マップすることもできます。POJOは、状況によっては便利なことがあります。あなたが次のことを行うことができますマップにだけ各行のロードが

stack47220687.txtでファイルを準備します

Gamename: Gamescore: Minutestoplay 
Gameone : 120 : 1428 
Gametwo : 20 : 10 
Gamethree : 90 : 800 
Gamefour : 190 : 2001 
Gamefive : 25 : 80 
Gamesix : 55 : 862 

そしてこの

package stack47220687; 

import java.io.FileReader; 
import java.util.Map; 

import org.junit.Test; 
import org.supercsv.cellprocessor.constraint.NotNull; 
import org.supercsv.cellprocessor.ift.CellProcessor; 
import org.supercsv.io.CsvMapReader; 
import org.supercsv.io.ICsvMapReader; 
import org.supercsv.prefs.CsvPreference; 

public class HowToReadACSVFile { 

private static final CsvPreference COLON_DELIMITED = new CsvPreference.Builder('"', ':', "\n").build(); 

private static CellProcessor[] getProcessors() { 
    final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // gamename 
        new NotNull(), // gamescore 
        new NotNull(), // minutestoplay 
    }; 
    return processors; 
} 

@Test 
public void read() throws Exception { 
    ICsvMapReader mapReader = null; 
    try { 
     mapReader = new CsvMapReader(new FileReader(
         Thread.currentThread().getContextClassLoader().getResource("stack47220687.txt").getPath()), 
         COLON_DELIMITED); 

     // the header columns are used as the keys to the Map 
     final String[] header = mapReader.getHeader(true); 
     final CellProcessor[] processors = getProcessors(); 

     Map<String, Object> oneRecordInAMap; 
     while ((oneRecordInAMap = mapReader.read(header, processors)) != null) { 
      System.out.println(String.format("lineNo=%s, rowNo=%s, this line stored in a map=%s", 
          mapReader.getLineNumber(), mapReader.getRowNumber(), oneRecordInAMap)); 
      /** 
      * oneRecordInAMap.get("Gamescore"); 
      */ 

     } 

    } finally { 
     if (mapReader != null) { 
      mapReader.close(); 
     } 
    } 
} 

} 

作品のようなものを使用スーパーcsvと2.4.0

<dependency> 
     <groupId>net.sf.supercsv</groupId> 
     <artifactId>super-csv</artifactId> 
     <version>2.4.0</version> 
    </dependency> 

とあなたのフォーマットが正しくない場合それはまた意味のあるエラーメッセージを提供します

lineNo=2, rowNo=2, this line stored in a map={ Gamescore= 120 , Gamename=Gameone , Minutestoplay= 1428 } 
lineNo=3, rowNo=3, this line stored in a map={ Gamescore= 20 , Gamename=Gametwo , Minutestoplay= 10 } 
lineNo=4, rowNo=4, this line stored in a map={ Gamescore= 90 , Gamename=Gamethree , Minutestoplay= 800 } 
lineNo=5, rowNo=5, this line stored in a map={ Gamescore= 190 , Gamename=Gamefour , Minutestoplay= 2001 } 
lineNo=6, rowNo=6, this line stored in a map={ Gamescore= 25 , Gamename=Gamefive , Minutestoplay= 80 } 
lineNo=7, rowNo=7, this line stored in a map={ Gamescore= 55 , Gamename=Gamesix , Minutestoplay= 862} 

を印刷します。

+0

提案していただきありがとうございますが、ファイルタイプは具体的には.txtファイルになりますので、その特定のライブラリではtxtファイルを開くことはできないようです。 – rxbert

+0

こんにちは、私は、正しい方向を指すべきであるいくつかの例のコードを提供します。 – jschnasse

+0

もちろん、txtファイルを読むことができます。 [CSVは実際にはプレーンテキストファイルです](https://en.wikipedia.org/wiki/Comma-separated_values)。既存のツールのおかげで、テーブルのような構造を扱う場合にも非常に便利な形式です。 – jschnasse