java - 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.
解决方案
希望这会有所帮助:
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':递减它,并不断重复这些步骤)
推荐阅读
- python - Blender Python 打开具有特定大小并位于屏幕中心的浏览器
- node.js - 检索秘密 Firebase 服务帐户 json
- android - 活动加载时出现 UsbManager 错误
- flutter - 我想将颤振计时器输出转换为 MM:SS 格式
- c# - 从 C# MVC 中的 Redirect 获取 Cookie 信息
- html - 我在移动视图中看不到我的引导侧边栏
- amazon-web-services - 15 分钟后超过 Lambda 执行超时
- javascript - 如何从多选下拉列表中选择默认选项
- javascript - 关闭vs代码中的功能时如何关闭蓝线
- reactjs - Can I add variables of unknown name, but known types in type of TypeScript?