以下是我的代码......我正在尝试制作一个倒数计时器。现在它在按正确的顺序倒计时方面正常工作。我试图弄清楚如何在代码中放置一个if语句,以便打印1分钟和'秒,而不是1分钟和'秒'
import java.util.Scanner;
public class countdown {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minutes;
System.out.println("Please enter the timer countdown in minutes:");
minutes = scan.nextInt();
while (minutes < 1) {
System.out.print("Invalid entry: Enter 1 or more minutes: ");
minutes = scan.nextInt();
}
for (int i = minutes - 1; i >= 0; i--)
{
for (int s = 59; s >= 1; s--)
System.out.println(i + " minutes, " + s + " seconds");
System.out.println("The timer is done!");
}
}
}
答案 0 :(得分:1)
像这样,
String minutes = i + (i > 1 ? " minutes" : " minute"); // put this line in outer loop
String seconds = s + (s > 1 ? " seconds" : " second"); // and this line in inner loop
System.out.println(minutes +", "+ seconds);
答案 1 :(得分:0)
只需在其中添加if / else语句:
for (int i = minutes - 1; i >= 0; i--){
String minute;
if(minutes == 1)
minute = " minute ";
else
minute = " minutes ";
for (int s = 59; s >= 1; s--){
String seconds;
if(s == 1)
seconds = " second";
else
seconds = " second";
System.out.println(i + minute + s + seconds);
}
}
另一个答案可能更好,但它使用不同的语法,使所有这些代码成为一个短线。他们做的基本相同。
答案 2 :(得分:0)
这两个if / else语句应该有效。
for (int s = 59; s >= 1; s--)
{
if (i == 1)
System.out.print(i + " minute, ");
else
System.out.print(i + " minutes, ");
if (s == 1)
System.out.println(s + " second");
else
System.out.println(s + " seconds");
}