这是我的代码:
colSum2
代码要求输入一个名称,然后在文件中搜索该名称,然后在另一个窗口中显示排名。
文件格式如下:
当我运行代码时,它没有给我这样的元素异常。
完整的错误消息:
import java.awt.*;
import java.util.*;
import java.io.*;
public class BabyNames
{
public static int decades = 11;
public static void main (String [] args) throws FileNotFoundException
{
DrawingPanel panel = new DrawingPanel(550,560);
Graphics g = panel.getGraphics();
panel.setBackground(Color.WHITE);
String line = search();
graph(g,line);
}
public static String search() throws FileNotFoundException
{
Scanner util = new Scanner(new File("names.txt"));
String line = "";
String requestedName = name();
String rankings = "";
String rank = "";
while (util.hasNextLine())
{
line = util.nextLine();
Scanner tracer = new Scanner(line);
String name = tracer.next();
if (name.equalsIgnoreCase(requestedName))
{
for (int x =1;x<=decades;x++)
{
rank = tracer.next();
rankings+=rank+" ";
}
}
if (!util.hasNextLine())
{
System.out.print("no data");
break;
}
}
return rankings;
}
public static String name()
{
String requestName = "";
Scanner console = new Scanner(System.in);
System.out.println("Type a name: ");
requestName = console.next();
return requestName;
}
public static void graph(Graphics g,String rankings)
{
g.setColor(Color.YELLOW);
g.fillRect(0,0,550,30);
g.fillRect(0,530,550,30);
g.setColor(Color.LIGHT_GRAY);
for (int x = 0; x <= 11;x++)
{
g.drawLine(0+50*x,30,0+50*x,530);
}
for (int x = 0;x<=10;x++)
{
g.drawLine(0,30+50*x,550,30+50*x);
}
Scanner console = new Scanner(rankings);
g.setColor(Color.RED);
int position = 0;
int firstRank = console.nextInt();
int position2 = firstRank/2+30;
for (int x = 0; x<=decades-1;x++)
{
int rank = console.nextInt();
if (rank==0)
{
position=530;
}
else
{
position = rank/2+30;
}
g.drawLine(0+x*50-50,position2,0+x*50,position);
position2 = position;
}
}
}
答案 0 :(得分:0)
查看您的代码:
在第二次您这样做:
在第3次操作中:
List<Integer>
而不是String[] {1, 2, 3}
)使用后请不要忘记关闭 Scanner
,这可能会带来问题。
public static void main(String[] args) throws IOException {
List<Integer> rankings = getRankings(Paths.get("d:/names.txt"));
}
public static List<Integer> getRankings(Path path) throws IOException {
return getNameRankings(getName(), path);
}
private static String getName() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Type a name: ");
return scan.next();
}
}
private static List<Integer> getNameRankings(String name, Path path) throws IOException {
String[] data = Files.lines(path)
.map(String::trim)
.map(line -> line.split("\\s+"))
.filter(parts -> parts[0].equalsIgnoreCase(name))
.findFirst()
.orElse(null);
if (data == null)
return Collections.emptyList();
return IntStream.range(1, data.length)
.map(i -> Integer.parseInt(data[i]))
.boxed()
.collect(Collectors.toList());
}