java - 在java代码中哪里实现错误信息
问题描述
所以我是 Java 编程的新手,对如何实现错误消息有点困惑。在我的代码中,当用户输入低于 2 的限制数时,我会给出一条错误消息,但无法弄清楚。
package test;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int limit = 0;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Limit: ");
limit = scan.nextInt();
System.out.println();
System.out.println("Sum of the even numbers between 2 and " + limit + " (inclusive) are:");
for (int count = 1; count <= limit; count++)
{
// Needed if ever even
if((count & 1)!= 1)
{
sum+=count;
System.out.println(count);
}
}
System.out.println("Total sum is " + sum);
}
}
我会在哪里写我的错误代码?我正在寻找有关在何处放置错误消息的进一步指导,不仅在我的代码中,而且还以供将来参考。谢谢!
解决方案
也许像一些代码
while (limit < 2) {
System.out.print("Enter Limit: ");
limit = scan.nextInt();
}
如果你想要一些额外message
的输入不正确,那么引入一个布尔值
boolean firstTime = true;
while (limit < 2) {
if (!firstTime) {
System.out.println ("Enter Below 2 ");
}
System.out.print("Enter Limit: ");
limit = scan.nextInt();
firstTime = false;
}
推荐阅读
- c# - 当 Windows 窗体自定义控件上的 AutoScroll=False 时,是否可以滚动长面板?
- php - 在 Symfony 4 中集成 VueJs,没有效果
- javascript - 未收到 POST 参数 Swagger3.0/OpenAPI
- python - 装饰器的 Django 主类
- reactjs - index.js:1375 警告:Material-UI:提供给 Tabs 组件的 `/` 值无效。所有 Tabs 子项都没有此值
- android - OpenCV 文档扫描算法
- python - ModuleNotFoundError:部署到 ElasticBeanstalk 时没有名为“django”的模块
- jsf - 如何从在深色背景上加载 gif 中删除边框?
- swift - Swift 5 从 CollectionView 中删除部分
- php - HTTP_REFFERER 不在 https 网站中显示参数