2017-09-22 3 views
0

列の数を誤ってカウントするコードに問題があります。私は、テキストファイルから、私が行列の次元として持つべきものに関する情報を読む必要がありますが、私はその列に問題があるようです。最初の桁は、行列の行数です。入力ファイルには何行と列を配列に設定する

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

public class Test { 

    public static void main(String[] args) throws FileNotFoundException { 

     File f = new File("testwork.txt"); 
     Scanner in = new Scanner(f); 
     int numRows = in.nextInt(); 

     ArrayList<Integer> columnCheck = new ArrayList<Integer>(); 

     while (in.hasNextLine()) { 
     columnCheck.add(in.nextInt()); 
     break; 
     } 

     int numColumns = columnCheck.size(); 

     System.out.println(numRows, numColumns); 
     in.close(); 
    } 

} 

私はこのコードから取得した出力が3である(行数)12(:ここ

3 
8 5 -6 7 
-19 5 17 32 
3 9 2 54 

は、情報を決定するコードです列の数)。明らかにこれは間違っており、whileループはループ内の数字の数を確認するために繰り返されますが、修正方法を理解することはできません。プログラムを4列だけにするには、whileループを変更する必要がありますか?

+0

を確認することができません:numColumnsのをあなたは破るため、1であります – Anona112

答えて

0

は、私は問題がhasNextLineは、()ではなく1行のすべての数字を読んでいる理由である「\ n」はキーを入力の上に読み込むこと。かもしれ信じる

while (in.hasNext()) {...} 

を使用してみてくださいテキストファイルの次の行に移動するためには、行が完了した後にin.hasNextLine()を使用して別のチェックが必要です。

1

これは、あなたが実際に

public static void main(String[] args) throws FileNotFoundException { 
    File f = new File("testwork.txt"); 
    Scanner in = new Scanner(f); 
    int numRows = in.nextInt(); 

    ArrayList<Integer> columnCheck = new ArrayList<Integer>(); 
    int numColumns = 0; 

    while (in.hasNextLine()) { 
     Scanner s2 = new Scanner(in.nextLine()); 
     numColumns++; 

     while (s2.hasNextInt()) { 
      columnCheck.add(s2.nextInt()); 
     } 
    } 

    System.out.println(numRows, numColumns); 
    in.close(); 
} 
0

このwhileループを達成しようとしているものでは間違っている:

while (in.hasNextLine()) { 
    columnCheck.add(in.nextInt()); 
    break; 
} 

まずラインを取得し、ArrayListの中の各整数を格納します。

このようにそれを実行します。

while (in.hasNextLine()) { 
    String column = in.nextLine(); 
    String columnArr[] = column.split("\\s+"); // split it by space 
    System.out.println("Column Numbers:" + columnArr.length()); 
    break; 
} 
関連する問題