java.util.NoSuchElementException(运行时错误)

时间:2015-06-10 08:57:35

标签: java

当我将以下代码提交给codeforces.com(http://codeforces.com/problemset/problem/3/A)时:

import java.util.Scanner;
public class A3 {

public static void main(String[] args) {
    Scanner s=new Scanner(System.in).useDelimiter("");
    Scanner t=new Scanner(System.in).useDelimiter("");
    String a=s.next();
    int y=s.nextInt();
    int x = (int)a.charAt(0);
    String d=t.next();
    int fy=t.nextInt();
    int fx = (int)d.charAt(0);
    int n=0;
    if (Math.abs(fx-x)>Math.abs(fy-y))
    {
        n=Math.abs(fx-x);
    }
    else
    {
        n= Math.abs(fy-y);
    }
    System.out.printf("%d\n",n);
    for (int counter=1;counter<=n;++counter)
    {
        if (fx<x)
        {
            System.out.printf("L");
            x--;
        }
        else if (fx>x)
        {
            System.out.printf("R");
            x++;
        }
        if (fy<y)
        {
            System.out.printf("D");
            y--;
        }
        else if (fy>y)
        {
            System.out.printf("U");
        }
        System.out.println();
    }
    s.close();
    t.close();

  }
}

,它说没有找到这样的元素,尽管它在Eclipse和JCreator IDE中运行得很好。那么有人能让我知道我做错了吗?提前致谢 :) 完整的错误代码:

java.util.NoSuchElementException

at java.util.Scanner.throwFor(Scanner.java:862)

at java.util.Scanner.next(Scanner.java:1371)

at A3.main(A3.java:10)

1 个答案:

答案 0 :(得分:1)

您想读取两行输入,我相信您可以使用 BufferedReader StringTokenizer

代替以下代码:

Scanner s=new Scanner(System.in).useDelimiter("");
Scanner t=new Scanner(System.in).useDelimiter("");
String a=s.next();
int y=s.nextInt();
int x = (int)a.charAt(0);
String d=t.next();
int fy=t.nextInt();
int fx = (int)d.charAt(0);

您可以使用以下内容:

BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer str = new StringTokenizer(br.readLine());
String a = str.nextToken();
int y = Integer.parseInt(str.nextToken);
int x = (int)a.charAt(0);//same as earlier

str = new StringTokenizer(br.readLine());
String d = str.nextToken();
int fy = Integer.parseInt(str.nextToken);
int fx = (int)d.charAt(0);//same as earlier

这应该足以满足您的需求,而且与Scanner相比,它速度更快。 您可以查看this文章,它展示了使用Java读取输入内容的不同方法,还告诉您哪种方法在速度方面更好: