gpt4 book ai didi

java - 程序中的双输出

转载 作者:行者123 更新时间:2023-12-02 06:24:41 24 4
gpt4 key购买 nike

当我运行代码时,我得到两次输出,而不是一次。这是什么原因造成的?另外,我如何输出计算机猜测单词所需的次数?这是当前的输出:但是当我输入一个单词时,它会输出两次?

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

}

}

最佳答案

不要在基于 GUI 的应用程序中使用控制台输入。应通过使用一个或多个可用的 UI 控件来获取用户输入。

Swing 中的绘制可能因多种原因而发生,其中许多原因是您无法控制的,这意味着每当 Swing 想要更新您的 UI 时,它都会调用 Paint,这意味着您会不断被要求提供新的 UI词

此外,您正在阻止绘制过程,这意味着在您绘制方法退出之前,不太可能绘制任何内容

首先查看 How to create a GUI with Swing并且,当您了解这一点时,Performing Custom Painting

关于java - 程序中的双输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com