好。所以这是本学期的最后一个HW作业,我遗漏了该计划的一大部分,因为这是我唯一无法解决的问题。我正在设置我的FileInputStream并使用for循环将值读入数组,就像我过去做的那样没有问题。出于某种原因,我得到了这个例外并且无法解决这个问题。我已经看过围绕这个异常的大量其他线程,但同样,似乎无法弄明白。请停下来。
这是代码,它编译;
import java.util.*;
import java.io.*;
public class CollinDunn_1_10 {
// Declare constants
static final int MAX_EMPLOY = 30;
static final String TAB = "\t";
static final String NL = "\n";
static final double IRA_INVEST = .08;
static final double FEDERAL_WITH = .18;
static final double STATE_WITH = .045;
static final double SAVINGS = .10;
public static void main (String [] args) throws Exception {
// I/O String references
final String INPUT = "CollinDunn_1_10_Input.txt";
final String OUTPUT = "CollinDunn_1_10_Output.txt";
// Declare variables
// One-dimensional array for storing employee names
String [] names = new String [MAX_EMPLOY];
// Two-dimensional array for storing employee pay data
// [0] hours worked [1] pay rate [2] gross pay [3] net pay
// [4] savings amount [5] IRA amount [6] taxs withheld
double [][] payInfo = new double [MAX_EMPLOY][6];
// Set up I/O
FileInputStream inputDataFile = new FileInputStream(INPUT);
Scanner inputFile = new Scanner(inputDataFile);
FileWriter outputDataFile = new FileWriter(OUTPUT);
PrintWriter outputFile = new PrintWriter(outputDataFile);
// Read data from the file
readData(inputFile, payInfo, names);
// Test printing to see if values are stored - REMOVE
for (int i = 0; i < MAX_EMPLOY; i++) {
System.out.print(names[i] + TAB + payInfo[i][0] + TAB + payInfo[i][1]);
}
} // End main
// Method for reading file data into the file.
// Data is sorted as (number of hours) (pay rate) (name)
public static void readData (Scanner inputFile, double [][] payInfo, String [] names) {
for (int i = 0; i < MAX_EMPLOY; i++) {
payInfo [i][0] = inputFile.nextDouble();
payInfo [i][1] = inputFile.nextDouble();
names [i] = inputFile.nextLine();
} // End For
return;
} // End readData
} // End Class
*文本文件中的字段如下: (小时)(付费)(姓名)
50.00 10.60 Light Karen L
52.00 10.80 Fagan Bert Todd
62.00 12.24 Antrim Forrest N *
The Exception and stack trace:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at CollinDunn_1_10.readData(CollinDunn_1_10.java:56)
at CollinDunn_1_10.main(CollinDunn_1_10.java:42)
答案 0 :(得分:1)
在尝试检索之前,您永远不会检查是否有要检索的值(查找Scanner.hasNextDouble)。由于for循环经历了MAX_EMPLOY迭代,因此只要输入文件包含少于MAX_EMPLOY的数据行,就会发生此异常。
答案 1 :(得分:0)
您应该每次检查您的表格或文件是否包含正确数量的元素,或者它们是否很大。代码应如下所示:
<?php
function offer($items, $buyItems, $get) {
$offerType = $buyItems+1;
$x = $items;
rsort($x);
$y = count($x);
for($i=$y; $i> 0; $i -= $offerType ) {
$index = $i-1;
array_splice($x, $index, 1);
}
$arrlength = count($x);
for($z = 0; $z < $arrlength; $z++)
{
echo $x[$z];
echo "\n";
}
echo "Total = " . array_sum($x) . "\n";
}
offer(array(2, 5, 7,16, 6, 8, 40, 90), 2, 1);
?>
你不需要“回归”;在这种方法的最后因为这种方法没有任何回报。这是“无效”的方法。