gpt4 book ai didi

java - 我应该如何构造这个 while 循环? (JAVA)

转载 作者:行者123 更新时间:2023-12-01 19:34:42 25 4
gpt4 key购买 nike

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

SAMPLE OUTPUT

最佳答案

程序中几乎没有错误。

  1. 您的 while 循环不会重复运行整个程序

  2. 扫描仪输入可能是资源泄漏,因此您尚未关闭它。

更正后的程序请引用如下

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()

}

关于java - 我应该如何构造这个 while 循环? (JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262978/

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