java 如何在if/if else语句中使用System.out.println()停止双重打印?

chhqkbe1  于 8个月前  发布在  Java
关注(0)|答案(1)|浏览(61)

我对编程和学习Java作为在线课程的一部分是相当陌生的。
我已经得到了许多不同的编码练习,其中一个应该是相对简单的,我打印出两个语句(“对不起,再试一次”或“赢!”)取决于两个不同的数字6面骰子匹配。
问题是,无论出于什么原因,两个语句都被打印出来,即使只有一个应该出现(两个“对不起,再试一次“或“对不起,再试一次”,然后是“赢!”如果数字匹配,我已经附上了一个细节截图。
你知道为什么会发生这种情况吗?下面的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DiceRoll extends JPanel
{
    private int firstDice;      // to hold the value for the first dice
    private int secondDice;     // to hold the value for the second dice
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        firstDice  = (int) (Math.random() * 6) + 1; // get a value for the first dice
        secondDice = (int) (Math.random() * 6) + 1; //get a value for the second dice
        // draw the dice squares
        g.setColor(Color.blue);
        g.fillRect(20, 20, 60, 60);
        g.setColor(Color.magenta);
        g.fillRect(120, 20, 60, 60);
        // put the values on the dice
        g.setColor(Color.white);
        g.drawString(" " + firstDice, 43, 54);
        g.drawString(" " + secondDice, 143, 54);
        // write the values under the dice
        g.setColor(Color.black);
        g.drawString("First dice = " + firstDice, 20, 100); 
        g.drawString("Second Dice = " + secondDice, 120, 100); // print out the dice values
        
        
        
        if (firstDice != secondDice) 
        {
            System.out.println("Sorry, try again");
        }
        else if (firstDice == secondDice) 
        {
            System.out.println("Win!");
        }
   }
}

字符串
我在网上查过解决方案,根据我所读到的,它应该是正确的。感觉我在这里错过了一些明显的东西。

4nkexdtk

4nkexdtk1#

掷骰子操作不应在paintComponent方法中,因为您无法控制系统如何调用此paintComponent。请将掷骰子操作放入main()中,然后重试。

相关问题