【发布时间】:2019-05-30 10:00:23
【问题描述】:
我正在尝试(只是为了让电影分级更容易一些;将您要添加的电影与列表中的所有其他电影进行比较以了解它的适合位置很难,而且效率不高)一个类似于binary insertion sort 的程序,可以按正确的顺序将电影添加到其他电影列表中。在确定电影应该去的列表中的位置的部分中,我收到一个错误
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Rater.binarySearch(Rater.java:32)
at Rater.main(Rater.java:24)
我不确定是什么原因造成的。代码如下:
import java.awt.List;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Rater
{
public static void main(String[] args)throws Exception
{
File file = new File("E:\\topmovies.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
ArrayList<String> movList = new ArrayList<String>();
while ((st = br.readLine()) != null) {
movList.add(st);
}
br.close();
while(true) {
System.out.println("Enter a movie to add.");
Scanner myObj = new Scanner(System.in);
String userName = myObj.nextLine();
myObj.close();
int index = binarySearch(movList, userName, 0, movList.size()-1);
movList.add(index, userName);
}
}
static int binarySearch(ArrayList<String> a, String item, int low, int high)
{
Scanner myObj3 = new Scanner(System.in);
if (high <= low) {
System.out.println("Did you like " + item + " more than " + a.get(low) + "?");
String answer2 = myObj3.nextLine().toLowerCase();
myObj3.close();
if(answer2.equals("yes")) {
return low + 1;
}
return low;
}
int mid = (low + high)/2;
if(item == a.get(mid)) {
myObj3.close();
return mid+1;
}
System.out.println("Did you like " + item + " more than " + a.get(mid) + "?");
String answer2 = "";
if(myObj3.hasNextLine()){
answer2 = myObj3.nextLine().toLowerCase();
}
myObj3.close();
if(answer2.equals("yes")) {
return binarySearch(a, item, mid+1, high);
}
return binarySearch(a, item, low, mid-1);
}
}
请忽略错误的命名约定,以及这可能还没有达到应有的效果。现在我只是想修复这个扫描仪不工作。
【问题讨论】:
-
你能尝试只创建一个扫描器(并传递它)吗?
标签: java java.util.scanner binary-tree binary-search-tree binary-search