首页 > 解决方案 > 4.23 Lab countdown until matching digits in Java

问题描述

So i have this lab and i kept getting 9 out of ten correct. I ended up changing my original code to this very wacky version to accommodate the extra point. The question is:

Write a program that takes in an integer in the range 20-98 as input. The output is a countdown starting from the integer, and stopping when both output digits are identical.

my code:

import java.util.Scanner;
public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int userDigit;
      int newDigit;

      userDigit = scnr.nextInt();

      newDigit = userDigit - 1;

      if ((userDigit > 19) && (userDigit < 99)) {
         System.out.print(userDigit + " ");

      }
      else {
         System.out.println("Input must be 20-98");
      }


      while ((userDigit > 19) && (userDigit < 99) && (newDigit % 11 != 0)) {
         if (userDigit % 11 == 0) {
            System.out.println();
            break;
         }
         System.out.print(newDigit + " ");
         --newDigit;

         if (newDigit % 11 == 0) {
            System.out.println(newDigit + " ");
            break;
         }
      }


   }
}

Can someone please tell me if i over thought this and if there was an easier way to format the for loop without having all the "ifs". I am new at this and have been taking the class for 4 weeks now. Any suggestions would be greatly appreciated. I know there was probably some way to use another method, but the instructions stated to use a "while" loop.

标签: javaloopswhile-loop

解决方案


希望这会有所帮助:

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    int userDigit = scnr.nextInt();
    scnr.close();

    if ((userDigit <= 19) || (userDigit >= 99))
        System.out.println("Input must be 20-98");

    do {
        System.out.println(userDigit + " ");
        if (userDigit % 11 == 0)
            break;

        --userDigit;

    } while ((userDigit > 19));
}

由于userDigit不需要再次使用的原始值,newDigit因此可以跳过额外的变量。

此外,如果需要 while 循环,那么考虑 do-while 可以帮助首先打印初始输入,这可以帮助跳过后续的冗余检查。

之后,您可以简单地对原始值进行操作userDigit(检查当前值是否可以除以 11;'yes':跳出 while 循环,'no':递减它,并不断重复这些步骤)


推荐阅读