是什么导致没有这样的元素例外

时间:2013-12-18 18:32:50

标签: java exception crash logic conditional

在我的代码中,当我输入一个单词时,我得到一个没有这样的元素异常。它确实输出正确的单词和刽子手,但它也会在这样做后崩溃。造成这种情况的原因是什么?我该怎么办? 这是错误的开始:

Exception in thread "AWT-EventQueue-1" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Hangman.paint(Hangman.java:50)
    at javax.swing.RepaintManager$3.run(Unknown Source)
    at javax.swing.RepaintManager$3.run(Unknown Source) 

同样难以修改我的代码,以便每次计算机猜测它都会绘制一部分刽子手,而不是全部出现在执行程序时?

import java.util.Scanner;
import javax.swing.JApplet;
import java.awt.*;

public class Hangman extends JApplet
{
    public void paint (Graphics Page)
    {
                //gallows
                Page.drawLine(0,300,20,300);
                Page.drawLine(10,40,10,300);
                Page.drawLine(10,40,80,40);
                Page.drawLine(80,40,80,55);

                //torso
                Page.drawOval(50,55,50,55);
                Page.drawOval(50,100,50,100);
                //left arm and hand
                Page.drawLine(50,150,40,110);
                Page.drawLine(40,110, 45,100);
                Page.drawLine(40,110, 25,100);
                Page.drawLine(40,110, 25,115);


                //right arm and hand
                Page.drawLine(100,150,120,110);
                Page.drawLine(120,110, 115,95);
                Page.drawLine(120,110, 125,95);
                Page.drawLine(120,110, 135,115);

                //left  leg and foot
                Page.drawLine(80,200,100,250);
                Page.drawLine(100,250, 115,260);


                //right leg and foot
                Page.drawLine(75,200,60,250);
                Page.drawLine(60,250,45,260);




     Scanner in = new Scanner(System.in);
     System.out.println("Enter a 4 or 5 letter word and the computer will play hangman against you!");
     String word = in.nextLine();


     char[] letter = word.toCharArray();


     for (int i = 0; i < letter.length; i++) {
             letter[i] = 'a';
     }


     for (int i = 0; i < word.length(); i++){
         for (int j = 48; j < 122; j++) {

                     if (letter[i] == word.charAt(i)) { 
                             break; 
                     } else {
                             letter[i] = (char)((int) j + 1);
                     }
             }
     }
     System.out.println("Your word is: ");

     for (char letters : letter) {
             System.out.print(letters);
     }
     in.close();
}

}

2 个答案:

答案 0 :(得分:1)

in方法中关闭paint。它会关闭底层流,下一次尝试从中读取会产生错误。

关闭与Scanner相关联的System.in对象几乎不是一个好主意。

来自the docs:“当扫描仪关闭时,如果源实现了Closeable接口,它将关闭其输入源。”

答案 1 :(得分:0)

在执行in.nextLine之前,请尝试检查是否有下一行。

while(in.hasNextLine())
{
    word = in.nextline();
}

问题是你正在调用nextLine()并且在没有行时抛出异常,试着看看javadoc:

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html