我的代码工作正常,除了我应该询问用户是否要退出程序的部分。这是一个简单的y / n,如果输入'n'则应该触发整个程序重复,并在输入'y'时终止。我知道我需要使用while循环,但我无法确切地知道我需要在代码中编写它以便它像预期的那样工作。
import java.util.*;
public class MilitaryTime
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
String answer = in.next();
while (answer != "n")
{
}
}
}
答案 0 :(得分:1)
你应该把你的代码分成(至少)两种不同的方法,但我只是想指出一种方法来实现你想要的最小变化:
public static void main (String [] args)
{
String answer = null; // you have no answer yet...
do { // ... but you want to execute your stuff at least once
Scanner in = new Scanner(System.in);
int hour1, minute1, hour2, minute2;
System.out.print("Please enter the first time: ");
int time1 = in.nextInt();
System.out.println();
hour1 = time1 / 100;
minute1 = time1 % 100;
System.out.print("Please enter the second time: ");
int time2 = in.nextInt();
System.out.println();
hour2 = time2 / 100;
minute2 = time2 % 100;
System.out.println("Time elapsed: " + (Math.abs(hour1 - hour2) + " Hours, " + (Math.abs(minute1 - minute2) + " Minutes \n")));
System.out.print("Do you want to quit? (y/n): ");
answer = in.next();
} while (!answer.equalsIgnoreCase("n"));
}
答案 1 :(得分:0)
在此之前重新运行主要方法。
while (answer.equals("n")) // comment by drewmoore; its helpfull for strings..
{
// you said, program should repeat if n is pressed.
// so, if answer is equal to n then execute the main function.
main();
}
这将执行,直到用户按下其他按钮。
其次,您不需要使用while
循环。这也可以使用if
来完成。