java - 我应该如何构建这个while循环?(JAVA)
问题描述
Java新手。当用户输入为'Y'时,我应该如何构造这个while循环以重新进入循环?while 应该在一开始就去吗?输出示例如下代码。
import java.util.Scanner;
public class RamosSLE33 {
public static void main(String[] args) {
char cont = 'Y';
String anniversaryGift = " ";
int year = 0;
Scanner input = new Scanner(System.in);
System.out.printf("ANNIVERSARY YEAR%n%n1. 50%n2. 55%n3. 60%n4. None of the above."
+ "%n%nSelect the anniversary year: ");
year = input.nextInt();
if (year == 1)
System.out.printf("The anniversary gift is gold.");
if (year == 2)
System.out.printf("The anniversary gift is emerald.");
if (year == 3)
System.out.printf("The anniversary gift is diamond.");
if (year == 4)
System.out.printf("Go to www.bernardine.com/jewelry-anniv.htm#traditional for more gift choices.");
cont = 'N';
while(Character.toUpperCase(cont) == 'Y') {
System.out.printf("%nSearch for another anniversary gift? Enter 'Y' or 'N': ");
cont = input.nextLine().charAt(0);
} // End while == Y
} //End main()
} //End class RamosSLE33
解决方案
您在程序中几乎没有错误。
您的 while 循环不会重复运行整个程序
扫描仪输入可能是资源泄漏,因此您尚未关闭它。
请参考以下更正后的程序
public class RamosSLE33 {
public static void main(String[] args) {
char cont = 'Y';
int year = 0;
Scanner input = new Scanner(System.in);
while (Character.toUpperCase(cont) == 'Y') {
System.out.printf("ANNIVERSARY YEAR%n%n1. 50%n2. 55%n3. 60%n4. None of the above."
+ "%n%nSelect the anniversary year: ");
year = input.nextInt();
if (year == 1) {
System.out.printf("The anniversary gift is gold.");
} else if (year == 2) {
System.out.printf("The anniversary gift is emerald.");
} else if (year == 3) {
System.out.printf("The anniversary gift is diamond.");
} else if (year == 4) {
System.out.printf("Go to www.bernardine.com/jewelry-anniv.htm#traditional for more gift choices.");
} else {
System.out.printf("An invalid Input Number");
}
cont = 'N';
System.out.printf("%nSearch for another anniversary gift? Enter 'Y' or 'N': ");
cont = input.next(".").charAt(0);
} // End while == Y
input.close();
System.out.printf("%n The progrm ends: ");
} // End main()
}
推荐阅读
- go - 使用来自 BSON 的 oneof 反序列化 proto 失败
- python - 用正则表达式替换重复出现的子字符串?
- c - 如何将浮点变量存储到 int 数组(C)?
- c++ - 在“使用 DWM 的自定义窗口框架”之后努力创建功能性自定义 Windows 10 框架装饰
- excel - 相关下拉+固定公式和计算
- python - 执行 Python 脚本以从 Web 服务器控制 GPIO
- java - 我想使用 spring boot 创建消息应用程序
- javascript - 当 fetch 返回 404 时替换 img url
- r - 使用 dplyr 为不同的组选择不同数量的 top_n
- validation - Keras 回调 on_epoch_end 抛出错误(Nonetype 没有 len())