2017-03-04 22 views
0

テキストファイルから一連の実数を配列に読み込むJavaプログラムを作成しました。スキャナーが-1.0に達したときにファイルからの読み取りを停止するように、センチネルとして-1.0を使用したいと思います。Javaのセンチネル - テキストファイルを配列に読み込む

私は正しい位置にセンチネルを挿入するのに苦労していますが、if文またはwhile文でこれを行うべきかどうかもわかりません。すべてのヘルプははるかに高く評価:

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

public class CalculatingWeights { 

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

     //Create file and scanner objects 
     File inputFile = new File("in.txt"); 
     Scanner in = new Scanner(inputFile); 

     //declare variables 
     double [] myArray = new double [100]; 
     int i = 0; 
     double min = myArray[0]; 
     double max = myArray[0]; 

     //Read numbers from file, add to array and determine min/max values 
     while(in.hasNextDouble()) { 
      myArray[i] = in.nextDouble(); 
      if(myArray[i] < min) { 
       min = myArray[i]; 
      } 
      if(myArray[i] > max) { 
       max = myArray[i]; 
      } 
      i++; 
     } 

     //Calculate and print weighting 

     for(int index = 0; index < myArray.length; index++) { 
      double num = myArray[index]; 
      double weighting = (num - min)/(max - min); 
      System.out.printf("%8.4f %4.2f\n", num, weighting); 
     } 
    } 
} 

答えて

0

あなたのコードの使用この

double [] myArray = new double [100]; 
     int count = 0; 
     double min = myArray[0]; 
     double max = myArray[0]; 

     //Read numbers from file, add to array and determine min/max values 
     while(in.hasNextDouble()) { 
      myArray[count] = in.nextDouble(); 
      //sentinel 
      if(myArray[count]==-1.0) 
       break; 
      if(myArray[count] < min) { 
       min = myArray[count]; 
      } 
      if(myArray[count] > max) { 
       max = myArray[count]; 
      } 
      count++; 
     } 

     //Calculate and print weighting 

     for(int index = 0; index < count; index++) {//<-----NOTE HERE: as the array is filled upto "count" 
      double num = myArray[index]; 
      double weighting = (num - min)/(max - min); 
      System.out.printf("%8.4f %4.2f\n", num, weighting); 
     } 
の多くを変更することなく、
関連する問題