首页 > 解决方案 > 我应该如何构建这个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

样本输出

标签: javaif-statementwhile-loopnested-loops

解决方案


您在程序中几乎没有错误。

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

}

推荐阅读