In my code I am getting a no such element exception when I enter a word. It does output the word correctly and the hangman, but it also crashses after doing so. What is causing this and how could I fix it? Here is the start of the error:
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)
Also would it be hard to modify my code so that each time the computer guesses it draws one part of the hangman instead of it all appearing upon executing the program?
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();
}
}
Do not close
in
inside yourpaint
method. It closes the underlying stream and the next attempt to read from it produces the error.It's hardly ever a good idea to close
Scanner
object associated withSystem.in
.From the docs: "When a Scanner is closed, it will close its input source if the source implements the Closeable interface."
Try checking to see if there is a next line before doing in.nextLine.
The problem is that you are calling nextLine() and it's throwing an exception when there's no line, try looking at the javadoc:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html