2017-03-04 1 views
0

J'ai écrit un programme Java qui lit une série de nombres réels d'un fichier texte dans un tableau. Je voudrais utiliser -1.0 comme sentinelle pour que le scanner arrête de lire le fichier quand il atteint -1.0.Java sentinel - lecture de fichier texte dans le tableau

J'ai du mal à insérer la sentinelle dans la position correcte, et je ne sais pas non plus si cela devrait être fait avec une instruction if ou while. Toute aide appréciée:

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); 
     } 
    } 
} 

Répondre

0

sans changer beaucoup de votre utilisation de code ce

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); 
     }