首页 > 解决方案 > 我的 babyname 函数没有此类元素异常

问题描述

这是我的代码:

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;
        }
    }

}

该代码要求输入名称,然后在文件中搜索该名称,然后在另一个窗口中绘制排名图。

该文件的格式如下:

在此处输入图像描述

当我运行我的代码时,它没有给我一个这样的元素异常。

完整的错误信息:

java.util.NoSuchElementException at
java.util.Scanner.throwFor(Scanner.java:862) at 
java.util.Scanner.next(Scanner.java:1485) at 
java.util.Scanner.nextInt(Scanner.java:2117) at 
java.util.Scanner.nextInt(Scanner.java:2076) at 
BabyNames.graph(BabyNames.java:75) at 
BabyNames.main(BabyNames.java:13)

标签: javanosuchelementexception

解决方案


看看你的代码:

  1. 作为用户输入名称
  2. 查看给定文件并找到以给定名称开头的行并返回其排名
  3. 在 UI 上显示此排名

在第二你做:

  1. 查找具有给定名称的字符串
  2. 分别读取所有整数并用它构建一个字符串(为什么不从文件中读取整个字符串)
  3. 将此字符串检索回调用方。

在第三你做:

  1. 接受给定的字符串
  2. 将此字符串拆分为单独的整数(同样,为什么不接受List<Integer>而不是String[] {1, 2, 3}
  3. 在 UI 上显示整数

使用后不要忘记关闭 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());
}

推荐阅读