當我運行我的代碼時,我得到了輸出兩次而不是一次。這是什麼原因?另外我怎樣才能輸出計算機猜測這個單詞的次數呢?這是當前的輸出:但是當我輸入一個單詞時,它會輸出兩次?雙輸出程序
Enter a 4 or 5 letter word and the computer will play hangman against you!
nice
Your word is: nice
Enter a 4 or 5 letter word and the computer will play hangman against you!
代碼
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);
}
}
}
與'JApplets'如何調用其'paint'方法有關。不要在那裏做輸入。 –
我該如何解決這個問題? – user3112609
不知怎的,你的'paint'方法調用兩次。簡單的解決方案使另一個類/方法進行輸入。 –