我编写了一个Java程序,它将一系列实数从文本文件读入数组。我想使用-1.0作为标记,以便扫描程序在达到-1.0时停止从文件读取。
我正在努力将哨兵插入正确的位置,并且也不确定是否应该使用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 :(得分: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);
}