所以我正在做Usacogate的Greedy Gift Givers,并使用while循环检查文件中的下一行是否为null,具体为
while((tempName = sc.nextLine()) != null){
问题是,一旦它读取了最后一行并返回到顶部以检查是否有下一行,Java抛出NoSuchElementException而不是看到没有行并退出循环。所有其他部分都可以工作,代码会返回正确的答案。
如何解决此问题?
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(new File("gift1.in"));
int n = sc.nextInt();
System.out.printf("n is: %d\n", n);
String[] names = new String[10];
sc.nextLine();
int[] account = new int[10];
for (int i = 0; i < n; i++) {
names[i]=sc.nextLine().trim();
System.out.printf("current Name is: %s\n", names[i]);
account[i]=0;
}
String tempName;
while((tempName = sc.nextLine()) != null){
System.out.printf("tempName is: %s\n", tempName.trim());
int indexDummy = -1;
for (int j=0; (j< names.length); j++){
if (names[j].equals(tempName)) {
indexDummy = j;
break;
}
}
System.out.printf("indexDummy is: %d\n", indexDummy);
String nextLine = sc.nextLine();
System.out.printf("Next line is: %s\n", nextLine);
StringTokenizer st = new StringTokenizer(nextLine);
int int1 = Integer.parseInt(st.nextToken());
int int2 = Integer.parseInt(st.nextToken());
if(int2 == 0) {
for(int i=0; i<n;i++){
System.out.println(names[i]+" "+account[i] );
}
continue;
}
int quotient = int1 / int2;
int tempNum = int2 * quotient;
int remainder = int1-tempNum;
System.out.printf("quotient and remainder are: %d %d\n", quotient, remainder);
account[indexDummy]=account[indexDummy]+remainder-int1;//parsing the two numbers
System.out.println(indexDummy);
System.out.println(names[indexDummy]+" has "+account[indexDummy]);
for (int k=0;k < int2 ;k++){
tempName = sc.nextLine();
for (int j=0; j< names.length; j++){
if (names[j].equals(tempName.trim() ) ) {
//indexDummy2 = j;
account[j] =account[j]+ quotient;
System.out.printf("%s has balance %d\n", names[j], account[j]);
break;
}
} //sort out the output
}
//tempName = sc.next();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out")));
for(int i=0; i<n;i++){
out.println(names[i]+" "+account[i] );
}
for(int i=0; i<n;i++){
System.out.println(names[i]+" "+account[i] );
}
out.close();
System.exit(0);
}
}
答案 0 :(得分:2)
您可以使用Scanner.hasNextLine()
检查是否有更多输入。
while(sc.hasNextLine() && (tempName = sc.nextLine()) != null) {
或者:
while(sc.hasNextLine()) {
tempName = sc.nextLine(); //if you know it's not going to have a null as input
答案 1 :(得分:2)
这就是你应该使用扫描仪的方式
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
}
并且您可以安全地跳过空检查,因为nextLine()返回一个非空对象。