首页 > 解决方案 > 在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);

 }

}

我会在哪里写我的错误代码?我正在寻找有关在何处放置错误消息的进一步指导,不仅在我的代码中,而且还以供将来参考。谢谢!

标签: java

解决方案


也许像一些代码

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;
}

推荐阅读