我需要一点帮助。我有点希望我的输出显示the年的表格格式。

但是,即使我的程序确实起作用了,也不一定像图片中的那样出现。谁能告诉我如何工作?

这是我的输入:
2000年-2020年

这是我的输出(但在单独的JOptionPane弹出框中):
2000、2004、2008、2012、2016

这是我的代码:

    String enterYear = JOptionPane.showInputDialog(null, "Enter the starting year: \nExample: 2015");   // User enters an input (Year)
    String enterLastYear = JOptionPane.showInputDialog(null, "Enter the ending year: ");
    int i = Integer.parseInt(enterYear);
    int x = Integer.parseInt(enterLastYear);
    String output = "";

    if (i < x){
        for (i = Integer.parseInt(enterYear); i < x; i ++ ){
            if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {

                JOptionPane.showMessageDialog(null, i + "");
            }
        }
    } else {
        JOptionPane.showMessageDialog(null, "Error: Starting Year is greater than Ending Year!");
    }
  }
}

最佳答案

当前,由于您在showMessageDialog循环的每次运行中都调用for,因此您会为每个结果显示一个弹出窗口。

更改您的代码,以便在循环中创建带有所有“答案”的结果字符串,然后一次显示结果对话框。

另外,您已经解析了int值,并在循环之前将其分配给i,因此不要重复两次并将其保留在循环头之外。

if (i < x){
    //we use this variable to count the number of leap years that we already found
    int noOfResults = 0;
    String results = "";
    for (; i < x; i ++ ){ //i loops over the years
        //i is a leap year when this expression is true:
        if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
            //add the leap year to the result string:
            results += i + " ";
            //increase the number of found results by 1:
            noOfResults++;
            //for every 5th result, we add a line break to the result string
            // this is done with the % sign, the modulo operator
            // which returns the remainder of a division
            // meaning that everytime we loop through this, it is
            // checked if the remainder of noOfResults divided by 5 is zero
            if(noOfResults % 5 == 0){
                results += "\n";
            }
        }
    }
    JOptionPane.showMessageDialog(null, results);
}

关于java - 在单个对话框中显示两年之间的leap年数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28727272/

10-11 22:10
查看更多