所以我是 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();
}
如果您想要一些额外的消息
(如果输入不正确),请引入一个 boolean 值
boolean firstTime = true;
while (limit < 2) {
if (!firstTime) {
System.out.println ("Enter Below 2 ");
}
System.out.print("Enter Limit: ");
limit = scan.nextInt();
firstTime = false;
}
关于java - 在java代码中哪里实现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293710/