gpt4 book ai didi

java - 如何重复整个程序直到手动终止?

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

我的代码工作正常,除了我应该询问用户是否要退出程序的部分。这是一个简单的 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")
{

}

}

}

最佳答案

您可能应该将代码拆分为(至少)两种不同的方法,但我只是尝试指出一种通过最少的更改来实现您想要的效果的方法:

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

}

关于java - 如何重复整个程序直到手动终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24355735/

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